我正在查看我找到的这段代码,但我无法弄清楚如何打印获胜者。本质上,我正在尝试生成一个遗传算法,该算法将生成一个 N 个数字,总和为 X。这个问题在 Lethian 上得到了解决:http: //lethain.com/genetic-algorithms-cool-name-该死的简单/ 但我似乎无法弄清楚如何打印进化的结果。
下面是一些示例代码:
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
任何帮助将非常感激!