Halcom 发表于 2017-3-7 13:19:15

零基础学习Python--粒子群算法PSO函数寻优-2

零基础学习Python--粒子群算法PSO函数寻优-2:(菜鸟编程solemnysw)
版权声明:本文为博主原创文章,未经博主允许不得转载。严格禁止其它商用行为!
百度网盘链接:
链接:http://pan.baidu.com/s/1hrYe6cW
链接:https://pan.baidu.com/s/1yECy3SICh_8a1QZzmtu5ww 提取码:n4ip

具体链接在halcom.cn论坛,联系人QQ:3283892722
该论坛是一个学习交流平台,我会逐一的和大家分享学习。
欢迎大家录制视频,你可在论坛进行打赏分享。
视频专用播放器:http://halcom.cn/forum.php?mod=viewthread&tid=258&extra=page%3D1from PIL import Image
from pylab import *
import string
import numpy
from numpy import random
import fun
# web('halcom.cn')

# PSO algorithm parameters
c1 = 1.49445;
c2 = 1.49445;
maxg=50;
sizepop=20;
Vmax=1;
Vmin=-1;
popmax= numpy.array( [ , ] );
popmin = numpy.array( [ [-5], [-4] ] );
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( [ nVar, 1] );
    V = numpy.array( [ , ] );
    fitness = fun.funfitness2(pop);
    gbest = pop
    fitnessgbest = fitness
fitnesszbest = min(fitness);
index = fun.minIndex(fitness, fitnesszbest);
zbest = pop

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);
      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;
      if (pop>popmax):
            pop = popmax;
      elif (pop<popmin):
            pop = popmin;
      if (pop>popmax):
            pop = popmax;
      elif (pop<popmin):
            pop = popmin;
      
      # update fitness
      fitness = fun.funfitness2(pop);

      # compare
      if (fitness<fitnessgbest):
            fitnessgbest = fitness
            gbest = pop;
            gbest = pop;
      if (fitness<fitnesszbest):
            fitnesszbest= fitness;
            zbest = pop;
    fitness_iter = fitnesszbest;

print "best solution is:"
print zbest

print "min objective value is:"
print fitnesszbest

plot( fitness_iter,'b-' )
show()子函数如下:
def funfitness(x1,x2):
    y = (x1-0.5)**2+(x2-0.6)**2;
    return y;

def funfitness2(x):
    y = (x-0.5)**2+(x-0.6)**2;
    return y;


def minIndex(fitness, fitnesszbest):
    for i in range(len(fitness)):
      if(fitness == fitnesszbest):
            break;
    return i;







页: [1]
查看完整版本: 零基础学习Python--粒子群算法PSO函数寻优-2