Python-遗传算法君主交叉代码实现

import numpy as np

import matplotlib.pyplot as plt

# import math as mt

import seaborn as sns

sns.set_style('darkgrid')

def funcl(x):

     y=0

     for i in range(len(x)):

         y=y+x[i]**2

     return y

#%%

NP=100   # 初始化种群数

D=10    # 单条染色体基因数目 10

Pc=0.8  # 交叉率

Pm=0.1  # 变异率

G=200   # 最大遗传代数

Xs=20   # 上限

Xx=-20    # 下限

jiyi=np.random.rand(NP,D)

f=jiyi*(Xs-Xx)+Xx                              # 随机获得初始种群

FIT=[]

sortf=[]

trace=[]

xtrace=[]

xtracemin=[]

test=[]

for i in range(NP):

     FIT.append(funcl(f[i]))    # 适应度函数

sortFIT=np.sort(FIT)           # 升序排序

index= np.argsort(FIT)         # 升序对应索引

for i in range(len(f)):

     sortf.append(f[index[i]])  # 得到升序顺序对应的种群

#%% 遗传算法循环

for i in range(G):

     print(i)

     Emper=sortf[0]             # 产生君主

     nf=sortf                   # 出新的种群,在其基础上进行交叉、变异

     for M in range(0,NP,2):

         p=np.random.rand()     # 君主交叉

         if p

             for j in range(D):

                 nf[M][j]=Emper[j]  # 将君主的染色体给偶数索引的染色体,

# 我觉得这一步好像谈不上交叉,外汇跟单gendan5.com只是单纯地将君主染色体所占整体比重加大了

# 人为再加一手传统的交叉过程,到时候将这个过程删除,看看影响结果不   

     for M in range(0,NP,2):

         p=np.random.rand()     # 交叉

         if p

             q=np.random.randint(0,high=2,size=(1,D))[0].tolist()

             for j in range(D):

                 if q[j]==1:

                     temp=nf[M+1][j]

                     nf[M+1][j]=nf[M][j]

                     nf[M][j]=temp

                    

     for M in range(NP):        # 变异

         for n in range(D):

             p=np.random.rand()

             if p

                 nf[M][n]=np.random.rand()*(Xs-Xx)+Xx

     # 交叉变异结束之后,新一代 nf 加上前代 f 2*NP 个个体进行筛选

     newf=np.vstack((sortf,nf))         # 垂直方向累加两个 f

     newFIT=[]

     for j in range(len(newf)):

         newFIT.append(funcl(newf[j]))    # 适应度函数

     sortFIT=np.sort(newFIT)           # 升序排序

     index= np.argsort(newFIT)         # 升序对应索引

     maxfit=max(newFIT)

     minfit=min(newFIT)

     sortf=[]

     for j in range(len(f)):

         sortf.append(newf[index[j]])  # 得到升序顺序对应的种群

     trace.append(minfit)

     st=sortf[0].tolist()

     xtrace.append(st)

xvalue=[]

for i in range(len(xtrace)):

     xvalue.append(xtrace[i][0])

plt.plot(trace,color='green', marker='o',linewidth=2, markersize=3)

plt.xlabel('Number of iterations',fontsize = 10)

plt.ylabel('minyvalue',fontsize = 10)

plt.savefig('pic4',bbox_inches = 'tight',pad_inches = 0,dpi =350)

plt.close()

plt.scatter(list(range(0,200)),xvalue,color='red',s=3)  #s 参数设置点的大小

plt.xlabel('Number of iterations',fontsize = 10)

plt.ylabel('x',fontsize = 10)

plt.savefig('pic5',bbox_inches = 'tight',pad_inches = 0,dpi =350)

plt.close()


请使用浏览器的分享功能分享到微信等