Python遗传算法,怎么了?

2024-10-01 07:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始用python编程,我对人工智能非常感兴趣,所以我试着做一个简单的遗传算法来找到我设定的目标词,但我的群体开始变得一成不变,程序永远运行,有人能看出我的错误吗?你知道吗

import random
import string
import operator
population = []
scores = []

#Configs
target = ('Target')
length = len(target)
popsize = (100)
mutrate = (0.13)
itlimit = (1000)

#From https://www.safaribooksonline.com/library/view/python-cookbook-2nd/0596007973/ch04s22.html
def random_pick(some_list, probabilities):
    x = random.uniform(0, 1)
    cumulative_probability = 0.0
    for item, item_probability in zip(some_list, probabilities):
        cumulative_probability += item_probability
        if x < cumulative_probability: break
    return item

#From http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
def rndstr():
    return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(length))

def populate():
    for p in range(0,popsize):
        population.append(rndstr())

def evaluate():
    for member in population:
        scores.append(sum(map(operator.eq, member, target)))

def mate():
    for index, pup in enumerate(population):
        pai = random_pick(population,prob)
        mae = random_pick(population,prob)
        stp = 0
        while pai == mae:
            pai = random_pick(population,prob)
            mae = random_pick(population,prob)
        firstpart, secondpart = pai[:int(len(pai)/2)], mae[int(len(mae)/2):]
        population[index] = firstpart + secondpart

def mutate():
    for pop in population:
        popl = list(pop)
        for i in range(0, len(popl)):
            if 1 == random.randint(1,mutrate*100):
                popl[i] = random.choice(string.ascii_lowercase + string.ascii_uppercase)
                ''.join(popl)


populate()
print(population)

while target not in population and itlimit > 0:
    itlimit = itlimit-1
    print(itlimit)
    evaluate()
    prob = [float(i)/length for i in scores]
    mate()
    mutate()
    print(population)

Tags: intargetforstringlendefrandomitem