分类: Python/Ruby
2021-08-11 17:19:23
import numpy as np
import matplotlib.pyplot as plt
# import math as mt
import seaborn as sns
sns.set_style('darkgrid')
x=np.arange(0,10,0.02)
y=x+10*np.sin(5*x)+7*np.cos(4*x)
plt.plot(x,y) #画原函数
plt.title('Primitive function')
plt.xlabel('x',fontsize = 10)
plt.ylabel('y',fontsize = 10)
plt.savefig('pic1',bbox_inches = 'tight',pad_inches = 0,dpi =350)
plt.close()
def funcl(x):
y=y=x+10*np.sin(5*x)+7*np.cos(4*x)
return y
#%%
NP=50 #初始化种群数
L=20 #二进制位串长度
Pc=0.8 #交叉率
Pm=0.3 #变异率
G=100 #最大遗传代数
Xs=10 #上限
Xx=0 #下限
f=np.random.randint(0,high=2,size=(NP,L)) #生成随机初始种群
fit=np.zeros((1,100))[0].tolist()
x=np.zeros((1,100))[0].tolist()
trace=[]
xtrace=[]
#%%遗传算法循环
for i in range(G):
print(i)
nf=f
for M in range(0,NP,2):
p=np.random.rand() #交叉
if p
q=np.random.randint(0,high=2,size=(1,L))[0].tolist()
for j in range(L):
if q[j]==1:
temp=nf[M+1][j]
nf[M+1][j]=nf[M][j]
nf[M][j]=temp
j=1
while j<=(NP*Pm):
h=np.random.randint(1,high=NP) #变异
for k in range(round(L*Pm)):
g=np.random.randint(1,high=L)
nf[h][g]=(not nf[h][g])+0 #取反操作,python和matlab不一样
j+=1
#交叉变异结束之后,新一代nf加上前代f共2*NP个个体进行筛选
newf=np.vstack((f,nf))
for j in range(newf.shape[0]):
U=newf[j]
m=0
for k in range(L):
m=U[k]*(2**(k-1))+m #将二进制解码为定义域范围内十进制
x[j]=Xx+m*(Xs-Xx)/(2**(L-1))
fit[j]=funcl(x[j]) #适应度函数
maxfit=max(fit)
minfit=min(fit)
if maxfit==minfit:
break
rr=fit.index(maxfit)
fbest=f[rr]
xbest=x[rr]
Fit=(np.array(fit)-minfit)/(maxfit-minfit)
sum_Fit=sum(Fit) #概率筛选复制操作(不是简单的复制,我们是根据适应函数给导向的)
Pfit=Fit/sum_Fit
indexnf=np.arange(0,100).tolist()
ng=[]
for dex in range(NP):
ng.append(np.random.choice(indexnf,p=Pfit))
for j in range(NP):
f[j]=newf[ng[j]]
f[0]=fbest
trace.append(maxfit)
xtrace.append(xbest)
plt.plot(trace,color='green', marker='o',linewidth=2, markersize=3)
plt.xlabel('Number of iterations',fontsize = 10)
plt.ylabel('maxyvalue',fontsize = 10)
plt.savefig('pic3',bbox_inches = 'tight',pad_inches = 0,dpi =350)
plt.close()
plt.plot(xtrace,color='m', marker='o',linewidth=2, markersize=3)
plt.xlabel('Number of iterations',fontsize = 10)
plt.ylabel('Corresponding xvalue',fontsize = 10)
plt.savefig('pic2',bbox_inches = 'tight',pad_inches = 0,dpi =350)
plt.close()