我正在学习如何使用遗传算法。我找到了这个(相对而且清晰)简单的练习,让我了解了如何做到这一点的基础知识(qazxsw poi)。
练习的目的是破解函数中给出的“密码”。然后它完成整个算法。首先,它使一组随机字符串成为“密码”的长度。
https://blog.sicara.com/getting-started-genetic-algorithms-python-tutorial-81ffa1dd72f9
然后检查每个单词的适应度(由单词与密码的接近程度确定),如下所示:
def generateOrganism(length):
possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
i = 0
result = ""
while i < length:
i += 1
character = random.choice(possible_chars)
result += character
return result
def generatePopulation(sizePopulation, password):
population = []
print('Starting Algorithm')
i = 0
while i < sizePopulation:
population.append(generateOrganism(len(password)))
i += 1
return population
这被称为computePerfPopulation函数,它生成单词及其适应性的字典。
def fitness (password, test_word):
if (len(test_word) != len(password)):
print("taille incompatible")
return
else:
score = 0
i = 0
while (i < len(password)):
if (password[i] == test_word[i]):
score+=1
i+=1
return score * 100 / len(password)
然后将该字典传递给selectFromPopulation函数,该函数选择具有最佳适应度的单词和用于“繁殖”的几个随机单词。
def computePerfPopulation(population, password):
populationPerf = {}
for individual in population:
populationPerf[individual] = fitness(password, individual)
if fitness(password, individual) == 100:
print("EUREKA, WE HAVE CRACKED THE PASSWORD. IT'S '", individual, "'")
return 'Done'
print(populationPerf)
return sorted(populationPerf.items(), key = operator.itemgetter(1), reverse = True)
然后将这些单词与下面的函数联系起来。这就是出现问题的地方。
def selectFromPopulation(populationSorted, best_sample, lucky_few):
nextGen = []
for i in range(best_sample):
nextGen.append(populationSorted[i][0])
for i in range(lucky_few):
nextGen.append(random.choice(populationSorted)[0])
random.shuffle(nextGen)
return nextGen
然后一些随机的单词可能会被下面的函数变异,但这并不完全重要。然后整个事情循环直到收到密码
def createChildren(breeders, num_of_children):
nextPopulation = []
for i in range(0, len(breeders) // 2):
for j in range(0, num_of_children):
nextPopulation.append(createChild(breeders[i], breeders[len(breeders) -1 -i]))
print(nextPopulation)
print(len(nextPopulation))
return nextPopulation
def createChild(individual1, individual2):
child = ""
for i in range(len(individual1)):
if (int(100) * random.random()) < 50:
child += individual1[i]
else:
print(i)
print(individual2)
child += individual2[i]
return child
有时,整个项目的工作原理与“密码”一致。但偶尔我会收到以下错误:
def mutatePopulation(population, chance_mutate): # population is a list
for i in range(len(population)):
if int(random.random() * 100) < chance_mutate:
population[i] = mutateWord(population[i])
return population
def mutateWord(word):
possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
index_mods = int(random.random() * len(word))
if index_mods == 0:
word = random.choice(possible_chars) + word[1:]
print(word)
else:
word = random.choice(possible_chars) + word[index_mods+1:]
return word
当我调查这个问题时,我开始打印出createChildren函数生成的列表(我将在下面给出完整的项目代码)并偶尔注意到(在第二个循环或以上,从不在第一个循环中) )一些单词将是一个或两个字符。我怀疑这是因为,当我再次循环它时,我将新的种群插入到computePerfPopulation函数中,新的种群与原始种群的大小不同,抛弃了索引? (我希望这是有道理的)
我不知道导致问题的原因,如果有人能告诉我发生了什么,我真的很感激。 (我知道这已经很长时间了,但请耐心等待)如果你有任何关于使这个代码更好的指示,如果你能给我一个很好的遗传算法实现资源,我将非常感激。
(如果您在此处获取所有这些代码并运行它,经过几次尝试后它应该显示错误等等)以下是完整的项目代码:
Traceback (most recent call last):
File "main.py", line 146 in <module>
project(100, 'lol' 10, 10, 5, 5)
File "main.py", line 137 in projcet
remakePopulation = createChildren(newBreeders, num_of_child)
File "main.py", line 33 in createChildren
nextPopulation.append(createChild(breeders[i], breeders[len(breeders) - 1 - 1]))
File "main.py", line 49, in createChild
child += individual2[i]
IndexError: string index out of range
在这部分
import random
import operator
def mutatePopulation(population, chance_mutate): # population is a list
for i in range(len(population)):
if int(random.random() * 100) < chance_mutate:
population[i] = mutateWord(population[i])
return population
def mutateWord(word):
possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
index_mods = int(random.random() * len(word))
if index_mods == 0:
word = random.choice(possible_chars) + word[1:]
print(word)
else:
word = random.choice(possible_chars) + word[index_mods+1:]
return word
def createChildren(breeders, num_of_children):
nextPopulation = []
for i in range(0, len(breeders) // 2):
for j in range(0, num_of_children):
nextPopulation.append(createChild(breeders[i], breeders[len(breeders) -1 -i]))
print(nextPopulation)
print(len(nextPopulation))
return nextPopulation
def createChild(individual1, individual2):
child = ""
for i in range(len(individual1)):
if (int(100) * random.random()) < 50:
child += individual1[i]
else:
print(i)
print(individual2)
child += individual2[i]
return child
def selectFromPopulation(populationSorted, best_sample, lucky_few):
nextGen = []
for i in range(best_sample):
nextGen.append(populationSorted[i][0])
for i in range(lucky_few):
nextGen.append(random.choice(populationSorted)[0])
random.shuffle(nextGen)
return nextGen
def computePerfPopulation(population, password):
populationPerf = {}
for individual in population:
populationPerf[individual] = fitness(password, individual)
if fitness(password, individual) == 100:
print("EUREKA, WE HAVE CRACKED THE PASSWORD. IT'S '", individual, "'")
return 'Done'
print(populationPerf)
return sorted(populationPerf.items(), key = operator.itemgetter(1), reverse = True)
def generateOrganism(length):
possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
i = 0
result = ""
while i < length:
i += 1
character = random.choice(possible_chars)
result += character
return result
def generatePopulation(sizePopulation, password):
population = []
print('Starting Algorithm')
i = 0
while i < sizePopulation:
population.append(generateOrganism(len(password)))
i += 1
return population
def fitness(password, test_word): # fitness function of the algorithm
if len(test_word) != len(password):
badFit = 0.0
return badFit
else:
score = 0
i = 0
while i < len(password):
if password[i] == test_word[i]:
score += 1
i += 1
if test_word == password:
print("SUCCESS")
fit = (score * 100) / len(password)
return fit
def project(population_size, password, best_sample, lucky_few, num_of_child, chance_of_mutation):
password = str(password)
population = generatePopulation(population_size, password)
populationSorted = computePerfPopulation(population, password)
#print(computePerfPopulation(population, password))
breeders = selectFromPopulation(populationSorted, best_sample, lucky_few)
nextPopulation = createChildren(breeders, num_of_child)
nextGeneration = mutatePopulation(nextPopulation, chance_of_mutation)
while True:
i = 1
newPopulationSorted = computePerfPopulation(nextGeneration, password)
if newPopulationSorted == 'Done':
break
newBreeders = selectFromPopulation(newPopulationSorted, best_sample, lucky_few)
remakePopulation = createChildren(newBreeders, num_of_child)
nextGeneration = mutatePopulation(remakePopulation, chance_of_mutation)
print(nextGeneration)
print(len(nextGeneration))
input('Press enter to continue')
i += 1
可能是单个文本而不是数组?
喜欢:
def mutateWord(word):
possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
多数民众赞成!