我不知道我为什么会有这样的错误:'(( 似乎我不能使用数组附加和新的速度不能读取粒子位置向量。我的错误有什么解决办法吗?你知道吗
import random as rd
import numpy as np
particle_position_vector = []
#to randomize
for _ in range(n_particles):
a3=rd.randint(0,1)
a2=rd.randint(0,50)
a1=100-a2-a3
particle_position_vector.append([rd.randint(0,1), rd.randint(0,2), a2, a1, a3])
pbest_position = particle_position_vector
gbest_position = np.array([float('inf'), float('inf'), float('inf'), float('inf'), float('inf')])
velocity_vector = ([np.array([0, 0, 0, 0, 0]) for _ in range(n_particles)])
iteration = 0
while iteration < n_iterations:
print("iteration : ", iteration)
for i in range(n_particles):
fitness_cadidate = fitness_function(particle_position_vector[i])
print(particle_position_vector[i],' ', -(fitness_cadidate))
for i in range(n_particles):
#to update new velocity and position
new_velocity = (W*velocity_vector[i]) + (c1*rd.random()) * (pbest_position[i] - particle_position_vector[i]) + (c2*rd.random()) * (gbest_position-particle_position_vector[i])
new_position = new_velocity + particle_position_vector[i]
particle_position_vector[i] = new_position
iteration = iteration + 1
输入:
Inform the number of iterations: 10
Inform the target error: 1e-6
Inform the number of particles: 10
然后,代码只在迭代0时运行并生成此错误
iteration : 0
[0, 0, 35, 64, 1] 26.724501800000002
[0, 2, 16, 83, 1] 13.9079791
[1, 2, 4, 96, 0] 6.9655632
[1, 0, 28, 71, 1] 29.718418700000004
[1, 0, 11, 88, 1] 27.8742026
[0, 0, 9, 90, 1] 23.903936
[1, 1, 9, 91, 0] 12.8856497
[0, 0, 43, 56, 1] 27.592368200000003
[0, 2, 31, 68, 1] 15.5352286
[0, 1, 42, 58, 0] 12.7122986
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-57e52263d20a> in <module>
59
60 for i in range(n_particles):
---> 61 new_velocity = (W*velocity_vector[i]) + (c1*rd.random()) * (pbest_position[i] - particle_position_vector[i]) + (c2*rd.random()) * (gbest_position-particle_position_vector[i])
62 new_position = new_velocity + particle_position_vector[i]
63 particle_position_vector[i] = new_position
TypeError: unsupported operand type(s) for -: 'list' and 'list'
在代码的某个地方,您正在从另一个列表中减去一个列表。在python命令行中尝试以下操作:
要减去元素,可以使用以下方法:
希望这有帮助!你知道吗
编辑
准确地说,这里有一个错误:
现在,为什么
pbest_position[i]
可以是一个添加了随机列表的列表。append()
将向列表中追加一个列表。例如:因此,不要使用
append()
,而是使用+
将元素添加到数组中,如下所示:确切地说,使用:
相关问题 更多 >
编程相关推荐