粒子实例没有属性'__getitem__'

时间:2015-01-31 09:40:46

标签: python magic-methods particle-swarm

我正在编写基本的PSO(粒子群优化),并且已经得到粒子实例没有属性__getitem__的错误。我认为一切都很好,但particle类似乎有一些错误。看一下particle课程。

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()

1 个答案:

答案 0 :(得分:1)

您将单个particle()实例视为列表:

val = val + (k[i])**2 - 10*cos(2*pi*k[i])

kparticle()的一个实例,[i]语法转换为该实例上的__getitem__调用。

你在这里传递了这个例子:

gbest = new_swarm[0]
gbestfit = functR(gbest)

而在其他地方你传递了.pos参数:

for p in s:
    fitness = functR(p.pos)

所以也许你打算对gbestfit行做同样的事情:

gbest = new_swarm[0]
gbestfit = functR(gbest.pos)