记录自己的python和智能算法学习之路。
class PSO:
'''简易粒子群算法'''
def __init__(self,c1,c2,maxgen,sizepop,popmax,popmin,Vmax,Vmin):
'''
遗传算法相关参数设定
c1,c2:速度更新参数
maxgen:迭代次数
sizepop:种群规模
popmax,popmin:个体大小
Vmax,Vmin:个体速度约束
'''
self.c1=c1
self.c2=c2
self.maxgen=maxgen
self.sizepop=sizepop
self.popmax=popmax
self.popmin=popmin
self.Vmax=Vmax
self.Vmin=Vmin
self.result=[None]*maxgen
self.pop=[None]*self.sizepop
self.V=[None]*self.sizepop
self.fitness=[None]*self.sizepop
def init_pop(self):
'''种群初始化'''
from random import uniform
import math
for i in range(0,self.sizepop):
self.pop[i]=[2*uniform(-1,1),2*uniform(-1,1)]
self.V[i]=[0.5*uniform(-1,1),0.5*uniform(-1,1)]
self.fitness[i]=self.fun(self.pop[i])
def fun(self,partical):
'''计算种群适应度'''
from math import sin,cos,sqrt,exp,pi
x1=partical[0]
x2=partical[1]
y=sin(sqrt(x1**2+x2**2))/sqrt(x1**2+x2**2)+exp(1/2*(cos(2*pi*x1)+cos(2*pi*x2)))-2.71289
return y
def init_extremum(self):
'''寻找初始极值'''
bestfitness=max(self.fitness)
bestindex=self.fitness.index(bestfitness)
self.zbest=self.pop[bestindex][:]
self.gbest=self.pop[:]
self.fitnessgbest=self.fitness[:]
self.fitnesszbest=bestfitness
def iteration_optimizition(self):
'''迭代寻优'''
import random
for i in range(0,self.maxgen):
for j in range(0,self.sizepop):
r1=random.random()
r2=random.random()
for k in range(0,len(self.V[j])):
self.V[j][k]=self.V[j][k]+self.c1*r1*(self.gbest[j][k]-self.pop[j][k])+self.c2*r2*(self.zbest[k]-self.pop[j][k])
if self.V[j][k]>self.Vmax:
self.V[j][k]=self.Vmax
elif self.V[j][k]<self.Vmin:
self.V[j][k]=self.Vmin
self.pop[j][k]=self.pop[j][k]+0.5*self.V[j][k]
if self.pop[j][k]>self.popmax:
self.pop[j][k]=self.popmax
elif self.pop[j][k]<self.popmin:
self.pop[j][k]=self.popmin
self.fitness[j]=self.fun(self.pop[j])
for j in range(0,self.sizepop):
if self.fitness[j]>self.fitnessgbest[j]:
self.gbest[j]=self.pop[j]
self.fitnessgbest[j]=self.fitness[j]
if self.fitness[j]>self.fitnesszbest:
self.zbest=self.pop[j][:]
self.fitnesszbest=self.fitness[j]
self.result[i]=self.fitnesszbest
import matplotlib.pyplot as plt
myPSO=PSO(1.49445,1.49445,300,20,2,-2,0.5,-0.5)
myPSO.init_pop()
myPSO.init_extremum()
myPSO.iteration_optimizition()
print("极值",myPSO.result[299],"极值点",myPSO.zbest)
plt.plot(myPSO.result)
plt.show()
'算法并不能总是寻找到极值点附近,偶尔会陷入局部最优。
好好学习,天天向上