零基础学习Python--粒子群算法PSO函数寻优-1
零基础学习Python--粒子群算法PSO函数寻优:(菜鸟编程solemnysw)版权声明:本文为博主原创文章,未经博主允许不得转载。严格禁止其它商用行为!
百度网盘链接:
链接:http://pan.baidu.com/s/1c19Qjjq
具体链接在halcom.cn论坛,联系人QQ:3283892722
该论坛是一个学习交流平台,我会逐一的和大家分享学习。
欢迎大家录制视频,你可在论坛进行打赏分享。
视频专用播放器:http://halcom.cn/forum.php?mod=viewthread&tid=258&extra=page%3D1主函数:
from PIL import Image
from pylab import *
import string
import matplotlib.pyplot as plt
import numpy as np
import random
import fun
#print random.random()
# PSO algorithm parameters
c1 = 1.49445;
c2 = 1.49445;
maxg=200;
sizepop=20;
Vmax=1;
Vmin=-1;
popmax=5;
popmin=-5;
nVar = 2;
pop = [ for y in range(sizepop)]
gbest = [ for y in range(sizepop)]
fitness =
fitnessgbest =
zbest =
V = [ for y in range(sizepop)]
# init pop
for i in range(sizepop):
pop = popmin + (popmax-popmin)*random.random();
pop = popmin + (popmax-popmin)*random.random();
fitness = fun.funfitness(pop,pop);
gbest = pop
gbest = pop
fitnessgbest = fitness
print fitness
fitnesszbest = min(fitness);
index = fun.minIndex(fitness, fitnesszbest);
zbest = pop
zbest = pop
print zbest
#plot(range(sizepop), fitness,'r*-')
#plot( fitness,'r*-')
#show()
fitness_iter =
# main loop
for i in range(maxg):
for j in range(sizepop):
# update vel
r1 = random.random();
r2 = random.random();
V = V + c1*r1*(gbest-pop)+c2*r2*(zbest-pop);
V = V + c1*r1*(gbest-pop)+c2*r2*(zbest-pop);
if (V>Vmax):
V = Vmax;
elif (V<Vmin):
V = Vmin;
if (V>Vmax):
V = Vmax;
elif (V<Vmin):
V = Vmin;
# update position
pop = pop + 0.5*V;
pop = pop + 0.5*V;
if (pop>popmax):
pop = popmax;
elif (pop<popmin):
pop = popmin;
if (pop>popmax):
pop = popmax;
elif (pop<popmin):
pop = popmin;
fitness = fun.funfitness(pop,pop);
if (fitness<fitnessgbest):
fitnessgbest = fitness
gbest = pop;
gbest = pop;
if (fitness<fitnesszbest):
fitnesszbest= fitness;
zbest = pop;
zbest = pop;
fitness_iter = fitnesszbest;
print "最优解:"
print zbest
plot( fitness_iter,'b-' )
show()相应的fun子函数如下:
def funfitness(x1,x2):
y = (x1-0.5)**2+(x2-0.6)**2;
return y;
def minIndex(fitness, fitnesszbest):
for i in range(len(fitness)):
if(fitness == fitnesszbest):
break;
return i;
谢谢楼主无私的分享 谢谢分享。 感谢大佬,谢谢分享。 谢谢楼主无私的分享
谢谢楼主无私的分享
页:
[1]