python3實(shí)現(xiàn)單目標(biāo)粒子群算法
本文實(shí)例為大家分享了python3單目標(biāo)粒子群算法的具體代碼,供大家參考,具體內(nèi)容如下
關(guān)于PSO的基本知識(shí)......就說一下算法流程
1) 初始化粒子群;
隨機(jī)設(shè)置各粒子的位置和速度,默認(rèn)粒子的初始位置為粒子最優(yōu)位置,并根據(jù)所有粒子最優(yōu)位置,選取群體最優(yōu)位置。
2) 判斷是否達(dá)到迭代次數(shù);
若沒有達(dá)到,則跳轉(zhuǎn)到步驟3)。否則,直接輸出結(jié)果。
3) 更新所有粒子的位置和速度;
4) 計(jì)算各粒子的適應(yīng)度值。
將粒子當(dāng)前位置的適應(yīng)度值與粒子最優(yōu)位置的適應(yīng)度值進(jìn)行比較,決定是否更新粒子最優(yōu)位置;將所有粒子最優(yōu)位置的適應(yīng)度值與群體最優(yōu)位置的適應(yīng)度值進(jìn)行比較,決定是否更新群體最優(yōu)位置。然后,跳轉(zhuǎn)到步驟2)。
直接扔代碼......(PS:1.參數(shù)動(dòng)態(tài)調(diào)節(jié);2.例子是二維的)
首先,是一些準(zhǔn)備工作...
# Import libs import numpy as np import random as rd import matplotlib.pyplot as plt # Constant definition MIN_POS = [-5, -5] # Minimum position of the particle MAX_POS = [5, 5] # Maximum position of the particle MIN_SPD = [-0.5, -0.5] # Minimum speed of the particle MAX_SPD = [1, 1] # Maximum speed of the particle C1_MIN = 0 C1_MAX = 1.5 C2_MIN = 0 C2_MAX = 1.5 W_MAX = 1.4 W_MIN = 0
然后是PSO類
# Class definition class PSO(): """ PSO class """ def __init__(self,iters=100,pcount=50,pdim=2,mode='min'): """ PSO initialization ------------------ """ self.w = None # Inertia factor self.c1 = None # Learning factor self.c2 = None # Learning factor self.iters = iters # Number of iterations self.pcount = pcount # Number of particles self.pdim = pdim # Particle dimension self.gbpos = np.array([0.0]*pdim) # Group optimal position self.mode = mode # The mode of PSO self.cur_pos = np.zeros((pcount, pdim)) # Current position of the particle self.cur_spd = np.zeros((pcount, pdim)) # Current speed of the particle self.bpos = np.zeros((pcount, pdim)) # The optimal position of the particle self.trace = [] # Record the function value of the optimal solution def init_particles(self): """ init_particles function ----------------------- """ # Generating particle swarm for i in range(self.pcount): for j in range(self.pdim): self.cur_pos[i,j] = rd.uniform(MIN_POS[j], MAX_POS[j]) self.cur_spd[i,j] = rd.uniform(MIN_SPD[j], MAX_SPD[j]) self.bpos[i,j] = self.cur_pos[i,j] # Initial group optimal position for i in range(self.pcount): if self.mode == 'min': if self.fitness(self.cur_pos[i]) < self.fitness(self.gbpos): gbpos = self.cur_pos[i] elif self.mode == 'max': if self.fitness(self.cur_pos[i]) > self.fitness(self.gbpos): gbpos = self.cur_pos[i] def fitness(self, x): """ fitness function ---------------- Parameter: x : """ # Objective function fitval = 5*np.cos(x[0]*x[1])+x[0]*x[1]+x[1]**3 # min # Retyrn value return fitval def adaptive(self, t, p, c1, c2, w): """ """ #w = 0.95 #0.9-1.2 if t == 0: c1 = 0 c2 = 0 w = 0.95 else: if self.mode == 'min': # c1 if self.fitness(self.cur_pos[p]) > self.fitness(self.bpos[p]): c1 = C1_MIN + (t/self.iters)*C1_MAX + np.random.uniform(0,0.1) elif self.fitness(self.cur_pos[p]) <= self.fitness(self.bpos[p]): c1 = c1 # c2 if self.fitness(self.bpos[p]) > self.fitness(self.gbpos): c2 = C2_MIN + (t/self.iters)*C2_MAX + np.random.uniform(0,0.1) elif self.fitness(self.bpos[p]) <= self.fitness(self.gbpos): c2 = c2 # w #c1 = C1_MAX - (C1_MAX-C1_MIN)*(t/self.iters) #c2 = C2_MIN + (C2_MAX-C2_MIN)*(t/self.iters) w = W_MAX - (W_MAX-W_MIN)*(t/self.iters) elif self.mode == 'max': pass return c1, c2, w def update(self, t): """ update function --------------- Note that : 1. Update particle position 2. Update particle speed 3. Update particle optimal position 4. Update group optimal position """ # Part1 : Traverse the particle swarm for i in range(self.pcount): # Dynamic parameters self.c1, self.c2, self.w = self.adaptive(t,i,self.c1,self.c2,self.w) # Calculate the speed after particle iteration # Update particle speed self.cur_spd[i] = self.w*self.cur_spd[i] \ +self.c1*rd.uniform(0,1)*(self.bpos[i]-self.cur_pos[i])\ +self.c2*rd.uniform(0,1)*(self.gbpos - self.cur_pos[i]) for n in range(self.pdim): if self.cur_spd[i,n] > MAX_SPD[n]: self.cur_spd[i,n] = MAX_SPD[n] elif self.cur_spd[i,n] < MIN_SPD[n]: self.cur_spd[i,n] = MIN_SPD[n] # Calculate the position after particle iteration # Update particle position self.cur_pos[i] = self.cur_pos[i] + self.cur_spd[i] for n in range(self.pdim): if self.cur_pos[i,n] > MAX_POS[n]: self.cur_pos[i,n] = MAX_POS[n] elif self.cur_pos[i,n] < MIN_POS[n]: self.cur_pos[i,n] = MIN_POS[n] # Part2 : Update particle optimal position for k in range(self.pcount): if self.mode == 'min': if self.fitness(self.cur_pos[k]) < self.fitness(self.bpos[k]): self.bpos[k] = self.cur_pos[k] elif self.mode == 'max': if self.fitness(self.cur_pos[k]) > self.fitness(self.bpos[k]): self.bpos[k] = self.cur_pos[k] # Part3 : Update group optimal position for k in range(self.pcount): if self.mode == 'min': if self.fitness(self.bpos[k]) < self.fitness(self.gbpos): self.gbpos = self.bpos[k] elif self.mode == 'max': if self.fitness(self.bpos[k]) > self.fitness(self.gbpos): self.gbpos = self.bpos[k] def run(self): """ run function ------------- """ # Initialize the particle swarm self.init_particles() # Iteration for t in range(self.iters): # Update all particle information self.update(t) # self.trace.append(self.fitness(self.gbpos))
然后是main...
def main(): """ main function """ for i in range(1): pso = PSO(iters=100,pcount=50,pdim=2, mode='min') pso.run() # print('='*40) print('= Optimal solution:') print('= x=', pso.gbpos[0]) print('= y=', pso.gbpos[1]) print('= Function value:') print('= f(x,y)=', pso.fitness(pso.gbpos)) #print(pso.w) print('='*40) # plt.plot(pso.trace, 'r') title = 'MIN: ' + str(pso.fitness(pso.gbpos)) plt.title(title) plt.xlabel("Number of iterations") plt.ylabel("Function values") plt.show() # input('= Press any key to exit...') print('='*40) exit() if __name__ == "__main__": main()
最后是計(jì)算結(jié)果,完美結(jié)束?。?!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python3將變量寫入SQL語句的實(shí)現(xiàn)方式
這篇文章主要介紹了python3將變量寫入SQL語句的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03TensorFlow中tf.batch_matmul()的用法
這篇文章主要介紹了TensorFlow中tf.batch_matmul()的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Flask??請(qǐng)求鉤子的實(shí)現(xiàn)
這篇文章主要給大家分享了Flask請(qǐng)求鉤子的實(shí)現(xiàn),在客戶端和服務(wù)器交互的過程中,有些準(zhǔn)備工作或掃尾工作需要處理,比如:在請(qǐng)求開始時(shí),建立數(shù)據(jù)庫連接;在請(qǐng)求開始時(shí),根據(jù)需求進(jìn)行權(quán)限校驗(yàn);在請(qǐng)求結(jié)束時(shí),指定數(shù)據(jù)的交互格式;下面來看看文章詳細(xì)介紹內(nèi)容吧2021-11-11使用Python實(shí)現(xiàn)壓縮pptx的功能
當(dāng)處理大型PPTX文件時(shí),其中包含許多高分辨率照片時(shí),文件大小可能會(huì)顯著增加,為了解決這個(gè)問題,我們可以使用Python編程語言和python-pptx庫來壓縮PPTX文件中的照片,下面我們就來看看具體操作吧2024-02-02你知道怎么改進(jìn)Python 二分法和牛頓迭代法求算術(shù)平方根嗎
這篇文章主要介紹了Python編程實(shí)現(xiàn)二分法和牛頓迭代法求平方根代碼的改進(jìn),具有一定參考價(jià)值,需要的朋友可以了解下,希望能夠給你帶來幫助2021-08-08