粒子群算法python实现
时间: 2023-11-09 09:58:43 浏览: 130
粒子群优化算法的python实现
5星 · 资源好评率100%
粒子群算法(Particle Swarm Optimization,PSO)是一种群体智能算法,用于寻找多维空间中的最优解。下面是粒子群算法的python实现:
```python
import random
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, maxx - minx) for i in range(dim)]
self.__best_pos = self.__pos
self.__best_score = float('inf')
self.__score = float('inf')
def set_pos(self, pos):
self.__pos = pos
def get_pos(self):
return self.__pos
def set_vel(self, vel):
self.__vel = vel
def get_vel(self):
return self.__vel
def set_best_pos(self, pos):
self.__best_pos = pos
def get_best_pos(self):
return self.__best_pos
def set_best_score(self, score):
self.__best_score = score
def get_best_score(self):
return self.__best_score
def set_score(self, score):
self.__score = score
def get_score(self):
return self.__score
class PSO:
def __init__(self, dim, size, iter_num, c1, c2, minx, maxx):
self.__size = size
self.__particles = [Particle(dim, minx, maxx) for i in range(size)]
self.__c1 = c1
self.__c2 = c2
self.__minx = minx
self.__maxx = maxx
self.__iter_num = iter_num
self.__gbest_score = float('inf')
self.__gbest_pos = [random.uniform(minx, maxx) for i in range(dim)]
def run(self):
for i in range(self.__iter_num):
for particle in self.__particles:
pos = particle.get_pos()
vel = particle.get_vel()
for j in range(len(pos)):
vel[j] = vel[j] + self.__c1 * random.random() * (particle.get_best_pos()[j] - pos[j]) \
+ self.__c2 * random.random() * (self.__gbest_pos[j] - pos[j])
pos[j] = pos[j] + vel[j]
if pos[j] > self.__maxx:
pos[j] = self.__maxx
vel[j] = random.uniform(self.__minx - self.__maxx, self.__maxx - self.__minx)
elif pos[j] < self.__minx:
pos[j] = self.__minx
vel[j] = random.uniform(self.__minx - self.__maxx, self.__maxx - self.__minx)
score = self.objective_function(pos)
particle.set_score(score)
if score < particle.get_best_score():
particle.set_best_score(score)
particle.set_best_pos(pos)
if score < self.__gbest_score:
self.__gbest_score = score
self.__gbest_pos = pos
print('Iteration: %d, Best Score: %f' % (i, self.__gbest_score))
return self.__gbest_pos, self.__gbest_score
def objective_function(self, x):
# 目标函数(需要根据实际问题进行自定义)
return sum([i ** 2 for i in x])
if __name__ == '__main__':
pso = PSO(dim=2, size=10, iter_num=50, c1=2, c2=2, minx=-10, maxx=10)
pso.run()
```
阅读全文