本人并未运行,如有问题请与作者联系,如有侵权请告之
转载:http://blog.chinaunix.net/u2/67622/showart_665510.html
%IAGA
function best=ga
clear
MAX_gen=200; %最大迭代步数
best.max_f=0; %当前最大的适应度
STOP_f=14.5; %停止循环的适应度
RANGE=[0 255]; %初始取值范围[0 255]
SPEEDUP_INTER=5; %进入加速迭代的间隔
advance_k=0; %优化的次数
popus=init; %初始化
for gen=1:MAX_gen
fitness=fit(popus,RANGE); %求适应度
f=fitness.f;
picked=choose(popus,fitness); %选择
popus=intercross(popus,picked); %杂交
popus=aberrance(popus,picked); %变异
if max(f)>best.max_f
advance_k=advance_k+1;
x_better(advance_k)=fitness.x;
best.max_f=max(f);
best.popus=popus;
best.x=fitness.x;
end
if mod(advance_k,SPEEDUP_INTER)==0
RANGE=minmax(x_better);
RANGE
advance=0;
end
end
return;
function popus=init%初始化
M=50;%种群个体数目
N=30;%编码长度
popus=round(rand(M,N));
return;
function fitness=fit(popus,RANGE)%求适应度
[M,N]=size(popus);
fitness=zeros(M,1);%适应度
f=zeros(M,1);%函数值
A=RANGE(1);B=RANGE(2);%初始取值范围[0 255]
for m=1:M
x=0;
for n=1:N
x=x+popus(m,n)*(2^(n-1));
end
x=x*((B-A)/(2^N))+A;
for k=1:5
f(m,1)=f(m,1)-(k*sin((k+1)*x+k));
end
end
f_std=(f-min(f))./(max(f)-min(f));%函数值标准化
fitness.f=f;fitness.f_std=f_std;fitness.x=x;
return;
function picked=choose(popus,fitness)%选择
f=fitness.f;f_std=fitness.f_std;
[M,N]=size(popus);
choose_N=3; %选择choose_N对双亲
picked=zeros(choose_N,2); %记录选择好的双亲
p=zeros(M,1); %选择概率
d_order=zeros(M,1);
%把父代个体按适应度从大到小排序
f_t=sort(f,'descend');%将适应度按降序排列
for k=1:M
x=find(f==f_t(k));%降序排列的个体序号
d_order(k)=x(1);
end
for m=1:M
popus_t(m,:)=popus(d_order(m),:);
end
popus=popus_t;
f=f_t;
p=f_std./sum(f_std); %选择概率
c_p=cumsum(p)'; %累积概率
for cn=1:choose_N
picked(cn,1)=roulette(c_p); %轮盘赌
picked(cn,2)=roulette(c_p); %轮盘赌
popus=intercross(popus,picked(cn,:));%杂交
end
popus=aberrance(popus,picked);%变异
return;
function popus=intercross(popus,picked) %杂交
[M_p,N_p]=size(picked);
[M,N]=size(popus);
for cn=1:M_p
p(1)=ceil(rand*N);%生成杂交位置
p(2)=ceil(rand*N);
p=sort(p);
t=popus(picked(cn,1),p(1):p(2));
popus(picked(cn,1),p(1):p(2))=popus(picked(cn,2),p(1):p(2));
popus(picked(cn,2),p(1):p(2))=t;
end
return;
function popus=aberrance(popus,picked) %变异
P_a=0.05;%变异概率
[M,N]=size(popus);
[M_p,N_p]=size(picked);
U=rand(1,2);
for kp=1:M_p
if U(2)>=P_a %如果大于变异概率,就不变异
continue;
end
if U(1)>=0.5
a=picked(kp,1);
else
a=picked(kp,2);
end
p(1)=ceil(rand*N);%生成变异位置
p(2)=ceil(rand*N);
if popus(a,p(1))==1%0 1变换
popus(a,p(1))=0;
else
popus(a,p(1))=1;
end
if popus(a,p(2))==1
popus(a,p(2))=0;
else
popus(a,p(2))=1;
end
end
return;
function picked=roulette(c_p) %轮盘赌
[M,N]=size(c_p);
M=max([M N]);
U=rand;
if U<c_p(1)
picked=1;
return;
end
for m=1:(M-1)
if U>c_p(m) & U<c_p(m+1)
picked=m+1;
break;
end
end