如何解决类型错误:'int' 对象不可下标遗传算法与搜索
我有这个代码,我正在尝试使用遗传算法进行本地搜索。我想用这些数据来运行:
[0 : [3,2,1],1 : [4],2 : [6,5],3 : [7],4 : [8],5 : [9]]
这是我的代码:
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)]
population = [0[3,1[4],2[6,3[7],4[8],5[9]]
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
但是运行它会抛出这个错误:
TypeError Traceback (most recent call last)
<ipython-input-34-73e983c9ab93> in <module>()
----> 1 ga()
<ipython-input-33-a504bbf614a5> in ga(times,popSize,mutation_prob)
4 def ga(times = 10,mutation_prob = 0.001):
5 #population = [int(random.random() * top) for j in range(popSize)]
----> 6 population = [0[3,7 1[4],8 2[6,TypeError: 'int' object is not subscriptable
我能做些什么来执行它?我做对了吗?
解决方法
您的数组有语义错误。例如。 1[2]
不是有效的 Python。如果您想做的是将数字映射到数字数组,请使用按键索引每个列表的字典或具有值和子属性的字典数组。
正如其他人已经指出的那样,您可以使用这样的字典:
population = {
0: [1,2],1: [3,4,5],...
}
您遇到的错误通常意味着您正在尝试为无法编入索引的对象建立索引。
,只需使用字典:
population = {0:[3,2,1],1:[4],2:[6,3:[7],4:[8],5:[9]}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。