Python實現粒子群演算法
阿新 • • 發佈:2019-01-06
問題描述
用粒子群演算法優化函式
解決方案
利用粒子群演算法解決優化問題
其中引數設定為:
具體程式碼
import numpy as np
import random
import math
import copy
class Ind:
def __init__(self):
self.x = []
self.v = []
self.fitness = 0.0
self.Bestx = []
self.Bestfitness = 0.0
def Fitness(self):
self.fitness = 21.5 + self.x[0] * math.sin(4 * math.pi * self.x[0]) + self.x[1] * math.sin(20 * math.pi * self.x[1])
def Init(self, Upper, Lower, Vmax, Vmin, N):
for i in range(N):
self.x.append(random.uniform(Lower[i], Upper[i]))
self.v.append(random.uniform(Vmin, Vmax))
self.Fitness()
self.Bestx = copy.deepcopy(self.x)
self.Bestfitness = self.fitness
def Find_Best(Pparent, Pop):
Best = copy.deepcopy(Pparent[0])
for i in range(Pop):
if Best.fitness < Pparent[i].fitness:
Best = copy.deepcopy(Pparent[i])
return Best
if __name__ == '__main__':
w = 0.9
c1 = c2 = 2
Pop = 100
N = 2
Upper = [12.1, 5.8]
Lower = [-3.0, 4.1]
Vmax = 0.5
Vmin = 0.000005
Gmax = 200
Pparent = [Ind() for _ in range(Pop)]
for i in range(Pop):
Pparent[i].Init(Upper, Lower, Vmax, Vmin, N)
Best = Find_Best(Pparent, Pop)
for i in range(Gmax):
Bestcurrent = Find_Best(Pparent, Pop)
if Bestcurrent.fitness > Best.fitness:
Best = copy.deepcopy(Bestcurrent)
print(Best.fitness)
for j in range(Pop):
for k in range(N):
Pparent[j].v[k] = w * Pparent[j].v[k] + c1 * random.random() * (Best.x[k] - Pparent[j].x[k]) + c2 * random.random() * (Pparent[j].Bestx[k] - Pparent[j].x[k])
if abs(Pparent[j].v[k]) > Vmax:
if Pparent[j].v[k] > 0:
Pparent[j].v[k] = Vmax
else:
Pparent[j].v[k] = -Vmax
if abs(Pparent[j].v[k]) < Vmin:
if Pparent[j].v[k] > 0:
Pparent[j].v[k] = Vmin
else:
Pparent[j].x[k] = -Vmax
Pparent[j].x[k] += Pparent[j].v[k]
if Pparent[j].x[k] > Upper[k] or Pparent[j].x[k] < Lower[k]:
Pparent[j].x[k] = random.uniform(Lower[k], Upper[k])
Temp = copy.deepcopy(Pparent[j])
Pparent[j].Fitness()
if Pparent[j].fitness > Pparent[j].Bestfitness:
Pparent[j].Bestfitness = Pparent[j].fitness
Pparent[j].Bestx = copy.deepcopy(Pparent[j].x)