遗传算法计算函数最小值f(x)=∑xi^2 基于matlib与python对比
采用种群数100,实数编码,进化100代交叉概率0.8,变异概率0.1
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
#适应度函数
def func2(x):
summ=sum(pow(x,2))
return summ
D=10
NP=100
Xs=20
Xx=-20
G=100
Pc=0.8
Pm=0.1
nf=np.zeros((D,NP))
f=np.random.rand(D,NP)*(Xs-Xx)+Xx
Sortf=np.zeros((D,NP))
NSortf=np.zeros((D,NP))
MSLL=np.zeros(NP)
NMSLL=np.zeros(NP)
NMSLL1=np.zeros(NP)
#Index=np.zeros(NP)
trace=[]
for w in range(NP):
MSLL[w]=func2(f[:,w]) #MSLL是f的适应度
Index=np.argsort(MSLL)
SortMSLL=sorted(MSLL) #SortMSLL是从低到高排序后的MSLL
Sortf=f[:,Index] #由f升序得到
for gen in range(G):
Emper=Sortf[:,0] #选择君主
NoPoint=round(D*Pc) #交叉点个数
PoPoint=np.random.randint(0,D,[NoPoint,int(NP/2)])
nf=Sortf
for i in range(int(NP/2)):
nf[:,2*i]=Emper
nf[:,2*i+1]=Sortf[:,2*i+1]
for k in range(NoPoint):
nf[PoPoint[k,i],2*i]=nf[PoPoint[k,i],2*i+1]
nf[PoPoint[k,i],2*i+1]=Emper[PoPoint[k,i]]
#变异操作
for by in range(NP):
for i in range(D):
r=np.random.rand()
if r<Pm:
nf[i,by]=np.random.rand()*(Xs-Xx)+Xx
#子群按适应度排序
for i in range(NP):
NMSLL[i]=func2(nf[:,i])
Index=np.argsort(NMSLL)
NSortMSLL=sorted(NMSLL)
NSortf=nf[:,Index]
f1=np.hstack((Sortf,NSortf))
MSLL1=np.hstack((SortMSLL,NSortMSLL))
Index=np.argsort(MSLL1)
SortMSLL1=sorted(MSLL1)
Sortf1=f1[:,Index]
SortMSLL=SortMSLL1[0:NP]
Sortf=Sortf1[:,0:NP]
trace.append(SortMSLL[0])
MATLIB
```python
clear all
close all
clc
D=10
NP=100
Xs=20
Xx=-20
G=25
f=zeros(D,NP)
nf=zeros(D,NP)
Pc=0.8
Pm=0.1
f=rand(D,NP)*(Xs-Xx)+Xx
for np=1:NP
MSLL(np)=func2(f(:,np))
end
[SortMSLL,Index]=sort(MSLL)
Sortf=f(:,Index)
%%%%君主方式进行选择交叉
for gen=1:G
Emper=Sortf(:,1) %君主染色体
NoPoint=round(D*Pc)
PoPoint=randi([1,D],NoPoint,NP/2)
nf=Sortf
for i=1:NP/2
nf(:,2*i-1)=Emper
nf(:,2*i)=Sortf(:,2*i)
for k=1:NoPoint
nf(PoPoint(k,i),2*i-1)=nf(PoPoint(k,i),2*i)
nf(PoPoint(k,i),2*i)=Emper(PoPoint(k,i))
end
end
for m =1:NP
for n=1:D
r=rand(1,1)
if r<Pm
nf(n,m)=rand(1,1)*(Xs-Xx)+Xx
end
end
end
for np=1:NP
NMSLL(np)=func2(nf(:,np))
end
[NSortMSLL,Index]=sort(NMSLL)
NSortf=nf(:,Index)
f1=[Sortf,NSortf]
MSLL1=[SortMSLL,NSortMSLL]
[SortMSLL1,Index]=sort(MSLL1)
Sortf1=f1(:,Index)
SortMSLL=SortMSLL1(1:NP)
Sortf=Sortf1(:,1:NP)
trace(gen)=SortMSLL(1)
end
bestf=Sortf(:,1)
trace(end)
figure
plot(trace)
xlabel('迭代次数')
ylabel('目标函数值')
function result=func2(x)
sumn=sum(x.^2)
result=sumn
end