零基础学习Python--粒子群算法PSO函数寻优-4
零基础学习Python--粒子群算法PSO函数寻优-4:链接:https://pan.baidu.com/s/1yECy3SICh_8a1QZzmtu5ww 提取码:n4ip
采用 np.argmax替代minIndex函数:
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from PIL import Image
from pylab import *
import matplotlib.pyplot as plt
import numpy as np
from random import *
#import fun
def funfitness(x1,x2):
y = (x1-0.5)**2+(x2-0.6)**2;
return y;
# 采用 np.argmax替代
# def minIndex(fitness, fitnesszbest):
# for i in range(len(fitness)):
# if(fitness == fitnesszbest):
# break;
# return i;
if __name__=="__main__":
c1 = 1.49445;
c2 = 1.49445;
maxg=200;
sizepop=20;
Vmax=1;
Vmin=-1;
popmax=5;
popmin=-5;
nVar = 2;
#print random.random()
# PSO algorithm parameters
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();
pop = popmin + (popmax-popmin)*random();
fitness = funfitness(pop,pop);
gbest = pop
gbest = pop
fitnessgbest = fitness
print(fitness)
fitnesszbest = min(fitness);
# index = fun.minIndex(fitness, fitnesszbest);
index = np.argmin( fitness )
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();
r2 = 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 = 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-' )
plt.show()
好棒一起学习 很好 的资源 谢谢楼主
很好 的资源 谢谢楼主 感谢分享感谢分享感谢分享 很好的资源谢谢楼主啦
页:
[1]