關鍵在於賦值的關係:
淺賦值:對原來的引用
深度賦值:纔是對值影響
#! /user/bin/env python
#encoding=utf-8
__author__ = 'chw'
import time
import numpy as np
import copy
import matplotlib.pyplot as plt
start=time.time()
c1=2
c2=2
PopMax=100
Vmax=PopMax/10
SizePop=20
D=2
Maxgen=200
Wmax=0.9
Wmin=0.4
pop=np.random.rand(SizePop,D)*2*PopMax-PopMax
v=np.random.rand(SizePop,D)*Vmax*2-Vmax
def fun(x1,x2):
return x1**2+x2**2
fitness=np.zeros((SizePop,1),dtype=float)
for i in xrange(SizePop):
fitness[i]=fun(pop[i,0],pop[i,1])
bestfitness=max(fitness)
for i in xrange(SizePop):
if fitness[i]==bestfitness:
zbest=pop[i,:]
break
gbest=pop
fitnessgbest=fitness
fitnesszbest=bestfitness
# yy=np.zeros((Maxgen,1),dtype=float)
yy=np.random.rand(Maxgen,1)
x=np.arange(Maxgen)
for i in xrange(Maxgen):
if i==0:
w=Wmax
else:
w=Wmax-i*0.5/Maxgen
for j in xrange(SizePop):
v[j,:]=w*v[j,:]+c1*np.random.rand()*(gbest[j,:]-pop[j,:])+c2*np.random.rand()*(zbest-pop[j,:])
pop[j,:]=pop[j,:]+v[j,:]
for t in xrange(D):
if pop[j,t]>PopMax:
pop[j,t]=PopMax
if pop[j,t]<-PopMax:
pop[j,t]=-PopMax
if v[j,t]>Vmax:
v[j,t]=Vmax
if v[j,t]<-Vmax:
v[j,t]=-Vmax
fitness[j]=fun(pop[j,0],pop[j,1])
for j in xrange(SizePop):
if fitness[j]<fitnessgbest[j]:
gbest[j,:]=copy.deepcopy(pop[j,:])
fitnessgbest[j]=copy.deepcopy(fitness[j])
for j in xrange(SizePop):
if fitnessgbest[j]<fitnesszbest:
zbest=copy.deepcopy(gbest[j,:])
fitnesszbest=copy.deepcopy(fitnessgbest[j])
yy[i]=copy.deepcopy(fitnesszbest)
print zbest
print fitnesszbest
plt.figure()
plt.plot(x,yy)
plt.show()
print time.time()-start
# s1=[0,1,2]
# s2=[2,3,4]
# plt.figure()
# plt.plot(s1,s2)
# plt.show()
參考:http://blog.csdn.net/just_do_it_123/article/details/50927348
http://www.jb51.net/article/61902.htm