一个Python实现的精简版遗传算法

本文使用Python实现的精简版遗传算法,算法中仅采用变异算子而没有使用交叉算子,但是进化依然很有效,具体源代码如下:

from string import ascii_lowercase
from random import choice, random

target  = list("welcome to ")
charset = ascii_lowercase + ' .:/'
parent  = [choice(charset) for _ in range(len(target))]
minmutaterate  = .09
C = range(100)

perfectfitness = len(target)
def fitness(trial):
    return sum(t==h for t,h in zip(trial, target))

def mutaterate(parent):
    return 1.0-(1.0*(perfectfitness - fitness(parent)) / perfectfitness * (1.0 - minmutaterate))

def mutate(parent, rate):
    return [(ch if random() <= rate else choice(charset)) for ch in parent]

def log(iterations,rate,parent):
    print ("#%-4i, rate: %4.3f, fitness: %4.1f%%, '%s'" %
           (iterations, rate, fitness(parent)*100./perfectfitness, ''.join(parent)))

iterations = 0
while parent != target:
    rate =  mutaterate(parent)
    iterations += 1
    if iterations % 10 == 0: log(iterations,rate,parent)
    copies = [ mutate(parent, rate) for _ in C ]  + [parent]
    parent = max(copies, key=fitness)
print ()
log(iterations,rate,parent)


2 Responses to “一个Python实现的精简版遗传算法”

  1. CnHUP  on 六月 3rd, 2010

    welcome.


发表评论

You must be logged in to post a comment.