二进制数的Python遗传算法
我被要求做一个遗传算法,目标是确定一个8位的字符串,最多有1个和0个。eval函数应返回更改数加1。例如00000000返回10011100返回3,01100101返回6。这就是我所拥有的:二进制数的Python遗传算法,python,genetic-algorithm,Python,Genetic Algorithm,我被要求做一个遗传算法,目标是确定一个8位的字符串,最多有1个和0个。eval函数应返回更改数加1。例如00000000返回10011100返回3,01100101返回6。这就是我所拥有的: def random_population(): from random import choice pop = ''.join(choice(('0','1')) for _ in range(8)) return pop def mutate(dna):
def random_population():
from random import choice
pop = ''.join(choice(('0','1')) for _ in range(8))
return pop
def mutate(dna):
""" For each gene in the DNA, there is a 1/mutation_chance chance
that it will be switched out with a random character. This ensures
diversity in the population, and ensures that is difficult to get stuck in
local minima. """
dna_out = ""
mutation_chance = 100
for c in xrange(DNA_SIZE):
if int(random.random()*mutation_chance) == 1:
dna_out += random_char()
else:
dna_out += dna[c] return dna_out
def crossover(dna1, dna2):
""" Slices both dna1 and dna2 into two parts at a random index within their
length and merges them. Both keep their initial sublist up to the crossover
index, but their ends are swapped. """
pos = int(random.random()*DNA_SIZE)
return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])
def eval(dna):
changes = 0
for index, bit in enumerate(dna):
if(index == 0):
prev = bit
else:
if(bit != prev):
changes += 1
prev = bit
return changes+1
#============== End Functions =======================#
#============== Main ================# changes = 0
prev = 0
dna = random_population()
print "dna: "
print dna
print eval(dna)
我很难真正理解遗传算法的部分(交叉/变异)。我应该随机配对数字,然后随机选择一对,让一对保持不变,然后在一个随机点交叉。然后,它将通过在整个种群中随机变异一位来结束。当前的交叉和变异代码只是从我发现的一个遗传算法示例中提取出来的,我正试图理解它。欢迎任何帮助。我建议的一部分: 代码不起作用,但它可能传输信息
# a population consists of many individuals
def random_population(population_size = 10):
from random import choice
pop = [''.join(choice(('0','1')) for _ in range(8)) for i in range(population_size)]
return pop
# you need a fitness function
def fitness(individual):
return # a value from 0 up
def algorithm():
# a simple algorithm somehow alike
# create population
population = random_population()
# this loop must stop after some rounds because the best result may never be reached
while goal_not_reached(population) and not time_is_up():
# create the roulette wheel
roulette_wheel = map(fitness, population)
# highest value of roulette wheel
max_value = sum(roulette_wheel)
# the new generation
new_population = []
for i in range(len(population) - len(new_population)):
# create children from the population
# choose 2 random values from 0 to max_value and find the individuals
# for it in the roulette wheel, combine them to new individuals
new_population.append(new_individual)
# mutate the population
population = map(mutate, new_population) # a new generation is created
我发现我喜欢做的一件事是:
编辑:哦,天哪,这是四月份问的。很抱歉挖坟墓。一个群体由许多个体组成——我只看到一个“dna”。交叉有助于基因“子程序”的收敛,变异有助于产生达到目标所需的错误。此外,你需要一个适应力函数,确定个体交叉和重组的可能性。你可以使用轮盘赌来决定哪些人可以交叉创造下一代的孩子。