from sko.PSO import PSO
import matplotlib.pyplot as plt
'''
目标是求目标函数的最小值
粒子群优化算法和蚁群算法类似,主要依靠群体之间的联系寻找最优解和最优输入嘴和
参数介绍:
func: 目标函数
ndim: 输入参数的个数
pop: 粒子的个数
max_iter: 最大迭代次数
lb: 输入参数的下限,低于此数值将不再衰减
ub: 输入参数的上限,高于此数值将不再增加
w: 学习衰减速率,惯性权重,学习的精度将随着迭代次数的增加而增加,但随之而来的是移动速度的下降。
c1: 自身最优值的记忆权重
c2: 群体最优值的记忆权重
'''
def demo_func(x):
x1, x2, x3 = x
return x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2
pso = PSO(func=demo_func, n_dim=3, pop=40, max_iter=150, lb=[0, -1, 0.5], ub=[1, 1, 1], w=0.8, c1=0.5, c2=0.5)
pso.run()
print('pbest_x', pso.pbest_x, 'pbest_y', pso.pbest_y, 'length', len(pso.pbest_y))
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
print('gbest_y_hist', pso.gbest_y_hist)
plt.plot(pso.gbest_y_hist)
plt.show()