|
零基础学习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 = [[0 for x in range(nVar)] for y in range(sizepop)]
- gbest = [[0 for x in range(nVar)] for y in range(sizepop)]
- fitness = [0 for x in range(sizepop)]
- fitnessgbest = [0 for x in range(sizepop)]
- zbest = [0 for x in range(nVar)]
- V = [[0 for x in range(nVar)] for y in range(sizepop)]
- # init pop
- for i in range(sizepop):
- pop[i][0] = popmin + (popmax-popmin)*random.random();
- pop[i][1] = popmin + (popmax-popmin)*random.random();
- fitness[i] = fun.funfitness(pop[i][0],pop[i][1]);
- gbest[i][0] = pop[i][0]
- gbest[i][1] = pop[i][1]
- fitnessgbest[i] = fitness[i]
- print fitness[i]
- fitnesszbest = min(fitness);
- index = fun.minIndex(fitness, fitnesszbest);
- zbest[0] = pop[index][0]
- zbest[1] = pop[index][1]
- print zbest
- #plot(range(sizepop), fitness,'r*-')
- #plot( fitness,'r*-')
- #show()
- fitness_iter = [0 for x in range(maxg)]
- # main loop
- for i in range(maxg):
- for j in range(sizepop):
- # update vel
- r1 = random.random();
- r2 = random.random();
- V[j][0] = V[j][0] + c1*r1*(gbest[j][0]-pop[j][0])+c2*r2*(zbest[0]-pop[j][0]);
- V[j][1] = V[j][1] + c1*r1*(gbest[j][1]-pop[j][1])+c2*r2*(zbest[1]-pop[j][1]);
- if (V[j][0]>Vmax):
- V[j][0] = Vmax;
- elif (V[j][0]<Vmin):
- V[j][0] = Vmin;
- if (V[j][1]>Vmax):
- V[j][1] = Vmax;
- elif (V[j][1]<Vmin):
- V[j][1] = Vmin;
- # update position
- pop[j][0] = pop[j][0] + 0.5*V[j][0];
- pop[j][1] = pop[j][1] + 0.5*V[j][1];
- if (pop[j][0]>popmax):
- pop[j][0] = popmax;
- elif (pop[j][0]<popmin):
- pop[j][0] = popmin;
- if (pop[j][1]>popmax):
- pop[j][1] = popmax;
- elif (pop[j][1]<popmin):
- pop[j][1] = popmin;
-
- fitness[j] = fun.funfitness(pop[j][0],pop[j][1]);
- if (fitness[j]<fitnessgbest[j]):
- fitnessgbest[j] = fitness[j]
- gbest[j][0] = pop[j][0];
- gbest[j][1] = pop[j][1];
- if (fitness[j]<fitnesszbest):
- fitnesszbest= fitness[j];
- zbest[0] = pop[j][0];
- zbest[1] = pop[j][1];
- fitness_iter[i] = 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[i] == fitnesszbest):
- break;
- return i;
复制代码
|
|