我被要求制定一個遺傳算法的目標,以確定一個8位字符串與最1和0的。 eval函數將返回改變的1數加上所以,例如00000000返回1,00011100回報3,和01100101回報6.這是我有:Python遺傳算法的二進制數
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)
我無法真正搞清楚遺傳算法部分(交叉/變異)。我應該隨機配對數字,然後隨機選擇一對,保持一對不變,然後在隨機點交叉。然後它將隨着整個人口中的一點點隨機變異而結束。目前的交叉和變異編碼僅僅來自我發現並試圖理解的遺傳算法示例。歡迎任何fhelp。
一個人口由許多個人組成 - 我只看到一個「dna」。交叉有助於收斂基因的「子程序」,而突變有助於創造出達到目標所需的錯誤。 – User
此外,你需要一個fittness功能,確定一個人如何可能進行交叉和重組。您可以使用輪盤賭輪http://en.wikipedia.org/wiki/Fitness_proportionate_selection來確定哪些人可以交叉並創建進入下一代的孩子。 – User