实验三、基本遗传算法设计实验
一、实验目的
1、了解基本遗传算法全局优化一般思路
2、掌握选择、交叉、变异算子如何实现
3、轮盘赌方法(roulette wheel model) 如何用程序方法实现
4、适应度函数设计方法
二、实验内容
1、初始化处理。
2、神经网络的MA TLAB实现
三、实验步骤
1、熟悉MATLAB开发环境
2、输入参考程序
3、设置断点,运行程序,观察运行结果
四、参考程序
1、初始化
function result=Initial(length)
for i=1:length
r=rand();
result(i)=round(r);
end
2、Matlab 实现----十进制与二进制转换
⏹function y=Dec(a,b,x,L)
⏹base=2.^((L-1):-1:0);
⏹y=dot(base,x);
⏹y=a+y*(b-a)/(2^L-1);
3、Matlab 实现---适应度函数计算
⏹function F=fitness(x)
⏹F=20+x+10*sin(4*x)+8*cos(3*x);
4、Matlab 实现----GA()
function [xv, fv]=GA(fitness,a,b,NP,NG,pc,pm)
L=24; %L=ceil(log((b-a)/eps+1))L=24
x=zeros(NP,L);
for i=1:NP;
x(i,:)=Initial(L);
fx(i)=fitness(Dec(a,b,x(i,:),L));
end
for k=1:NG
sumfx=sum(fx);
px=fx/sumfx;
ppx=0;
ppx(1)=px(1);
for i=2:NP
ppx(i)=ppx(i-1)+px(i);
end
for i=1:NP
sita=rand();
for n=1:NP
if sita<=ppx(n)
SelFather=n;
break;
end
end
SelMother=floor(rand()*(NP-1))+1;
posCut=floor(rand()*(L-2))+1;
r1=rand();
if r1<=pc
nx(i,1:posCut)=x(SelFather,1:posCut);
nx(i,(posCut+1):L)=x(SelMother,(posCut+1):L); r2=rand();
if r2<=pm
posMut=round(rand()*(L-1)+1);
nx(i,posMut)=~nx(i,posMut);
end
else
nx(i,:)=x(SelFather,:);
end
end
x=nx;
for i=1:NP
fx(i)=fitness(Dec(a,b,x(i,:),L));
end
end
fv=-inf;
for i=1:NP
fitx=fitness(Dec(a,b,x(i,:),L));
if fitx>fv
fv=fitx;
xv=Dec(a,b,x(i,:),L);
end
end
⏹
5、Matlab 实现----主程序
⏹a=0;
⏹b=10;
⏹NP=50;
⏹NG=10000;
⏹pc=0.6;
⏹pm=0.04;
⏹
⏹[xv, fv]=GA(@fitness,a,b,NP,NG,pc,pm);
⏹disp “最优个体"
⏹xv
⏹disp “最优适应度"
⏹
⏹Fv
6、实验结果
五、思考题
1、如何求最小值并考虑怎样修改程序:f (x )=x 2-10x+16z[0,31]的最小值(其中x 取整数)?
2、如何求最小值并考虑怎样修改程序:f (x )=x 2-10x+16[0,10]的最小值(其中要求x 精确
到小数点后六位)?。