I am coding basic PSO (particle swarm optimization) and have been getting this error that particle instance has no attribute __getitem__
. I think everything is fine but the particle
class seems to have some error. Take a look at the particle
class.
from numpy import array
from random import random
from math import sin, sqrt, cos, pi
import matplotlib.pyplot as plt
import pylab
## Settings
c1 = 2
c2 = 2
size = 100
bad_size = 10
dim = 10
max_iterations = 20
Error_limit = 0.00001
def functR(k):
val = 10*dim
for i in range(dim):
val = val + (k[i])**2 - 10*cos(2*pi*k[i])
return val
#print functR([0]*20)
class particle():
def __init__(self, pos, fitness,vel, pbestpos, pbestfit):
self.pos = pos
self.fitness = fitness
self.vel = vel
self.pbestpos = pbestpos
self.pbestfitness = pbestfit
class swarm():
def __init__(self, size, bad_size, dim):
#self.gbest = gbest
self.size = size
self.bad_size = bad_size
self.dim = dim
def create(self):
particles = []
for i in range(size + bad_size):
p = particle()
p.pos = array([random() for i in range(dim)])
p.vel = 0.0
p.fitness = 0.0
p.pbestpos = p.pos
p.pbestfit = p.fitness
#p = particle(pos, fitness,vel, pbestpos, pbestfit)
particles.append(p)
return particles
def optimizer():
s = swarm(size, bad_size, dim)
new_swarm = s.create()
gbest = new_swarm[0]
gbestfit = functR(gbest)
i = 0
## The iterative loop
while i < max_iterations:
for p in s:
fitness = functR(p.pos)
if fitness > p.fitness:
p.fitness = fitness
p.pbestpos = p.pos
if fitness > gbestfit:
gbest = p
## Plotting
pylab.xlim([0,10])
pylab.ylim([0,1.5])
plt.plot(i,gbest.fitness, "bo")
## Velocity and Position update
vel = p.vel + c1 * random() * (p.pbestpos - p.pos) \
+ c2 * random() * (gbest.pos - p.pos)
p.pos = p.pos + vel
plt.show()
i += 1
print "gbest fitness :", gbestfit
print "Best particle :", gbest.pos
print optimizer()
You are treating a single particle()
instance as a list here:
val = val + (k[i])**2 - 10*cos(2*pi*k[i])
k
is an instance of particle()
, the [i]
syntax translates to a __getitem__
call on that instance.
You are passing in that instance here:
gbest = new_swarm[0]
gbestfit = functR(gbest)
while elsewhere you pass in the .pos
parameter instead:
for p in s:
fitness = functR(p.pos)
so perhaps you meant to do the same for the gbestfit
line:
gbest = new_swarm[0]
gbestfit = functR(gbest.pos)