這篇文章給大家介紹使用python3怎么實現(xiàn)一個單目標(biāo)粒子群算法,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
創(chuàng)新互聯(lián)公司專注于企業(yè)全網(wǎng)營銷推廣、網(wǎng)站重做改版、城關(guān)網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5場景定制、商城網(wǎng)站建設(shè)、集團(tuán)公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站制作、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為城關(guān)等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。1) 初始化粒子群;
隨機(jī)設(shè)置各粒子的位置和速度,默認(rèn)粒子的初始位置為粒子最優(yōu)位置,并根據(jù)所有粒子最優(yōu)位置,選取群體最優(yōu)位置。
2) 判斷是否達(dá)到迭代次數(shù);
若沒有達(dá)到,則跳轉(zhuǎn)到步驟3)。否則,直接輸出結(jié)果。
3) 更新所有粒子的位置和速度;
4) 計算各粒子的適應(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ù)動態(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()
最后是計算結(jié)果,完美結(jié)束!!!
關(guān)于使用python3怎么實現(xiàn)一個單目標(biāo)粒子群算法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
本文標(biāo)題:使用python3怎么實現(xiàn)一個單目標(biāo)粒子群算法-創(chuàng)新互聯(lián)
分享網(wǎng)址:http://m.newbst.com/article42/doddhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、商城網(wǎng)站、自適應(yīng)網(wǎng)站、定制開發(fā)、微信公眾號、標(biāo)簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容