我被要求制作一个遗传算法,目标是确定一个 1 和 0 最多的 8 位字符串。eval 函数应该返回更改的数量加 1。例如,00000000 返回 1,00011100 返回 3,01100101 返回 6。这就是我所拥有的:
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)
我实际上无法弄清楚遗传算法部分(交叉/突变)。我应该随机配对数字,然后随机选择一对,让一对保持不变,然后在随机点交叉。然后它将通过随机突变整个种群中的一位而结束。当前的交叉和变异代码取自我发现并试图理解的遗传算法示例。欢迎任何帮助。