如何解决如何创建遗传算法来执行本地搜索?
我有一个大学作业,我必须做一个遗传算法来遍历给定的数字列表(接收一个条目和一个最终点)并显示到达该最终点的最佳路径。 在搜索时我发现了这个代码:
import random
stringSize = 4
top = 10 * stringSize
def value(s):
return max(-abs(round(0.3*top) - s),.025 - abs(round(0.8 * top) - s))
def ga(times = 10,popSize = 20,mutation_prob = 0.001):
population = [int(random.random() * top) for j in range(popSize)]
print(len(population))
print("---")
history = []
for i in range(times):
fitness = [value(population[j]) for j in range(popSize)]
fitMax = -float('inf')
for j in range(popSize):
if fitness[j] > fitMax:
fitMax = fitness[j]
jBest = j
history.append(population[jBest])
fit_sum = sum(fitness)
probs = [x/fit_sum for x in fitness]
cutoff = [sum(probs[:j+1]) for j in range(popSize)]
children = []
for j in range(popSize):
r = random.random()
for k in range(popSize):
if r < cutoff[k]:
break
par1 = population[k-1]
par2 = population[int(random.random() * popSize)]
split = int(random.random() * (stringSize + 1))
child = str(par1)[:split] + str(par2)[split:]
if random.random() < mutation_prob:
where = int(random.random() * stringSize)
what = str(int(random.random() * 10))
child = child[0:where] + what + child[where + 1:]
children.append(int(child))
population = children
return population
运行这段代码我得到了这个结果:
20
---
[28,28,25,28]
我需要在此代码中进行哪些调整才能在列表中进行迭代(本地搜索)并打印路径?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。