改进粒子群算法 python代码
时间: 2023-12-10 12:35:08 浏览: 100
以下是改进粒子群算法的Python代码示例:
```python
import random
import math
class Particle:
def __init__(self, dim, minx, maxx):
self.__pos = [random.uniform(minx, maxx) for i in range(dim)]
self.__vel = [random.uniform(minx, maxx) for i in range(dim)]
self.__bestPos = self.__pos[:]
self.__fitness = 0.0
self.__bestFitness = 0.0
def updateFitness(self, evalfn):
self.__fitness = evalfn(self.__pos)
if self.__fitness > self.__bestFitness:
self.__bestFitness = self.__fitness
self.__bestPos = self.__pos[:]
def updateVelocity(self, bestPos, omega, phip, phig):
for i in range(len(self.__vel)):
rp, rg = random.uniform(0, 1), random.uniform(0, 1)
cognitive = phip * rp * (self.__bestPos[i] - self.__pos[i])
social = phig * rg * (bestPos[i] - self.__pos[i])
self.__vel[i] = omega * self.__vel[i] + cognitive + social
def updatePosition(self, bounds):
for i in range(len(self.__pos)):
self.__pos[i] = self.__pos[i] + self.__vel[i]
if self.__pos[i] < bounds[i][0]:
self.__pos[i] = bounds[i][0]
self.__vel[i] = 0.0
elif self.__pos[i] > bounds[i][1]:
self.__pos[i] = bounds[i][1]
self.__vel[i] = 0.0
def getFitness(self):
return self.__fitness
def getBestPosition(self):
return self.__bestPos[:]
class ParticleSwarmOptimizer:
def __init__(self, evalfn, dim, nparticles, minx, maxx, omega, phip, phig):
self.__evalfn = evalfn
self.__particles = [Particle(dim, minx, maxx) for i in range(nparticles)]
bestParticle = self.__particles[0]
for particle in self.__particles:
particle.updateFitness(self.__evalfn)
if particle.getFitness() > bestParticle.getFitness():
bestParticle = particle
self.__bestGlobalPos = bestParticle.getBestPosition()
self.__omega = omega
self.__phip = phip
self.__phig = phig
def run(self, maxIterations):
for i in range(maxIterations):
for particle in self.__particles:
particle.updateVelocity(self.__bestGlobalPos, self.__omega, self.__phip, self.__phig)
particle.updatePosition(bounds)
particle.updateFitness(self.__evalfn)
if particle.getFitness() > self.__bestGlobalFitness:
self.__bestGlobalPos = particle.getBestPosition()
self.__bestGlobalFitness = particle.getFitness()
def getBestPosition(self):
return self.__bestGlobalPos[:]
# 示例函数
def sphereFn(x):
return sum([xi ** 2 for xi in x])
# 参数设置
bounds = [(-10, 10), (-10, 10), (-10, 10), (-10, 10), (-10, 10)]
nparticles = 20
maxIterations = 100
omega = 0.5
phip = 0.5
phig = 0.5
# 运行粒子群算法
pso = ParticleSwarmOptimizer(sphereFn, len(bounds), nparticles, -10, 10, omega, phip, phig)
pso.run(maxIterations)
# 输出最优解
print("Best position: ", pso.getBestPosition())
print("Best fitness: ", sphereFn(pso.getBestPosition()))
```
阅读全文