【发布时间】:2018-01-31 07:04:57
【问题描述】:
我正在尝试创建一种遗传算法来查找控制台输入中给出的单词。但我不知道我是否成功地做了一个完整的遗传算法。 代码如下:
main.py:
from population import Population
target = input()
maxPop = 10
mutation = 100
print("\n\n\n")
pop = Population(target, maxPop, mutation)
人口.py:
import random
from ADN import genetic
class Population:
def __init__(self, target, maxPop, mut):
adn = genetic()
self.popul = []
i = 0
while i < maxPop:
self.popul.append(adn.genFirst(len(target)))
print(self.popul[i])
i+=1
#oldPop = self.popul
#adn.fitness(oldPop, target)
#"""
while target not in self.popul:
oldPop = self.popul
self.popul = adn.fitness(oldPop, target)
if target in self.popul:
return
#"""
ADN.py:
import random
class genetic:
def genFirst(self, length):
bestGenes = ""
self.letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890[],. "
word = ""
i = 0
while i < length:
word += random.choice(self.letters)
i+=1
return word
def fitness(self, oldPop, target):
newPop = []
j = 0
for word in oldPop:
newW = ""
for letter in word:
if(letter not in target):
letter = random.choice(self.letters)
else:
if(target.index(letter) != word.index(letter)):
letter = random.choice(self.letters)
newW += letter
newPop.append(newW)
print(newPop)
return newPop
如果不是完整的遗传算法,缺少什么?
【问题讨论】:
-
遗传算法没有严格的“模板”,因此不清楚“完整”与非“完整”的区别在哪里。
-
既然你似乎同时缺少变异算子和交叉算子,为什么你认为它有资格作为遗传算法?看来这是一个不错的开始。
-
当正确的字母被传输到下一代时,我认为交叉已经完成
-
cmets 必须足够有用。太宽泛,无法回答。
-
即使您有一个称为“适应度”的函数,但实际上并没有文献中通常理解的适应度函数。即使作为@EugeneSh。正确地指出,对于什么算作遗传算法没有官方标准,将您的代码称为遗传算法将是一个延伸。 “它缺少什么?”这个问题的答案。是“几乎所有东西”(适应度函数、选择算子、变异算子和交叉算子)。见:en.wikipedia.org/wiki/Genetic_algorithm
标签: python python-3.x genetic-algorithm genetic-programming