gpt4 book ai didi

python - 粒子实例没有属性 '__getitem__'

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:44 25 4
gpt4 key购买 nike

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

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

最佳答案

您在此处将单个 article() 实例视为列表:

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

karticle() 的实例,[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)

关于python - 粒子实例没有属性 '__getitem__',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com