多目标粒子群算法,简称PSO算法,它的基本概念源于对鸟群觅食行为的研究。设想这样一个场景:一群鸟在随机搜寻食物,在这个区域里只有一块食物,所有的鸟都不知道食物在哪里,但是它们知道当前的位置离食物还有多远。最简单有效的策略?寻找鸟群中离食物最近的个体来进行搜素。
如下是PSO算法的python实现
import numpy as np
from sko.PSO import PSO
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# 基本的PSO算法 未进行改进
def demo_func(x):
x1, x2 = x
return -20 * np.exp(-0.2 * np.sqrt(0.5 * (x1 ** 2 + x2 ** 2))) - np.exp(
0.5 * (np.cos(2 * np.pi * x1) + np.cos(2 * np.pi * x2))) + 20 + np.e
max_iter = 100
pso = PSO(func=demo_func, dim=2, pop=40, max_iter=max_iter, lb=[-2, -2], ub=[2, 2])
pso.record_mode = True
pso.run()
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
# %% Now Plot the animation
record_value = pso.record_value
X_list, V_list = record_value['X'], record_value['V']
fig, ax = plt.subplots(1, 1)
ax.set_title('title', loc='center')
line = ax.plot([], [], 'b.')
X_grid, Y_grid = np.meshgrid(np.linspace(-2.0, 2.0, 40), np.linspace(-2.0, 2.0, 40))
Z_grid = demo_func((X_grid, Y_grid))
ax.contour(X_grid, Y_grid, Z_grid, 30)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
plt.ion()
p = plt.show()
def update_scatter(frame):
i, j = frame // 10, frame % 10
ax.set_title('iter = ' + str(i))
X_tmp = X_list[i] + V_list[i] * j / 10.0
plt.setp(line, 'xdata', X_tmp[:, 0], 'ydata', X_tmp[:, 1])
return line
ani = FuncAnimation(fig, update_scatter, blit=True, interval=25, frames=max_iter * 10)
ani.save('pso.gif')
其算法流程在此不再讲解了,这里只提供PSO算法的Python实现。