我有这段代码来实现粒子群优化算法:
class Particle:
def __init__(self,domain,ID):
self.ID = ID
self.gbest = None
self.velocity = []
self.current = []
self.pbest = []
for x in range(len(domain)):
self.current.append(random.randint(domain[x][0],domain[x][1]))
self.velocity.append(random.randint(domain[x][0],domain[x][1]))
self.pbestx = self.current
def updateVelocity():
for x in range(0,len(self.velocity)):
self.velocity[x] = 2*random.random()*(self.pbestx[x]-self.current[x]) + 2 * random.random()*(self.gbest[x]-self.current[x])
def updatePosition():
for x in range(0,len(self.current)):
self.current[x] = self.current[x] + self.velocity[x]
def updatePbest():
if costf(self.current) < costf(self.best):
self.best = self.current
def psoOptimize(domain,costf,noOfParticles=20, noOfRuns=30):
particles = []
for i in range(noOfParticles):
particle = Particle(domain,i)
particles.append(particle)
for i in range(noOfRuns):
Globalgbest = []
cost = 9999999999999999999
for i in particles:
if costf(i.pbest) < cost:
cost = costf(i.pbest)
Globalgbest = i.pbest
for particle in particles:
particle.updateVelocity()
particle.updatePosition()
particle.updatePbest(costf)
particle.gbest = Globalgbest
return determineGbest(particles,costf)
当我运行它时,我收到此错误:
TypeError: updateVelocity() takes no arguments (1 given)
但它明确表示particle.updateVelocity()
,之间没有任何内容()
。 “1给定”论点从何而来?代码有什么问题,如何修复?
Python 隐式地将对象传递给方法调用,但是您need to https://stackoverflow.com/q/2709821显式声明它的参数。这通常被命名为self
:
def updateVelocity(self):
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)