天天看点

Python实现粒子群算法PSO

去github上吧scikit-opt这个库下载下来,

https://github.com/guofei9987/scikit-opt

如果不想下载整个库,也可以只下载pso.py这个文件

PSO

定义你的目标函数

def demo_func2(p):
    # Sphere函数
    out_put = 0
    for i in p:
        out_put += i ** 2
    return out_put
           

使用粒子群算法

from pso import PSO
my_pso = PSO(func=demo_func2, pop=30, dim=5, max_iter=100)
fitness = my_pso.fit()
           

输出结果并画图

print(my_pso.gbest_x)
print(my_pso.gbest_y)
my_pso.plot_history()
           
Python实现粒子群算法PSO

以上代码全部整理到了 github

包括下面这个动画:

Python实现粒子群算法PSO