import matplotlib.pyplot as plt
from random import uniform
from random import random
from numpy import array, sin, cos, sqrt
class Particle(object):
def __init__(self, position):
self.x = position
self.v = array([0., 0.])
self.best = position
def fit(p):
(x, y) = p
return (x**2+y**2)/32-cos(x)-cos(y)
def PSO():
c1 = 2
c2 = 2
N = 100
# 初始化
particle = [Particle(array([uniform(-10, 10), uniform(-10, 10)]))
for i in range(N)]
# 初始化全局最优位置
gbest = particle[0].x
for p in particle:
if fit(p.x) < fit(gbest):
gbest = p.x
plt.ion()
for t in range(100):
plt.clf()
# 对于所有粒子
for p in particle:
# 更新速度和位置
p.v += c1*random()*(p.best-p.x)+c2*random()*(gbest-p.x)
v = sqrt(p.v[0]**2+p.v[1]**2)
if v > 1:
p.v /= v
p.x += p.v
# 更新最优位置
if fit(p.x) < fit(p.best):
p.best = p.x
if fit(p.best) < fit(gbest):
gbest = p.best
plt.scatter(*array([p.x for p in particle]).T)
plt.xlim([-10, 10])
plt.ylim([-10, 10])
plt.pause(0.2)
plt.ioff()
plt.show()
PSO()
python 粒子群算法实现
最新推荐文章于 2022-01-11 16:02:01 发布
本文介绍了如何使用Python实现粒子群优化(PSO)算法,通过随机初始化粒子位置,不断更新粒子速度和位置来寻找函数最小值。展示了PSO在优化问题上的应用过程,包括速度更新公式、最佳位置更新和可视化结果。
摘要由CSDN通过智能技术生成