logo资料库

遗传算法的各种应用示例(含源码).doc

第1页 / 共11页
第2页 / 共11页
第3页 / 共11页
第4页 / 共11页
第5页 / 共11页
第6页 / 共11页
第7页 / 共11页
第8页 / 共11页
资料共11页,剩余部分请下载后查看
function youhuafun D=code; N=50; % Tunable maxgen=50; % Tunable crossrate=0.5; %Tunable muterate=0.08; %Tunable generation=1; num = length(D); fatherrand=randint(num,N,3); score = zeros(maxgen,N); while generation<=maxgen ind=randperm(N-2)+2; % 随机配对交叉 A=fatherrand(:,ind(1:(N-2)/2)); B=fatherrand(:,ind((N-2)/2+1:end)); % 多点交叉 rnd=rand(num,(N-2)/2); ind=rnd tmp=A(ind); A(ind)=B(ind); B(ind)=tmp; % % 两点交叉 tmprnd=rand; tmpind=tmprnd difind=[0,diff(t mpind)]; if ~any(difind) difind(1)=1; end childind(k)=scoreind(logical(difind)); end fatherrand=fatherrand(:,childind); generation=generation+1; end % score maxV=max(score,[],2); minV=11*300-maxV; plot(minV,'*');title('各代的目标函数值'); F4=D(:,4); FF4=F4-fatherrand(:,1); FF4=max(FF4,1); D(:,5)=FF4; save DData D function D=code load youhua.mat % properties F2 and F3 F1=A(:,1); F2=A(:,2); F3=A(:,3); for kk=1:(N-2)/2 rndtmp=randint(1,1,num)+1; tmp=A(1:rndtmp,kk); A(1:rndtmp,kk)=B(1:rndtmp,kk); B(1:rndtmp,kk)=tmp; % % % % % % end if (max(F2)>1450)||(min(F2)<=900) fatherrand=[fatherrand(:,1:2),A,B]; error('DATA property F2 exceed it''s range % 变异 rnd=rand(num,N); ind=rnd [m,n]=size(ind); tmp=randint(m,n,2)+1; tmp(:,1:2)=0; fatherrand=tmp+fatherrand; fatherrand=mod(fatherrand,3); % fatherrand(ind)=tmp; (900,1450]') end % get group property F1 of data, according to F2 value F4=zeros(size(F1)); for ite=11:-1:1 index=find(F2<=900+ite*50); F4(index)=ite; end D=[F1,F2,F3,F4]; %评价、选择 function ScoreN=scorefun(fatherrand,D) scoreN=scorefun(fatherrand,D);% 求得 N 个个体的评价 F3=D(:,3); 函数 score(generation,:)=scoreN; [scoreSort,scoreind]=sort(scoreN); sumscore=cumsum(scoreSort); sumscore=sumscore./sumscore(end); F4=D(:,4); N=size(fatherrand,2); FF4=F4*ones(1,N); FF4rnd=FF4-fatherrand; FF4rnd=max(FF4rnd,1); childind(1:2)=scoreind(end-1:end); ScoreN=ones(1,N)*300*11; for k=3:N % 这里有待优化
for k=1:N FF4k=FF4rnd(:,k); for ite=1:11 F0index=find(FF4k==ite); if ~isempty(F0index) tmpMat=F3(F0index); tmpSco=sum(tmpMat); ScoreBin(ite)=mod(tmpSco,300); end end Scorek(k)=sum(ScoreBin); end ScoreN=ScoreN-Scorek; 遗传算法实例: % 下面举例说明遗传算法 % % 求下列函数的最大值 % % f(x)=10*sin(5x)+7*cos(4x) x∈[0,10] % % 将 x 的值用一个 10 位的二值形式表示为二值问题,一个 10 位的二值数提供的分辨率是每为 (10-0)/(2^10-1)≈0.01 。 % % 将变量域 [0,10] 离散化为二值域 [0,1023], x=0+10*b/1023, 其中 b 是 [0,1023] 中的一个二值数。 % % % %--------------------------------------------------------------------------------- -----------------------------% %--------------------------------------------------------------------------------- -----------------------------% % 编程 %----------------------------------------------- % 2.1 初始化(编码) % initpop.m 函数的功能是实现群体的初始化,popsize 表示群体 的大小,chromlength 表示染色体的长度(二值数的长度), % 长度大小取决于变量的二进制编码的长度(在本例中取 10 位)。 %遗传算法子程序 %Name: initpop.m %初始化 function pop=initpop(popsize,chromlength) pop=round(rand(popsize,chromlength)); % rand 随机产生每个 单元为 {0,1} 行数为 popsize,列数为 chromlength 的矩阵, % roud 对矩阵的每个单元进行圆整。这样产生的初始种群。 % 2.2 计算目标函数值 % 2.2.1 将二进制数转化为十进制数(1) %遗传算法子程序 %Name: decodebinary.m %产生 [2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为 十进制 function pop2=decodebinary(pop) [px,py]=size(pop); %求 pop 行和列数 for i=1:py pop1(:,i)=2.^(py-i).*pop(:,i); end pop2=sum(pop1,2); %求 pop1 的每行之和 % 2.2.2 将二进制编码转化为十进制数(2) % decodechrom.m 函数的功能是将染色体(或二进制编码)转换 为十进制,参数 spoint 表示待解码的二进制串的起始位置 % (对于多个变量而言,如有两个变量,采用 20 为表示,每个变 量为 10,则第一个变量从 1 开始,另一个变量从 11 开始。本例 为 1), % 参数 1ength 表示所截取的长度(本例为 10)。 %遗传算法子程序 %Name: decodechrom.m %将二进制编码转换成十进制 function pop2=decodechrom(pop,spoint,length) pop1=pop(:,spoint:spoint+length-1); pop2=decodebinary(pop1); % 2.2.3 计算目标函数值 % calobjvalue.m 函数的功能是实现目标函数的计算,其公式采 用本文示例仿真,可根据不同优化问题予以修改。 %遗传算法子程序 %Name: calobjvalue.m %实现目标函数的计算 function [objvalue]=calobjvalue(pop) temp1=decodechrom(pop,1,10); %将 pop 每行转化成十进制数 x=temp1*10/1023; %将二值域 中的数转化为变量域 的数 objvalue=10*sin(5*x)+7*cos(4*x); %计算目标函数值 % 2.3 计算个体的适应值 %遗传算法子程序 %Name:calfitvalue.m %计算个体的适应值 function fitvalue=calfitvalue(objvalue) global Cmin; Cmin=0; [px,py]=size(objvalue); for i=1:px if objvalue(i)+Cmin>0 temp=Cmin+objvalue(i); else temp=0.0;
end fitvalue(i)=temp; end fitvalue=fitvalue'; % 2.4 选择复制 % 选择或复制操作是决定哪些个体可以进入下一代。程序中采 用赌轮盘选择法选择,这种方法较易实现。 % 根据方程 pi=fi/∑fi=fi/fsum ,选择步骤: % 1) 在第 t 代,由(1)式计算 fsum 和 pi % 2) 产生 {0,1} 的随机数 rand( .),求 s=rand( .)*fsum % 3) 求 ∑fi≥s 中最小的 k ,则第 k 个个体被选中 % 4) 进行 N 次 2)、3)操作,得到 N 个个体,成为第 t=t+1 代种群 %遗传算法子程序 %Name: selection.m %选择复制 function [newpop]=selection(pop,fitvalue) totalfit=sum(fitvalue); %求适应值之和 fitvalue=fitvalue/totalfit; %单个个体被选择的概率 fitvalue=cumsum(fitvalue); % 如 fitvalue=[1 2 3 4] , 则 cumsum(fitvalue)=[1 3 6 10] [px,py]=size(pop); ms=sort(rand(px,1)); %从小到大排列 fitin=1; newin=1; while newin<=px if(ms(newin))
end % 2.7 求出群体中最大得适应值及其个体 %遗传算法子程序 %Name: best.m %求出群体中适应值最大的值 function [bestindividual,bestfit]=best(pop,fitvalue) [px,py]=size(pop); bestindividual=pop(1,:); bestfit=fitvalue(1); for i=2:px if fitvalue(i)>bestfit bestindividual=pop(i,:); bestfit=fitvalue(i); end end % 2.8 主程序 %遗传算法主程序 %Name:genmain05.m clear clf popsize=20; %群体大小 chromlength=10; %字符串长度(个体长度) pc=0.6; %交叉概率 pm=0.001; %变异概率 pop=initpop(popsize,chromlength); %随机产生初始群体 for i=1:20 %20 为迭代次数 [objvalue]=calobjvalue(pop); %计算目标函数 fitvalue=calfitvalue(objvalue); %计算群体中每个个体的适应度 [newpop]=selection(pop,fitvalue); %复制 [newpop]=crossover(pop,pc); %交叉 [newpop]=mutation(pop,pc); %变异 [bestindividual,bestfit]=best(pop,fitvalue); %求出群体中适应值 最大的个体及其适应值 y(i)=max(bestfit); n(i)=i; pop5=bestindividual; x(i)=decodechrom(pop5,1,chromlength)*10/1023; pop=newpop; end fplot('10*sin(5*x)+7*cos(4*x)',[0 10]) hold on plot(x,y,'r*') hold off [z index]=max(y); %计算最大值及其位置 x5=x(index)%计算最大值对应的 x 值 y=z 【问题】求 f(x)=x 10*sin(5x) 7*cos(4x)的最大值,其中 0<=x<=9 【分析】选择二进制编码,种群中的个体数目为 10,二进制编码 长度为 20,交叉概率为 0.95,变异概率为 0.08 【程序清单】 %编写目标函数 function[sol,eval]=fitness(sol,options) x=sol(1); eval=x 10*sin(5*x) 7*cos(4*x); %把上述函数存储为 fitness.m 文件并放在工作目录下 initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小 为 10 [x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',... [0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25 次 遗传迭代 运算借过为:x = 7.8562 24.8553(当 x 为 7.8562 时,f(x)取最大值 24.8553) 注:遗传算法一般用来取得近似最优解,而不是最优解。 遗传算法实例 2 【问题】在-5<=Xi<=5,i=1,2 区间内,求解 f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2 x2.^2)))-exp(0.5*(cos(2*pi*x1) cos(2*pi*x2))) 22.71282 的 最 小 值。 【分析】种群大小 10,最大代数 1000,变异率 0.1,交叉率 0.3 【程序清单】 %源函数的 matlab 代码 function [eval]=f(sol) numv=size(sol,2); x=sol(1:numv); eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x)) /numv) 22.71282; %适应度函数的 matlab 代码 function [sol,eval]=fitness(sol,options) numv=size(sol,2)-1; x=sol(1:numv); eval=f(x); eval=-eval; %遗传算法的 matlab 代码 bounds=ones(2,1)*[-5 5]; [p,endPop,bestSols,trace]=ga(bounds,'fitness') 注:前两个文件存储为 m 文件并放在工作目录下,运行结果为 p = 0.0000 -0.0000 0.0055
大家可以直接绘出 f(x)的图形来大概看看 f(x)的最值是多少, 也可是使用优化函数来验证。matlab 命令行执行命令: fplot('x 10*sin(5*x) 7*cos(4*x)',[0,9]) evalops 是传递给适应度函数的参数,opts 是二进制编码的精度, termops 是选择 maxGenTerm 结束函数时传递个 maxGenTerm 的参数,即遗传代数。xoverops 是传递给交叉函数的参数。 mutops 是传递给变异函数的参数。 【问题】求 f(x)=x+10*sin(5x)+7*cos(4x)的最大值,其中 0<=x<=9 【分析】选择二进制编码,种群中的个体数目为 10,二进制编码 长度为 20,交叉概率为 0.95,变异概率为 0.08 【程序清单】 %编写目标函数 function[sol,eval]=fitness(sol,options) x=sol(1); eval=x+10*sin(5*x)+7*cos(4*x); %把上述函数存储为 fitness.m 文件并放在工作目录下 initPop=initializega(10,[0 9],'fitness');%生成初始种群,大小 为 10 [x endPop,bPop,trace]=ga([0 9],'fitness',[],initPop,[1e-6 1 1],'maxGenTerm',25,'normGeomSelect',... [0.08],['arithXover'],[2],'nonUnifMutation',[2 25 3]) %25 次 遗传迭代 运算借过为:x = 7.8562 24.8553(当 x 为 7.8562 时,f(x)取最大值 24.8553) 注:遗传算法一般用来取得近似最优解,而不是最优解。 遗传算法实例 2 【问题】在-5<=Xi<=5,i=1,2 区间内,求解 f(x1,x2)=-20*exp(-0.2*sqrt(0.5*(x1.^2+x2.^2)))-exp(0.5*(cos(2* pi*x1)+cos(2*pi*x2)))+22.71282 的最小值。 【分析】种群大小 10,最大代数 1000,变异率 0.1,交叉率 0.3 【程序清单】 %源函数的 matlab 代码 function [eval]=f(sol) numv=size(sol,2); x=sol(1:numv); eval=-20*exp(-0.2*sqrt(sum(x.^2)/numv)))-exp(sum(cos(2*pi*x)) /numv)+22.71282; %适应度函数的 matlab 代码 function [sol,eval]=fitness(sol,options) numv=size(sol,2)-1; x=sol(1:numv); eval=f(x); eval=-eval; %遗传算法的 matlab 代码 bounds=ones(2,1)*[-5 5]; [p,endPop,bestSols,trace]=ga(bounds,'fitness') 注:前两个文件存储为 m 文件并放在工作目录下,运行结果为 p = 0.0000 -0.0000 0.0055 大家可以直接绘出 f(x)的图形来大概看看 f(x)的最值是多少, 也可是使用优化函数来验证。matlab 命令行执行命令: fplot('x+10*sin(5*x)+7*cos(4*x)',[0,9]) evalops 是传递给适应度函数的参数,opts 是二进制编码的精度, termops 是选择 maxGenTerm 结束函数时传递个 maxGenTerm 的参数,即遗传代数。xoverops 是传递给交叉函数的参数。 mutops 是传递给变异函数的参数。 参考资料:不记得了,抱歉 function Main() %定义全局变量 global VariableNum POPSIZE MaxGens PXOVER PMutation VariableNum=3 %变量个数 POPSIZE=50 %种群大小 MaxGens=1000 %种群代数 PXOVER=0.8 %交叉概率 PMutation=0.2 %变异概率 %读取数据文件 load E:\现代优化算法\遗传算法\bound.txt VarBound=bound(:,1:2); global Pop newPop Pop=zeros(POPSIZE+1,VariableNum); newPop=zeros(POPSIZE+1,VariableNum); %初始化种群 for i=1:POPSIZE for j=1:VariableNum Pop(i,j)=VarBound(j,1)+rand()*(VarBound(j,2)-VarBound(j, 1)); end end %计算适应值 fitnessList=zeros(POPSIZE,1); for i=1:POPSIZE fitnessList(i,1)=fitness(Pop(i,1:VariableNum)); end %保存最好值和最坏值 Best=zeros(1,VariableNum+1); Worst=zeros(1,VariableNum+1); maxvalue=max(fitnessList); indexMax=find(fitnessList==maxvalue,1,'first');
Best(1,1:VariableNum)=Pop(indexMax,1:VariableNum); Best(1,VariableNum+1)=maxvalue; minvalue=min(fitnessList); indexMin=find(fitnessList==minvalue,1,'first'); Worst(1,1:VariableNum)=Pop(indexMin,1:VariableNum); Worst(1,VariableNum+1)=minvalue; genetation=1; while genetation1 if VariableNUM==2 point=1; else point=round(rand()*(VariableNUM-2)+1); end tempOne=zeros(1,point); tempOne(1,1:point)=Pop(first_index,1:point); Pop(first_index,1:point)=Pop(second_index,1:point); Pop(second_index,1:point)=tempOne(1,1:point); end end end newPop=zeros(size(Pop),1); newPop=Pop;
=============================================== ===== 其可能的路径数目 与城市数目 n 是成指数型增长的,所以一般很难精确地求出其最 优解,本文采用遗传算法 %变异操作 求其近似解。 function newPop=Mutation(Pop,VariableNUM,MutationRate,bound) point=1; sizePop=length(Pop); for i=1:sizePop for j=1:VariableNUM Mrate=rand(); if Mrate
按均匀变异(该变异点 xk 的取值范围为[ukmin,ukmax],产生 一个[0,1]中随机数 r,该点 变异为 x'k=ukmin+r(ukmax-ukmin))操作。如: 8 14 2 13 8 6 3 2 5 7 3 4 3 2 4 2 2 1 变异后: 8 14 2 13 10 6 3 2 2 7 3 4 5 2 4 1 2 1 反 grefenstette 编码:交叉和变异都是在 grefenstette 编码之后进行的,为了循环操作 和返回最终结果,必须逆 grefenstette 编码过程,将编码恢 复到自然编码。 循环操作:判断是否满足设定的带数 xzome,否,则跳入适应度 f 的计算;是,结束遗传 操作,跳出。 matlab 代码 distTSP.txt 0 6 18 4 8 7 0 17 3 7 4 4 0 4 5 20 19 24 0 22 8 8 16 6 0 %GATSP.m function gatsp1() clear; load distTSP.txt; distance=distTSP; N=5; ngen=100; ngpool=10; %ngen=input('# of generations to evolve = '); %ngpool=input('# of chromosoms in the gene pool = '); % size of genepool gpool=zeros(ngpool,N+1); % gene pool for i=1:ngpool, % intialize gene pool gpool(i,:)=[1 randomize([2:N]')' 1]; for j=1:i-1 while gpool(i,:)==gpool(j,:) gpool(i,:)=[1 randomize([2:N]')' 1]; end end end costmin=100000; tourmin=zeros(1,N); cost=zeros(1,ngpool); increase=1;resultincrease=1; for i=1:ngpool, cost(i)=sum(diag(distance(gpool(i,:)',rshift(g pool(i,:))'))); end % record current best solution [costmin,idx]=min(cost); tourmin=gpool(idx,:); disp([num2str(increase) 'minmum trip length = ' num2str(costmin)]) costminold2=200000;costminold1=150000;resultco st=100000; tourminold2=zeros(1,N); tourminold1=zeros(1,N); resulttour=zeros(1,N); while (abs(costminold2-costminold1) ;100)&(abs(costmi nold1-costmin) ;100)&(increase ;500) costminold2=costminold1; tourminold2=tourminold1; costminold1=costmin;tourminold1=tourmin; increase=increase+1; if resultcost>costmin resultcost=costmin; resulttour=tourmin; resultincrease=increase-1; end for i=1:ngpool, cost(i)=sum(diag(distance(gpool(i,:)',rshift(g pool(i,:))'))); end % record current best solution [costmin,idx]=min(cost); tourmin=gpool(idx,:); %============== % copy gens in th gpool according to the probility ratio % >1.1 copy twice % >=0.9 copy once % ;0.9 remove [csort,ridx]=sort(cost); % sort from small to big. csum=sum(csort); caverage=csum/ngpool; cprobilities=caverage./csort; copynumbers=0;removenumbers=0; for i=1:ngpool, if cprobilities(i) >1.1 copynumbers=copynumbers+1; end
分享到:
收藏