Halcom 发表于 2017-3-6 21:36:05

零基础学习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;








sunlei0417 发表于 2020-2-18 13:00:47

谢谢楼主无私的分享

pzhuzq 发表于 2020-2-20 01:29:29

谢谢分享。

sheepherder 发表于 2020-4-11 14:14:27

感谢大佬,谢谢分享。

therookie 发表于 2020-4-28 15:57:22

谢谢楼主无私的分享

LJN 发表于 2020-8-21 23:09:07


谢谢楼主无私的分享
页: [1]
查看完整版本: 零基础学习Python--粒子群算法PSO函数寻优-1