天天看點

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