【发布时间】:2013-01-24 23:03:11
【问题描述】:
我正在尝试了解遗传算法的工作原理。就像我通过尝试在我的 on 上写一些东西来学习的所有东西一样;但是,我的知识非常有限,我不确定我是否做得对。
该算法的目的是查看如果一半的人口已经感染,那么半数牛群感染疾病需要多长时间。这只是我脑海中想到的一个例子,所以我不确定这是否是一个可行的例子。
关于如何提高我的知识的一些反馈会很好。
代码如下:
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()
【问题讨论】:
-
确实,您的算法有什么问题?你告诉我们。你有任何错误吗?它会产生意外的输出吗?
-
没有错误,我指的是我的代码的逻辑。我不确定它是否 100% 准确。很难调试逻辑。
-
另外,这不是遗传算法,您只是在对牛群进行迭代以传播感染。遗传算法是一种在非常不光滑的相空间中最小化的方法。您有一些适应度函数(它定义了您当前在相空间中的位置有多好),并且您可以在连续几代中选择和“培育”这些位置。简而言之,遗传算法是一种优化算法,而这不是。
-
这是我正在寻找的反馈类型。当谈到这个话题时,我很无知,但对我来说很有趣。感谢您的反馈。
标签: python algorithm genetic-algorithm genetic