我想了解遗传算法是如何工作的。和所有事情一样,我通过尝试自己写东西来学习;然而,我的知识非常有限,我不确定我是否做得对。
这个算法的目的是观察如果一半的人群已经被感染了,那么要花多长时间才能感染上一种疾病。这只是我在脑海中想到的一个例子,所以我不确定这是否一个可行的例子。
关于如何提高我的知识的一些反馈将是很好的。
以下是代码:
import random
def disease():
herd = []
generations = 0
pos = 0
for x in range(100):
herd.append(random.choice('01'))
print herd
same = all(x == herd[0] for x in herd)
while same == False:
same = all(x == herd[0] for x in herd)
for animal in herd:
try:
if pos != 0:
after = herd[pos+1]
before = herd[pos-1]
if after == before and after == '1' and before == '1' and animal == '0':
print "infection at", pos
herd[pos] = '1'
#print herd
pos += 1
except IndexError:
pass
pos = 0
generations += 1
random.shuffle(herd)
#print herd
print "Took",generations,"generations to infect all members of herd."
if __name__ == "__main__":
disease()我正在寻找基于这个算法的逻辑的评论。什么是可以改进的,哪些是需要改进的,才能使这成为真正的遗传算法,如果不是的话。
发布于 2013-02-09 11:53:37
你的算法不是遗传算法,它是一个简单的感染模型。
遗传算法通常至少使用以下概念:遗传、变异、选择(或适应度)。
见,例如这里
如果--为了介绍性的理解--您想将这些概念应用于您的示例:
要把它组合在一起,你可以制作不同的动物群,它们的“遗传”属性有不同的起始值(例如preferred_proximity_to_next_animal、skin_color、身高、攻击性等等)。
然后,在您的适应度函数中,定义每个属性是如何与适应度相关联的,即它们如何与感染的概率相关。然后让程序运行几代人,看看在每一次迭代中,感染的全球概率与你的牛群的遗传结构有关的降低。
就像这样,你可能会发现有利的属性组合。在搜索相关问题中,一般采用遗传算法。
发布于 2013-02-09 15:53:47
import random
def disease():
herd = []
generations = 0
pos = 0不要在使用变量之前指定变量
for x in range(100):
herd.append(random.choice('01'))
print herd
same = all(x == herd[0] for x in herd)
while same == False:
same = all(x == herd[0] for x in herd)首先,不要检查== False,使用not。而且,没有必要将它存储在相同的地方,只需测试它:
while not all(x == herd[0] for x in herd):我建议使用以下方法进行测试:
while len(set(herd)) != 1:这样会更有效率。
for animal in herd:
try:
if pos != 0:
after = herd[pos+1]
before = herd[pos-1]
if after == before and after == '1' and before == '1' and animal == '0':如果您已经在检查前后是否都等于“1”,则没有必要检查after == before。我会考虑做:
if (after, animal, before) == ('1','0','1'):在这种情况下,我认为更清楚地显示了发生了什么。
print "infection at", pos
herd[pos] = '1'
#print herd
pos += 1
except IndexError:
pass捕获IndexError通常不是一个好主意。太容易得到一个偶然的IndexError,然后让您的代码错过真正的问题。它也不能说明为什么你会得到一个索引错误。
与其更新pos,我建议您使用
for pos, animal in enumerate(herd):但是,既然你不想要第一个和最后一个元素,我建议
for pos in xrange(1, len(herd) - 1):
before, animal, after = herd[pos-1,pos+2]回到您的代码:
pos = 0你应该在循环之前重设东西,而不是事后。这样更容易理解。但是如果你能完全避免休息的话
generations += 1
random.shuffle(herd)
#print herd
print "Took",generations,"generations to infect all members of herd."
if __name__ == "__main__":
disease()发布于 2013-02-09 08:12:27
提取方法:initHerd、processGeneration和infect。
https://codereview.stackexchange.com/questions/21495
复制相似问题