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)
遺伝的アルゴリズムの部分(クロスオーバー/突然変異)を実際に理解するのに苦労しています。数字をランダムにペアにしてから、ペアをランダムに選択し、1 つのペアをそのままにして、ランダムなポイントでクロスオーバーする必要があります。その後、人口全体から 1 ビットをランダムに変異させて終了します。crossover と mutate の現在のコードは、私が見つけて理解しようとしていた遺伝的アルゴリズムの例から取ったものです。どんな助けでも大歓迎です。