Login
升级VIP 登录 注册 安全退出
当前位置: 首页 > word文档 > 其他文档 > 遗传算法matlab代码,遗传算法matlab代码详解

遗传算法matlab代码,遗传算法matlab代码详解

收藏

本作品内容为遗传算法matlab代码,格式为 doc ,大小 88064 KB ,页数为 12页

遗传算法matlab代码


("标准实用functionyouhuafunD=code;N=50;%Tunablemaxgen=50;%Tunablecrossrate=0.5;%Tunablemuterate=0.08;%Tunablegeneration=1;num=length(D);fatherrand=randint(num,N,3);score=zeros(maxgen,N);whilegeneration<=maxgenind=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=rndtmp=A(ind);A(ind)=B(ind);B(ind)=tmp;%%两点交叉%forkk=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;%endfatherrand=[fatherrand(:,1:2),A,B];%变异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;%评价、选择scoreN=scorefun(fatherrand,D);%求得N个个体的评价函数score(generation,:)=scoreN;[scoreSort,scoreind]=sort(scoreN);sumscore=cumsum(scoreSort);sumscore=sumscore./sumscore(end);childind(1:2)=scoreind(end-1:end);fork=3:Ntmprnd=rand;tmpind=tmprnddifind=[0,diff(tmpind)];if~any(difind)difind(1)=1;endchildind(k)=scoreind(logical(difind));endfatherrand=fatherrand(:,childind);generation=generation+1;end%scoremaxV=max(score,[],2);minV=11300-maxV;plot(minV,'');title('各代的目标函数值');F4=D(:,4);FF4=F4-fatherrand(:,1);FF4=max(FF4,1);D(:,5)=FF4;saveDDataDfunctionD=codeloadyouhua.mat%propertiesF2andF3F1=A(:,1);F2=A(:,2);F3=A(:,3);if(max(F2)>1450)(min(F2)<=900)error('DATApropertyF2exceedit''srange(900,1450]')end%getgrouppropertyF1ofdata,accordingtoF2valueF4=zeros(size(F1));forite=11:-1:1index=find(F2<=900+ite50);F4(index)=ite;endD=[F1,F2,F3,F4];functionScoreN=scorefun(fatherrand,D)F3=D(:,3);F4=D(:,4);N=size(fatherrand,2);FF4=F4ones(1,N);FF4rnd=FF4-fatherrand;FF4rnd=max(FF4rnd,1);文案大全标准实用ScoreN=ones(1,N)30011;%这里有待优化fork=1:NFF4k=FF4rnd(:,k);forite=1:11F0index=find(FF4k==ite);if~isempty(F0index)tmpMat=F3(F0index);tmpSco=sum(tmpMat);ScoreBin(ite)=mod(tmpSco,300);endendScorek(k)=sum(ScoreBin);endScoreN=ScoreN-Scorek;遗传算法实例:%下面举例说明遗传算法%%求下列函数的最大值%%f(x)=10sin(5x)+7cos(4x)x∈[0,10]%%将x的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为(10-0)/(2^10-1)≈0.01。%%将变量域[0,10]离散化为二值域[0,1023],x=0+10b/1023,其中b是[0,1023]中的一个二值数。%%%%--------------------------------------------------------------------------------------------------------------%%--------------------------------------------------------------------------------------------------------------%%编程%-----------------------------------------------%2.1初始化(编码)%initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),%长度大小取决于变量的二进制编码的长度(在本例中取10位)。%遗传算法子程序%Name:initpop.m%初始化functionpop=initpop(popsize,chromlength)pop=round(rand(popsize,chromlength));%rand随机产生每个单元为{0,1}行数为popsize,列数为chromlength的矩阵,%roud对矩阵的每个单元进行圆整。这样产生的初始种群。%2.2计算目标函数值%2.2.1将二进制数转化为十进制数(1)%遗传算法子程序%Name:decodebinary.m%产生[2^n2^(n-1)...1]的行向量,然后求和,将二进制转化为十进制functionpop2=decodebinary(pop)[px,py]=size(pop);%求pop行和列数fori=1:pypop1(:,i)=2.^(py-i).pop(:,i);endpop2=sum(pop1,2);%求pop1的每行之和%2.2.2将二进制编码转化为十进制数(2)%decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置%(对于多个变量而言,如有两个变量,采用20为表示,每个变量为10,则第一个变量从1开始,另一个变量从11开始。本例为1),%参数1ength表示所截取的长度(本例为10)。%遗传算法子程序%Name:decodechrom.m%将二进制编码转换成十进制functionpop2=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=temp110/1023;%将二值域中的数转化为变量域的数objvalue=10sin(5x)+7cos(4x);%计算目标函数值%2.3计算个体的适应值%遗传算法子程序%Name:calfitvalue.m%计算个体的适应值functionfitvalue=calfitvalue(objvalue)globalCmin;文案大全标准实用Cmin=0;[px,py]=size(objvalue);fori=1:pxifobjvalue(i)+Cmin>0temp=Cmin+objvalue(i);elsetemp=0.0;endfitvalue(i)=temp;endfitvalue=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=[1234],则cumsum(fitvalue)=[13610][px,py]=size(pop);ms=sort(rand(px,1));%从小到大排列fitin=1;newin=1;whilenewin<=pxif(ms(newin))bestfitbestindividual=pop(i,:);bestfit=fitvalue(i);endend%2.8主程序%遗传算法主程序%Name:genmain05.mclearclfpopsize=20;%群体大小chromlength=10;%字符串长度(个体长度)pc=0.6;%交叉概率pm=0.001;%变异概率pop=initpop(popsize,chromlength);%随机产生初始群体fori=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;endfplot('10sin(5x)+7cos(4x)',[010])holdonplot(x,y,'r')holdoff[zindex]=max(y);%计算最大值及其位置x5=x(index)%计算最大值对应的x值y=z【问题】求f(x)=x10sin(5x)7cos(4x)的最大值,其中0<=x<=9【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08【程序清单】%编写目标函数function[sol,eval]=fitness(sol,options)x=sol(1);eval=x10sin(5x)7cos(4x);%把上述函数存储为fitness.m文件并放在工作目录下initPop=initializega(10,[09],'fitness');%生成初始种群,大小为10[xendPop,bPop,trace]=ga([09],'fitness',[],initPop,[1e-611],'maxGenTerm',25,'normGeomSelect',...[0.08],['arithXover'],[2],'nonUnifMutation',[2253])%25次遗传迭代运算借过为:x=7.856224.8553(当x为7.8562时,f(x)取最大值24.8553)注:遗传算法一般用来取得近似最优解,而不是最优解。遗传算法实例2【问题】在-5<=Xi<=5,i=1,2区间内,求解f(x1,x2)=-20exp(-0.2sqrt(0.5(x1.^2x2.^2)))-exp(0.5(cos(2pix1)cos(2pix2)))22.71282的最小值。【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3【程序清单】%源函数的matlab代码function[eval]=f(sol)文案大全标准实用numv=size(sol,2);x=sol(1:numv);eval=-20exp(-0.2sqrt(sum(x.^2)/numv)))-exp(sum(cos(2pix))/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)[-55];[p,endPop,bestSols,trace]=ga(bounds,'fitness')注:前两个文件存储为m文件并放在工作目录下,运行结果为p=0.0000-0.00000.0055大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:fplot('x10sin(5x)7cos(4x)',[0,9])evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。【问题】求f(x)=x+10sin(5x)+7cos(4x)的最大值,其中0<=x<=9【分析】选择二进制编码,种群中的个体数目为10,二进制编码长度为20,交叉概率为0.95,变异概率为0.08【程序清单】%编写目标函数function[sol,eval]=fitness(sol,options)x=sol(1);eval=x+10sin(5x)+7cos(4x);%把上述函数存储为fitness.m文件并放在工作目录下initPop=initializega(10,[09],'fitness');%生成初始种群,大小为10[xendPop,bPop,trace]=ga([09],'fitness',[],initPop,[1e-611],'maxGenTerm',25,'normGeomSelect',...[0.08],['arithXover'],[2],'nonUnifMutation',[2253])%25次遗传迭代运算借过为:x=7.856224.8553(当x为7.8562时,f(x)取最大值24.8553)注:遗传算法一般用来取得近似最优解,而不是最优解。遗传算法实例2【问题】在-5<=Xi<=5,i=1,2区间内,求解f(x1,x2)=-20exp(-0.2sqrt(0.5(x1.^2+x2.^2)))-exp(0.5(cos(2pix1)+cos(2pix2)))+22.71282的最小值。【分析】种群大小10,最大代数1000,变异率0.1,交叉率0.3【程序清单】%源函数的matlab代码function[eval]=f(sol)numv=size(sol,2);x=sol(1:numv);eval=-20exp(-0.2sqrt(sum(x.^2)/numv)))-exp(sum(cos(2pix))/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)[-55];[p,endPop,bestSols,trace]=ga(bounds,'fitness')注:前两个文件存储为m文件并放在工作目录下,运行结果为p=0.0000-0.00000.0055大家可以直接绘出f(x)的图形来大概看看f(x)的最值是多少,也可是使用优化函数来验证。matlab命令行执行命令:fplot('x+10sin(5x)+7cos(4x)',[0,9])evalops是传递给适应度函数的参数,opts是二进制编码的精度,termops是选择maxGenTerm结束函数时传递个maxGenTerm的参数,即遗传代数。xoverops是传递给交叉函数的参数。mutops是传递给变异函数的参数。参考资料:不记得了,抱歉functionMain()%定义全局变量globalVariableNumPOPSIZEMaxGensPXOVERPMutationVariableNum=3%变量个数POPSIZE=50%种群大小MaxGens=1000%种群代数PXOVER=0.8%交叉概率PMutation=0.2%变异概率%读取数据文件loadE:\\现代优化算法\\遗传算法\\bound.txtVarBound=bound(:,1:2);文案大全标准实用globalPopnewPopPop=zeros(POPSIZE+1,VariableNum);newPop=zeros(POPSIZE+1,VariableNum);%初始化种群fori=1:POPSIZEforj=1:VariableNumPop(i,j)=VarBound(j,1)+rand()(VarBound(j,2)-VarBound(j,1));endend%计算适应值fitnessList=zeros(POPSIZE,1);fori=1:POPSIZEfitnessList(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;whilegenetation1ifVariableNUM==2point=1;elsepoint=round(rand()(VariableNUM-2)+1);endtempOne=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);endendendnewPop=zeros(size(Pop),1);newPop=Pop;====================================================%变异操作functionnewPop=Mutation(Pop,VariableNUM,MutationRate,bound)point=1;sizePop=length(Pop);fori=1:sizePopforj=1:VariableNUMMrate=rand();ifMratecostminresultcost=costmin;resulttour=tourmin;resultincrease=increase-1;endfori=1:ngpool,cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));end%recordcurrentbestsolution[costmin,idx]=min(cost);tourmin=gpool(idx,:);%==============%copygensinthgpoolaccordingtotheprobilityratio%>1.1copytwice%>=0.9copyonce%;0.9remove[csort,ridx]=sort(cost);%sortfromsmalltobig.csum=sum(csort);caverage=csum/ngpool;cprobilities=caverage./csort;copynumbers=0;removenumbers=0;fori=1:ngpool,ifcprobilities(i)>1.1copynumbers=copynumbers+1;endifcprobilities(i)<0.9removenumbers=removenumbers+1;endendcopygpool=min(copynumbers,removenumbers);fori=1:copygpoolforj=ngpool:-1:2i+2gpool(j,:)=gpool(j-1,:);endgpool(2i+1,:)=gpool(i,:);endifcopygpool==0gpool(ngpool,:)=gpool(1,:);end%=========%whengenarationismorethan50,orthepatternsinacouplearetooclose,domutationfori=1:ngpool/2%sameidx=[gpool(2i-1,:)==gpool(2i,:)];diffidx=find(sameidx==0);iflength(diffidx)<=2gpool(2i,:)=[1randomize([2:12]')'1];endend%===========%crossgensincouplesfori=1:ngpool/2[gpool(2i-1,:),gpool(2i,:)]=crossgens(gpool(2i-1,:),gpool(2i,:));endfori=1:ngpool,cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));end%recordcurrentbestsolution[costmin,idx]=min(cost);tourmin=gpool(idx,:);disp([num2str(increase)'minmumtriplength='num2str(costmin)])enddisp(['costfunctionevaluation:'int2str(increase)'times!'])disp(['n:'int2str(resultincrease)])disp(['minmumtriplength='num2str(resultcost)])disp('optimumtour=')disp(num2str(resulttour))%====================================================functionB=randomize(A,rowcol)%Usage:B=randomize(A,rowcol)%randomizerowordersorcolumnordersofAmatrix%rowcol:if=0oromitted,roworder(default)%if=1,columnorder文案大全标准实用rand('state',sum(100clock))ifnargin==1,rowcol=0;endifrowcol==0,[m,n]=size(A);p=rand(m,1);[p1,I]=sort(p);B=A(I,:);elseifrowcol==1,Ap=A';[m,n]=size(Ap);p=rand(m,1);[p1,I]=sort(p);B=Ap(I,:)';end%=====================================================functiony=rshift(x,dir)%Usage:y=rshift(x,dir)%rotatexvectortoright(down)by1ifdir=0(default)%orrotatextoleft(up)by1ifdir=1ifnargin;2,dir=0;end[m,n]=size(x);ifm>1,ifn==1,col=1;elseifn>1,error('xmustbeavector!break');end%xisacolumnvectorelseifm==1,ifn==1,y=x;returnelseifn>1,col=0;%xisarowvectorendendifdir==1,%rotateleftorupifcol==0,%rowvector,rotatelefty=[x(2:n)x(1)];elseifcol==1,y=[x(2:n);x(1)];%rotateupendelseifdir==0,%defaultrotaterightordownifcol==0,y=[x(n)x(1:n-1)];elseifcol==1%columnvectory=[x(n);x(1:n-1)];endend%==================================================function[L1,L2]=crossgens(X1,X2)%Usage:[L1,L2]=crossgens(X1,X2)s=randomize([2:12]')';n1=min(s(1),s(11));n2=max(s(1),s(11));X3=X1;X4=X2;fori=n1:n2,forj=1:13,ifX2(i)==X3(j),X3(j)=0;endifX1(i)==X4(j),X4(j)=0;endendendj=13;k=13;fori=12:-1:2,ifX3(i)~=0,j=j-1;t=X3(j);X3(j)=X3(i);X3(i)=t;endifX4(i)~=0,k=k-1;t=X4(k);X4(k)=X4(i);X4(i)=t;endendfori=n1:n2X3(2+i-n1)=X2(i);X4(2+i-n1)=X1(i);endL1=X3;L2=X4;%=======================由于BP网络的权值优化是一个无约束优化问题,而且权值要采用实数编码,所以直接利用Matlab遗传算法工具箱。以下贴出的代码是为一个19输入变量,1个输出变量情况下的非线性回归而设计的,如果要应用于其它情况,只需改动编解码函数即可。程序一:GA训练BP权值的主函数functionnet=GABPNET(XX,YY)%--------------------------------------------------------------------------%GABPNET.m%使用遗传算法对BP网络权值阈值进行优化,再用BP算法训文案大全标准实用练网络%--------------------------------------------------------------------------%数据归一化预处理nntwarnoffXX=premnmx(XX);YY=premnmx(YY);%创建网络net=newff(minmax(XX),[19,25,1],{'tansig','tansig','purelin'},'trainlm');%下面使用遗传算法对网络进行优化P=XX;T=YY;R=size(P,1);S2=size(T,1);S1=25;%隐含层节点数S=RS1+S1S2+S1+S2;%遗传算法编码长度aa=ones(S,1)[-1,1];popu=50;%种群规模initPpp=initializega(popu,aa,'gabpEval');%初始化种群gen=100;%遗传代数%下面调用gaot工具箱,其中目标函数定义为gabpEval[x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-611],'maxGenTerm',gen,...'normGeomSelect',[0.09],['arithXover'],[2],'nonUnifMutation',[2gen3]);%绘收敛曲线图figure(1)plot(trace(:,1),1./trace(:,3),'r-');holdonplot(trace(:,1),1./trace(:,2),'b-');xlabel('Generation');ylabel('Sum-SquaredError');figure(2)plot(trace(:,1),trace(:,3),'r-');holdonplot(trace(:,1),trace(:,2),'b-');xlabel('Generation');ylabel('Fittness');%下面将初步得到的权值矩阵赋给尚未开始训练的BP网络[W1,B1,W2,B2,P,T,A1,A2,SE,val]=gadecod(x);net.LW{2,1}=W1;net.LW{3,2}=W2;net.b{2,1}=B1;net.b{3,1}=B2;XX=P;YY=T;%设置训练参数net.trainParam.show=1;net.trainParam.lr=1;net.trainParam.epochs=50;net.trainParam.goal=0.001;%训练网络net=train(net,XX,YY);程序二:适应值函数function[sol,val]=gabpEval(sol,options)%val-thefittnessofthisindividual%sol-theindividual,returnedtoallowforLamarckianevolution%options-[current_generation]loaddata2nntwarnoffXX=premnmx(XX);YY=premnmx(YY);P=XX;T=YY;R=size(P,1);S2=size(T,1);S1=25;%隐含层节点数S=RS1+S1S2+S1+S2;%遗传算法编码长度fori=1:S,x(i)=sol(i);end;[W1,B1,W2,B2,P,T,A1,A2,SE,val]=gadecod(x);程序三:编解码函数function[W1,B1,W2,B2,P,T,A1,A2,SE,val]=gadecod(x)loaddata2nntwarnoffXX=premnmx(XX);YY=premnmx(YY);P=XX;T=YY;R=size(P,1);S2=size(T,1);S1=25;%隐含层节点数S=RS1+S1S2+S1+S2;%遗传算法编码长度%前RS1个编码为W1fori=1:S1,fork=1:R,W1(i,k)=x(R(i-1)+k);end文案大全标准实用end%接着的S1S2个编码(即第RS1个后的编码)为W2fori=1:S2,fork=1:S1,W2(i,k)=x(S1(i-1)+k+RS1);endend%接着的S1个编码(即第RS1+S1S2个后的编码)为B1fori=1:S1,B1(i,1)=x((RS1+S1S2)+i);end%接着的S2个编码(即第RS1+S1S2+S1个后的编码)为B2fori=1:S2,B2(i,1)=x((RS1+S1S2+S1)+i);end%计算S1与S2层的输出A1=tansig(W1P,B1);A2=purelin(W2A1,B2);%计算误差平方和SE=sumsqr(T-A2);val=1/SE;%遗传算法的适应值文案大全",)


  • 编号:1700761173
  • 分类:其他文档
  • 软件: wps,office word
  • 大小:12页
  • 格式:docx
  • 风格:商务
  • PPT页数:88064 KB
  • 标签:

广告位推荐

相关其他文档更多>