python的遗传算法--Hello World入门篇

本系列文章代码取材于书籍《Genetic Algorithms with Python》,本人是在校电气专业的研究生,立志从事于Python相关的代码工作,具体什么方向还有待深究。

众所周知,算法一类的相关工作在市场上工资不菲,对于跨专业想从事算法工作的同学,算法入门是很难的一件事,一者没有好的代码基础,二者算法书晦涩难懂,让人没有读下去的欲望。我从研究生入学到现在,已经有半年的时间了,期间一直摸索算法入门,但都没有坚持下来,但一直在学习Python的基础语法,几个月之前导师在群里推了这本书,还是英文,一开始没抱着什么期望,结果前几天偶尔得空,看了一下,发现这本书真的写的很用心,(这里不得不吐槽一下国内市面上的书本,大都没有用心写,都是这里抄抄那里抄抄),也挺符合我兴趣的,今天花了大半天攻克了Hello World 初级版(一是英语不好,二是学习的基础都遗忘了),这里先放代码,如果想听我自己的理解,有时间可以给大家录个视频。


import random
import datetime


def get_fitness(guess):
return sum(1 for expected, actual in zip(target, guess)
if expected == actual)


def display(guess):
timeDiff = datetime.datetime.now() - startTime
fitness = get_fitness(guess)
print("{0} {1} {2}".format(guess, fitness, str(timeDiff)))


def generate_parent(length):
genes = []
while len(genes) < length:
sampleSize = min(length - len(genes), len(geneSet))
genes.extend(random.sample(geneSet, sampleSize))
return ''.join(genes)


def mutate(parent):
index = random.randrange(0, len(parent))
childGenes = list(parent)
newGene, alternate = random.sample(geneSet, 2)
childGenes[index] = alternate
if newGene == childGenes[index]
else newGene
return ''.join(childGenes)


random.seed()
geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!."
target = "Hello World!"
startTime = datetime.datetime.now()
bestParent = generate_parent(len(target))
bestFitness = get_fitness(bestParent)
display(bestParent)
while True:
child = mutate(bestParent)
childFitness = get_fitness(child)

if bestFitness >= childFitness:
continue
display(child)
if childFitness >= len(bestParent):
break
bestFitness = childFitness
bestParent = child
 

下次更新不知道什么时候,随缘。

原文地址:https://www.cnblogs.com/python2/p/11995996.html