Я просматриваю этот код, который я нашел, и я не могу разобраться, как печатать победившего человека. По существу, я пытаюсь создать генетический алгоритм, который будет генерировать индивидуум из N чисел, суммируемых на общую сумму X. Этот вопрос был рассмотрен на Lethian: http://lethain.com/genetic-algorithms-cool-name-damn-simple/ Но я не могу понять, как напечатать человека, который является результатом эволюции.печать победившего человека из генетического алгоритма?
Heres пример кода:
from random import randint, random
from operator import add
target = 5 #this defines the target number we are trying to reach
p_count = 100 #this defines the number of individuals available to mutate for the desired result
i_length = 6 #this defines the length of each individual, the number of intergers in it
i_min = 0 #this defines the minimum value of an integer in the individual
i_max = 100 #this defines the maximum value of an integer in the individual
def individual(length, min, max):
return [ randint(min,max) for x in xrange(length) ] #Creates an individual. Defines an individual by the number of numbers contained in it and their min/max
def population(count, length, min, max):
return [ individual(length, min, max) for x in xrange(count) ] #Creates population from individuals. This sets the number of individuals in the population (count), the number of numbers in each individual (length), and the min and max numbers for the individual
def fitness(individual, target):
sum = reduce(add, individual, 0)
return abs(target-sum) #determines the fitness. does this by adding the indivduals numbers together, and taking that value from the target value
def grade(pop, target):
summed = reduce(add, (fitness(x, target) for x in pop))
return summed/(len(pop) * 1.0) #This returns an average fitness to compare populations to.
def evolve(pop, target, retain=0.2, random_select=0.05, mutate=0.01): #This evolves a population, retaining 20%, randomly selecting 5% so it doesnt get stuck/lose variance, and mutates 1%.
graded = [ (fitness(x, target), x) for x in pop]
graded = [ x[1] for x in sorted(graded)]
retain_length = int(len(graded)*retain)
parents = graded[:retain_length]
for individual in graded[retain_length:]:
if random_select > random():
parents.append(individual)
for individual in parents:
if mutate > random():
pos_to_mutate = randint(0, len(individual)-1)
individual[pos_to_mutate] = randint(
min(individual), max(individual))
parents_length = len(parents)
desired_length = len(pop) - parents_length
children = []
while len(children) < desired_length:
male = randint(0, parents_length-1)
female = randint(0, parents_length-1)
if male != female:
male = parents[male]
female = parents[female]
half = int(len(male)/2)
child = male[:half] + female[half:]
children.append(child)
parents.extend(children)
return parents
Любая помощь будет высоко ценится!
Алгоритм эволюционируют не дает вам индивидуум, он дает вам население –
Ваш фрагмент кода содержит только вспомогательные функции, алгоритм отсутствует ... Вы начнете с популяции (вызывая «население»), а затем развивая это несколько раз (вызывая 'evolve') , В какой-то момент вы, вероятно, выберете лучшего человека в населении. –
Похоже, вам придется неоднократно называть 'evolve()', а затем проверить, не достиг ли какой-либо человек в населении цели –