粒子群PSO优化算法学习笔记 及其python实现(附讲解如何使用python语言sko.PSO工具包)
算法描述
粒子群算法思想來源于實際生活中鳥捕食的過程。假設在一個n維的空間中,有一群鳥(m只)在捕食,食物位于n維空間的某個點上,對于第i只鳥某一時刻來說,有兩個向量描述,一個是鳥的位置向量,第二個是鳥的速度。假設鳥能夠判斷一個位置的好壞,所謂“好壞”,就是離食物更近了還是更遠了。鳥在捕食的過程中會根據自己的經驗以及鳥群中的其他鳥的位置決定自己的速度,根據當前的位置和速度,可以得到下一刻的位置,這樣每只鳥通過向自己和鳥群學習不斷的更新自己的速度位置,最終找到食物,或者離食物足夠近的點。更新速度和位置的表達式如下。
其效果圖見下面:
sko.PSO 工具包講解
python語言
首先要下載這個工具包。
這個anaconda下載大家都會
參數詳解
如代碼:
pso = PSO(func=demo_func, 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)
| func | 類型function, 所要求得優化函數 |
| dim | 類型int,維數,即函數的參數數 |
| pop | 類型int,種群的大小,也就是粒子的數量。我們使用“pop”來與GA保持一致。默認40 |
| max_iter | 類型int,iter迭代的最大值 默認150 |
| lb | 類型列表,下限。每個參數的下限 |
| ub | 類型列表,上限。每個參數的上限 |
| W | 對應公式里的慣性權重,默認0.8 |
| C1 | 學習因子1,默認0.5 |
| C2 | 學習因子2,默認0.5 |
| pbest_x | array_like, shape is (pop,dim)歷史上每個粒子的最佳位置 |
| pbest_y | array_like, shape is (pop,1)歷史上最好的粒子圖像 |
| gbest_x | array_like, shape is (1,dim)general best location for all particles in history |
| gbest_y | float歷史上所有粒子的最佳圖像 |
| gbest_y_hist | list每個迭代的gbest_y |
算例:有限制的粒子群
來源于官方文檔例子
第一步,定義問題
def demo_func(x):x1, x2, x3 = xreturn x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2第二步,做粒子群算法
from sko.PSO import PSOpso = PSO(func=demo_func, 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('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)結果:
可以發現x的值落在啦限制區間內。
第三步,畫出結果
算例:無限制的粒子群
def demo_func(x):x1, x2, x3 = xreturn x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2# %% Do PSO from sko.PSO import PSOpso = PSO(func=demo_func, dim=3) pso.run() print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)# %% Plot the result import matplotlib.pyplot as pltplt.plot(pso.gbest_y_hist) plt.show()結果:
可以發現x1的值無限接近0,x2無限接近0.05,x3的值無限接近0.
所謂優化,我的理解是對一個問題求出它足夠好的解,即使這個解不是最優解。如題中解接近0而不是0。在現實生活中,這個解滿足要求。
數據批量做粒子群優化
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: yudengwu # @Date : 2020/8/18 def demo_func(x):x1, x2, x3 = xreturn x1 ** 2 + (x2 - 0.05) ** 2 + x3 ** 2from sko.PSO import PSO import numpy as np import pandas as pddata={'lb':[[0,-1,0.5],[1,1,1],[2,3,4]],'ub':[[1,1,1],[2,2,2],[4,5,6]]} data=pd.DataFrame(data)print(data.shape[0])def pso(lb,ub):pso = PSO(func=demo_func, dim=3, pop=40, max_iter=150, lb=lb, ub=ub, w=0.8, c1=0.5, c2=0.5)pso.run()print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)for i in range(data.shape[0]):pso(data['lb'][i], data['ub'][i])結果
python 實現粒子群
這是一個簡單算例,通過該算例簡單感受下粒子群
求取 函數x + 16 * np.sin(5 * x) + 10 * np.cos(4 * x) 的最大值
這段代碼有參考https://blog.csdn.net/saltriver/article/details/63680543
電氣專業的計算機小白,寫博文不容易。如果你覺得本文對你有用,請點個贊支持下。謝謝
總結
以上是生活随笔為你收集整理的粒子群PSO优化算法学习笔记 及其python实现(附讲解如何使用python语言sko.PSO工具包)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 桂林银行app(桂林银行网上助手)
- 下一篇: 36篇博文带你学完opencv :pyt