Я не знаю, почему я получил эту ошибку: '((Похоже, я не могу использовать массив append, а new_velocity не может прочитать element_position_vector. Есть ли какое-нибудь решение для моей ошибки?
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'