遗传算法程序
遗传算法的原理及MATLAB程序实现.
1 遗传算法的原理1.1 遗传算法的基本思想遗传算法(genetic algorithms,GA)是一种基于自然选择和基因遗传学原理,借鉴了生物进化优胜劣汰的自然选择机理和生物界繁衍进化的基因重组、突变的遗传机制的全局自适应概率搜索算法。
遗传算法是从一组随机产生的初始解(种群)开始,这个种群由经过基因编码的一定数量的个体组成,每个个体实际上是染色体带有特征的实体。
染色体作为遗传物质的主要载体,其内部表现(即基因型)是某种基因组合,它决定了个体的外部表现。
因此,从一开始就需要实现从表现型到基因型的映射,即编码工作。
初始种群产生后,按照优胜劣汰的原理,逐代演化产生出越来越好的近似解。
在每一代,根据问题域中个体的适应度大小选择个体,并借助于自然遗传学的遗传算子进行组合交叉和变异,产生出代表新的解集的种群。
这个过程将导致种群像自然进化一样,后代种群比前代更加适应环境,末代种群中的最优个体经过解码,可以作为问题近似最优解。
计算开始时,将实际问题的变量进行编码形成染色体,随机产生一定数目的个体,即种群,并计算每个个体的适应度值,然后通过终止条件判断该初始解是否是最优解,若是则停止计算输出结果,若不是则通过遗传算子操作产生新的一代种群,回到计算群体中每个个体的适应度值的部分,然后转到终止条件判断。
这一过程循环执行,直到满足优化准则,最终产生问题的最优解。
图1-1给出了遗传算法的基本过程。
1.2 遗传算法的特点1.2.1 遗传算法的优点遗传算法具有十分强的鲁棒性,比起传统优化方法,遗传算法有如下优点:1. 遗传算法以控制变量的编码作为运算对象。
传统的优化算法往往直接利用控制变量的实际值的本身来进行优化运算,但遗传算法不是直接以控制变量的值,而是以控制变量的特定形式的编码为运算对象。
这种对控制变量的编码处理方式,可以模仿自然界中生物的遗传和进化等机理,也使得我们可以方便地处理各种变量和应用遗传操作算子。
2. 遗传算法具有内在的本质并行性。
用MATLAB实现遗传算法程序
用MATLAB实现遗传算法程序一、本文概述遗传算法(Genetic Algorithms,GA)是一种模拟自然界生物进化过程的优化搜索算法,它通过模拟自然选择和遗传学机制,如选择、交叉、变异等,来寻找问题的最优解。
由于其全局搜索能力强、鲁棒性好以及易于实现并行化等优点,遗传算法在多个领域得到了广泛的应用,包括函数优化、机器学习、神经网络训练、组合优化等。
本文旨在介绍如何使用MATLAB实现遗传算法程序。
MATLAB作为一种强大的数学计算和编程工具,具有直观易用的图形界面和丰富的函数库,非常适合用于遗传算法的实现。
我们将从基本的遗传算法原理出发,逐步介绍如何在MATLAB中编写遗传算法程序,包括如何定义问题、编码、初始化种群、选择操作、交叉操作和变异操作等。
通过本文的学习,读者将能够掌握遗传算法的基本原理和MATLAB编程技巧,学会如何使用MATLAB实现遗传算法程序,并能够在实际问题中应用遗传算法求解最优解。
二、遗传算法基础遗传算法(Genetic Algorithm,GA)是一种模拟自然选择和遗传学机制的优化搜索算法。
它借鉴了生物进化中的遗传、交叉、变异等机制,通过模拟这些自然过程来寻找问题的最优解。
遗传算法的核心思想是将问题的解表示为“染色体”,即一组编码,然后通过模拟自然选择、交叉和变异等过程,逐步迭代搜索出最优解。
在遗传算法中,通常将问题的解表示为一个二进制字符串,每个字符串代表一个个体(Individual)。
每个个体都有一定的适应度(Fitness),适应度越高的个体在下一代中生存下来的概率越大。
通过选择(Selection)、交叉(Crossover)和变异(Mutation)等操作,生成新一代的个体,并重复这一过程,直到找到满足条件的最优解或达到预定的迭代次数。
选择操作是根据个体的适应度,选择出适应度较高的个体作为父母,参与下一代的生成。
常见的选择算法有轮盘赌选择(Roulette Wheel Selection)、锦标赛选择(Tournament Selection)等。
遗传算法的MATLAB程序实例讲解学习
遗传算法的M A T L A B程序实例遗传算法的程序实例如求下列函数的最大值f(x)=10*sin(5x)+7*cos(4x) x∈[0,10]一、初始化(编码)initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),长度大小取决于变量的二进制编码的长度(在本例中取10位)。
代码:%Name: initpop.m%初始化function pop=initpop(popsize,chromlength)pop=round(rand(popsize,chromlength));% rand随机产生每个单元为 {0,1} 行数为popsize,列数为chromlength的矩阵,% roud对矩阵的每个单元进行圆整。
这样产生的初始种群。
二、计算目标函数值1、将二进制数转化为十进制数(1)代码:%Name: decodebinary.m%产生 [2^n 2^(n-1) ... 1] 的行向量,然后求和,将二进制转化为十进制function pop2=decodebinary(pop)[px,py]=size(pop); %求pop行和例数for i=1:pypop1(:,i)=2.^(py-1).*pop(:,i);py=py-1;endpop2=sum(pop1,2); %求pop1的每行之和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);3、计算目标函数值calobjvalue.m函数的功能是实现目标函数的计算,其公式采用本文示例仿真,可根据不同优化问题予以修改。
标准遗传算法程序说明
标准遗传算法程序说明一、 工作环境该程序是在vs2008环境下,使用c++语言编写的。
二、 程序结构程序中由两个类类型:一个是individual 类型,即种群中的个体,另一个是population 类型,即一个群体。
其中individual 类型包含以下数据成员:chrom 是个体的染色体,采用二进制编码;fitness 是个体在种群中归一化的适应度;varible 是chrom 解码后对应的值;y_varible 是个体的适应度。
Individual 类型的主要成员函数如下:init_individual(bitset<size_bit> c,double y,double v)是对个体的chrom 、varible 和y_varible 进行赋值;其他的函数如read_vari()、read_y_vari()、chang_fitness(double f)、chang_varible(double v)、chang_yvarible(double y)、chang_bitset(bitset<size_bit> c) 以及read_bitset()主要是由于数据成员被定义为私有的,在外面不能直接读取和修改,所以需要通过这些函数进行读取和修改。
而population 类型包括以下数据成员:individuals 是种群中的全部个体; size_population 是种群大小,即是个体数量;max_generation 是进化过程进行的最大代数;best 是当前为止最有解;best_individual 是当前最优个体;size_choose 是每次选择交叉的父代个体数;low_bound 是所求问题变量下界;top_boud 是所求问题变量上界;cross 是进行交叉的概率;mutation 是发生变异的概率;choosed 被选择进行交叉的个体。
Population 类型的成员函数如下:population(unsigned int m,unsigned int n,unsigned int ch,double l,double t,double cr,double mu)是该类型的构造函数,第一个参数m 是种群大小,n 是最大进化代数,ch 是每次选择进行交叉的个体数量,l 是所求问题变量下界,t 是所求问题变量上界,cr 进行交叉的概率,mu 发生变异的概率。
遗传算法简单程序
该程序是遗传算法优化BP神经网络函数极值寻优:%% 该代码为基于神经网络遗传算法的系统极值寻优%% 清空环境变量clcclear%% 初始化遗传算法参数%初始化参数maxgen=100; %进化代数,即迭代次数sizepop=20; %种群规模pcross=[0.4]; %交叉概率选择,0和1之间pmutation=[0.2]; %变异概率选择,0和1之间lenchrom=[1 1]; %每个变量的字串长度,如果是浮点变量,则长度都为1 bound=[-5 5;-5 5]; %数据范围individuals=struct('fitness',zeros(1,sizepop), 'chrom',[]); %将种群信息定义为一个结构体avgfitness=[]; %每一代种群的平均适应度bestfitness=[]; %每一代种群的最佳适应度bestchrom=[]; %适应度最好的染色体%% 初始化种群计算适应度值% 初始化种群for i=1:sizepop%随机产生一个种群individuals.chrom(i,:)=Code(lenchrom,bound);x=individuals.chrom(i,:);%计算适应度individuals.fitness(i)=fun(x); %染色体的适应度end%找最好的染色体[bestfitness bestindex]=min(individuals.fitness);bestchrom=individuals.chrom(bestindex,:); %最好的染色体avgfitness=sum(individuals.fitness)/sizepop; %染色体的平均适应度% 记录每一代进化中最好的适应度和平均适应度trace=[avgfitness bestfitness];%% 迭代寻优% 进化开始for i=1:maxgeni% 选择individuals=Select(individuals,sizepop);avgfitness=sum(individuals.fitness)/sizepop;%交叉individuals.chrom=Cross(pcross,lenchrom,individuals.chrom,sizepop,bound);% 变异individuals.chrom=Mutation(pmutation,lenchrom,individuals.chrom,sizepop,[i maxgen],bound);% 计算适应度for j=1:sizepopx=individuals.chrom(j,:); %解码individuals.fitness(j)=fun(x);end%找到最小和最大适应度的染色体及它们在种群中的位置[newbestfitness,newbestindex]=min(individuals.fitness);[worestfitness,worestindex]=max(individuals.fitness);% 代替上一次进化中最好的染色体if bestfitness>newbestfitnessbestfitness=newbestfitness;bestchrom=individuals.chrom(newbestindex,:);endindividuals.chrom(worestindex,:)=bestchrom;individuals.fitness(worestindex)=bestfitness;avgfitness=sum(individuals.fitness)/sizepop;trace=[trace;avgfitness bestfitness]; %记录每一代进化中最好的适应度和平均适应度end%进化结束%% 结果分析[r c]=size(trace);plot([1:r]',trace(:,2),'r-');title('适应度曲线','fontsize',12);xlabel('进化代数','fontsize',12);ylabel('适应度','fontsize',12);axis([0,100,0,1])disp('适应度变量');x=bestchrom;% 窗口显示disp([bestfitness x]);。
2020年遗传算法matlab程序实例精编版
%-----------------------------------------------%---------------------------------------------------遗传算法程序(一):说明: fga.m 为遗传算法的主程序; 采用二进制Gray编码,采用基于轮盘赌法的非线性排名选择, 均匀交叉,变异操作,而且还引入了倒位操作!function [BestPop,Trace]=fga(FUN,LB,UB,eranum,popsize,pCross,pMutation,pInversion,options) % [BestPop,Trace]=fmaxga(FUN,LB,UB,eranum,popsize,pcross,pmutation)% Finds a maximum of a function of several variables.% fmaxga solves problems of the form:% max F(X) subject to: LB <= X <= UB% BestPop - 最优的群体即为最优的染色体群% Trace - 最佳染色体所对应的目标函数值% FUN - 目标函数% LB - 自变量下限% UB - 自变量上限% eranum - 种群的代数,取100--1000(默认200)% popsize - 每一代种群的规模;此可取50--200(默认100)% pcross - 交叉概率,一般取0.5--0.85之间较好(默认0.8)% pmutation - 初始变异概率,一般取0.05-0.2之间较好(默认0.1)% pInversion - 倒位概率,一般取0.05-0.3之间较好(默认0.2)% options - 1*2矩阵,options(1)=0二进制编码(默认0),option(1)~=0十进制编%码,option(2)设定求解精度(默认1e-4)%% ------------------------------------------------------------------------T1=clock;if nargin<3, error('FMAXGA requires at least three input arguments'); endif nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==7, pInversion=0.15;options=[0 1e-4];endif find((LB-UB)>0)error('数据输入错误,请重新输入(LB<UB):');ends=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));disp(s);global m n NewPop children1 children2 VarNumbounds=[LB;UB]';bits=[];VarNum=size(bounds,1);precision=options(2);%由求解精度确定二进制编码长度bits=ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间[Pop]=InitPopGray(popsize,bits);%初始化种群[m,n]=size(Pop);NewPop=zeros(m,n);children1=zeros(1,n);children2=zeros(1,n);pm0=pMutation;BestPop=zeros(eranum,n);%分配初始解空间BestPop,TraceTrace=zeros(eranum,length(bits)+1);i=1;while i<=eranumfor j=1:mvalue(j)=feval(FUN(1,:),(b2f(Pop(j,:),bounds,bits)));%计算适应度end[MaxValue,Index]=max(value);BestPop(i,:)=Pop(Index,:);Trace(i,1)=MaxValue;Trace(i,(2:length(bits)+1))=b2f(BestPop(i,:),bounds,bits);[selectpop]=NonlinearRankSelect(FUN,Pop,bounds,bits);%非线性排名选择[CrossOverPop]=CrossOver(selectpop,pCross,round(unidrnd(eranum-i)/eranum));%采用多点交叉和均匀交叉,且逐步增大均匀交叉的概率%round(unidrnd(eranum-i)/eranum)[MutationPop]=Mutation(CrossOverPop,pMutation,VarNum);%变异[InversionPop]=Inversion(MutationPop,pInversion);%倒位Pop=InversionPop;%更新pMutation=pm0+(i^4)*(pCross/3-pm0)/(eranum^4);%随着种群向前进化,逐步增大变异率至1/2交叉率p(i)=pMutation;i=i+1;endt=1:eranum;plot(t,Trace(:,1)');title('函数优化的遗传算法');xlabel('进化世代数(eranum)');ylabel('每一代最优适应度(maxfitness)');[MaxFval,I]=max(Trace(:,1));X=Trace(I,(2:length(bits)+1));hold on; plot(I,MaxFval,'*');text(I+5,MaxFval,['FMAX=' num2str(MaxFval)]);str1=sprintf ('进化到%d 代,自变量为%s 时,得本次求解的最优值%f\n对应染色体是:%s',I,num2str(X),MaxFval,num2str(BestPop(I,:)));disp(str1);%figure(2);plot(t,p);%绘制变异值增大过程T2=clock;elapsed_time=T2-T1;if elapsed_time(6)<0elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;endif elapsed_time(5)<0elapsed_time(5)=elapsed_time(5)+60;elapsed_time(4)=elapsed_time(4)-1;end %像这种程序当然不考虑运行上小时啦str2=sprintf('程序运行耗时%d 小时%d 分钟%.4f 秒',elapsed_time(4),elapsed_time(5),elapsed_time(6));disp(str2);%初始化种群%采用二进制Gray编码,其目的是为了克服二进制编码的Hamming悬崖缺点function [initpop]=InitPopGray(popsize,bits)len=sum(bits);initpop=zeros(popsize,len);%The whole zero encoding individualfor i=2:popsize-1pop=round(rand(1,len));pop=mod(([0 pop]+[pop 0]),2);%i=1时,b(1)=a(1);i>1时,b(i)=mod(a(i-1)+a(i),2)%其中原二进制串:a(1)a(2)...a(n),Gray串:b(1)b(2)...b(n)initpop(i,:)=pop(1:end-1);endinitpop(popsize,:)=ones(1,len);%The whole one encoding individual%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%解码function [fval] = b2f(bval,bounds,bits)% fval - 表征各变量的十进制数% bval - 表征各变量的二进制编码串% bounds - 各变量的取值范围% bits - 各变量的二进制编码长度scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variablesnumV=size(bounds,1);cs=[0 cumsum(bits)];for i=1:numVa=bval((cs(i)+1):cs(i+1));fval(i)=sum(2.^(size(a,2)-1:-1:0).*a)*scale(i)+bounds(i,1);end%选择操作%采用基于轮盘赌法的非线性排名选择%各个体成员按适应值从大到小分配选择概率:%P(i)=(q/1-(1-q)^n)*(1-q)^i, 其中P(0)>P(1)>...>P(n), sum(P(i))=1function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)global m nselectpop=zeros(m,n);fit=zeros(m,1);for i=1:mfit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据endselectprob=fit/sum(fit);%计算各个体相对适应度(0,1)q=max(selectprob);%选择最优的概率x=zeros(m,2);x(:,1)=[m:-1:1]';[y x(:,2)]=sort(selectprob);r=q/(1-(1-q)^m);%标准分布基值newfit(x(:,2))=r*(1-q).^(x(:,1)-1);%生成选择概率newfit=cumsum(newfit);%计算各选择概率之和rNums=sort(rand(m,1));fitIn=1;newIn=1;while newIn<=mif rNums(newIn)<newfit(fitIn)selectpop(newIn,:)=pop(fitIn,:);newIn=newIn+1;elsefitIn=fitIn+1;endend%交叉操作function [NewPop]=CrossOver(OldPop,pCross,opts)%OldPop为父代种群,pcross为交叉概率global m n NewPopr=rand(1,m);y1=find(r<pCross);y2=find(r>=pCross);len=length(y1);if len>2&mod(len,2)==1%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数y2(length(y2)+1)=y1(len);y1(len)=[];endif length(y1)>=2for i=0:2:length(y1)-2if opts==0[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=EqualCrossOver(OldPop(y1(i+1),:),OldPop(y1(i+2),:));else[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=MultiPointCross(OldPop(y1(i+1),:),OldPop(y1(i+2),:));endendendNewPop(y2,:)=OldPop(y2,:);%采用均匀交叉function [children1,children2]=EqualCrossOver(parent1,parent2)global n children1 children2hidecode=round(rand(1,n));%随机生成掩码crossposition=find(hidecode==1);holdposition=find(hidecode==0);children1(crossposition)=parent1(crossposition);%掩码为1,父1为子1提供基因children1(holdposition)=parent2(holdposition);%掩码为0,父2为子1提供基因children2(crossposition)=parent2(crossposition);%掩码为1,父2为子2提供基因children2(holdposition)=parent1(holdposition);%掩码为0,父1为子2提供基因%采用多点交叉,交叉点数由变量数决定function [Children1,Children2]=MultiPointCross(Parent1,Parent2)global n Children1 Children2 VarNumChildren1=Parent1;Children2=Parent2;Points=sort(unidrnd(n,1,2*VarNum));for i=1:VarNumChildren1(Points(2*i-1):Points(2*i))=Parent2(Points(2*i-1):Points(2*i));Children2(Points(2*i-1):Points(2*i))=Parent1(Points(2*i-1):Points(2*i));end%变异操作function [NewPop]=Mutation(OldPop,pMutation,VarNum)global m n NewPopr=rand(1,m);position=find(r<=pMutation);len=length(position);if len>=1for i=1:lenk=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点for j=1:length(k)if OldPop(position(i),k(j))==1OldPop(position(i),k(j))=0;elseOldPop(position(i),k(j))=1;endendendendNewPop=OldPop;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%倒位操作function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r<=pInversion);len=length(PopIn);if len>=1for i=1:lend=sort(unidrnd(n,1,2));if d(1)~=1&d(2)~=nNewPop(PopIn(i),1:d(1)-1)=OldPop(PopIn(i),1:d(1)-1);NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1));NewPop(PopIn(i),d(2)+1:n)=OldPop(PopIn(i),d(2)+1:n);endendend遗传算法程序(二):function youhuafunD=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);while generation<=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=rnd tmp=A(ind);A(ind)=B(ind);B(ind)=tmp;% % 两点交叉% 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;% 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);for k=3:Ntmprnd=rand;tmpind=tmprnd difind=[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=11*300-maxV;plot(minV,'*');title('各代的目标函数值');F4=D(:,4);FF4=F4-fatherrand(:,1);FF4=max(FF4,1);D(:,5)=FF4;save DData Dfunction D=codeload youhua.mat% properties F2 and F3F1=A(:,1);F2=A(:,2);F3=A(:,3);if (max(F2)>1450)||(min(F2)<=900)error('DATA property F2 exceed it''s range (900,1450]')end% get group property F1 of data, according to F2 valueF4=zeros(size(F1));for ite=11:-1:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[F1,F2,F3,F4];function ScoreN=scorefun(fatherrand,D)F3=D(:,3);F4=D(:,4);N=size(fatherrand,2);FF4=F4*ones(1,N);FF4rnd=FF4-fatherrand;FF4rnd=max(FF4rnd,1);ScoreN=ones(1,N)*300*11;% 这里有待优化for k=1:NFF4k=FF4rnd(:,k);for ite=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;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%遗传算法程序(三):%IAGAfunction best=gaclearMAX_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_genfitness=fit(popus,RANGE); %求适应度f=fitness.f;picked=choose(popus,fitness); %选择popus=intercross(popus,picked); %杂交popus=aberrance(popus,picked); %变异if max(f)>best.max_fadvance_k=advance_k+1;x_better(advance_k)=fitness.x;best.max_f=max(f);best.popus=popus;best.x=fitness.x;endif mod(advance_k,SPEEDUP_INTER)==0RANGE=minmax(x_better);RANGEadvance=0;endendreturn;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:Mx=0;for n=1:Nx=x+popus(m,n)*(2^(n-1));endx=x*((B-A)/(2^N))+A;for k=1:5f(m,1)=f(m,1)-(k*sin((k+1)*x+k));endendf_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:Mx=find(f==f_t(k));%降序排列的个体序号d_order(k)=x(1);endfor m=1:Mpopus_t(m,:)=popus(d_order(m),:);endpopus=popus_t;f=f_t;p=f_std./sum(f_std); %选择概率c_p=cumsum(p)'; %累积概率for cn=1:choose_Npicked(cn,1)=roulette(c_p); %轮盘赌picked(cn,2)=roulette(c_p); %轮盘赌popus=intercross(popus,picked(cn,:));%杂交endpopus=aberrance(popus,picked);%变异return;function popus=intercross(popus,picked) %杂交[M_p,N_p]=size(picked);[M,N]=size(popus);for cn=1:M_pp(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;endreturn;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_pif U(2)>=P_a %如果大于变异概率,就不变异continue;endif U(1)>=0.5a=picked(kp,1);elsea=picked(kp,2);endp(1)=ceil(rand*N);%生成变异位置p(2)=ceil(rand*N);if popus(a,p(1))==1%0 1变换popus(a,p(1))=0;elsepopus(a,p(1))=1;endif popus(a,p(2))==1popus(a,p(2))=0;elsepopus(a,p(2))=1;endendreturn;function picked=roulette(c_p) %轮盘赌[M,N]=size(c_p);M=max([M N]);U=rand;if U<c_p(1)picked=1;return;endfor m=1:(M-1)if U>c_p(m) & U<c_p(m+1)picked=m+1;break;endend全方位的两点杂交、两点变异的改进的加速遗传算法(IAGA)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%。
遗传算法matlab程序代码
遗传算法matlab程序代码遗传算法是一种优化算法,用于在给定的搜索空间中寻找最优解。
在Matlab中,可以通过以下代码编写一个基本的遗传算法:% 初始种群大小Npop = 100;% 搜索空间维度ndim = 2;% 最大迭代次数imax = 100;% 初始化种群pop = rand(Npop, ndim);% 最小化目标函数fun = @(x) sum(x.^2);for i = 1:imax% 计算适应度函数fit = 1./fun(pop);% 选择操作[fitSort, fitIndex] = sort(fit, 'descend');pop = pop(fitIndex(1:Npop), :);% 染色体交叉操作popNew = zeros(Npop, ndim);for j = 1:Npopparent1Index = randi([1, Npop]);parent2Index = randi([1, Npop]);parent1 = pop(parent1Index, :);parent2 = pop(parent2Index, :);crossIndex = randi([1, ndim-1]);popNew(j,:) = [parent1(1:crossIndex),parent2(crossIndex+1:end)];end% 染色体突变操作for j = 1:NpopmutIndex = randi([1, ndim]);mutScale = randn();popNew(j, mutIndex) = popNew(j, mutIndex) + mutScale;end% 更新种群pop = [pop; popNew];end% 返回最优解[resultFit, resultIndex] = max(fit);result = pop(resultIndex, :);以上代码实现了一个简单的遗传算法,用于最小化目标函数x1^2 + x2^2。
遗传算法matlab程序实例
%-----------------------------------------------%---------------------------------------------------遗传算法程序(一):说明: fga.m 为遗传算法的主程序; 采用二进制Gray编码,采用基于轮盘赌法的非线性排名选择, 均匀交叉,变异操作,而且还引入了倒位操作!function [BestPop,Trace]=fga(FUN,LB,UB,eranum,popsize,pCross,pMutation,pInversion,options) % [BestPop,Trace]=fmaxga(FUN,LB,UB,eranum,popsize,pcross,pmutation)% Finds a maximum of a function of several variables.% fmaxga solves problems of the form:% max F(X) subject to: LB <= X <= UB% BestPop - 最优的群体即为最优的染色体群% Trace - 最佳染色体所对应的目标函数值% FUN - 目标函数% LB - 自变量下限% UB - 自变量上限% eranum - 种群的代数,取100--1000(默认200)% popsize - 每一代种群的规模;此可取50--200(默认100)% pcross - 交叉概率,一般取0.5--0.85之间较好(默认0.8)% pmutation - 初始变异概率,一般取0.05-0.2之间较好(默认0.1)% pInversion - 倒位概率,一般取0.05-0.3之间较好(默认0.2)% options - 1*2矩阵,options(1)=0二进制编码(默认0),option(1)~=0十进制编%码,option(2)设定求解精度(默认1e-4)%% ------------------------------------------------------------------------T1=clock;if nargin<3, error('FMAXGA requires at least three input arguments'); endif nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==7, pInversion=0.15;options=[0 1e-4];endif find((LB-UB)>0)error('数据输入错误,请重新输入(LB<UB):');ends=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));disp(s);global m n NewPop children1 children2 VarNumbounds=[LB;UB]';bits=[];VarNum=size(bounds,1);precision=options(2);%由求解精度确定二进制编码长度bits=ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间[Pop]=InitPopGray(popsize,bits);%初始化种群[m,n]=size(Pop);NewPop=zeros(m,n);children1=zeros(1,n);children2=zeros(1,n);pm0=pMutation;BestPop=zeros(eranum,n);%分配初始解空间BestPop,TraceTrace=zeros(eranum,length(bits)+1);i=1;while i<=eranumfor j=1:mvalue(j)=feval(FUN(1,:),(b2f(Pop(j,:),bounds,bits)));%计算适应度end[MaxValue,Index]=max(value);BestPop(i,:)=Pop(Index,:);Trace(i,1)=MaxValue;Trace(i,(2:length(bits)+1))=b2f(BestPop(i,:),bounds,bits);[selectpop]=NonlinearRankSelect(FUN,Pop,bounds,bits);%非线性排名选择[CrossOverPop]=CrossOver(selectpop,pCross,round(unidrnd(eranum-i)/eranum));%采用多点交叉和均匀交叉,且逐步增大均匀交叉的概率%round(unidrnd(eranum-i)/eranum)[MutationPop]=Mutation(CrossOverPop,pMutation,VarNum);%变异[InversionPop]=Inversion(MutationPop,pInversion);%倒位Pop=InversionPop;%更新pMutation=pm0+(i^4)*(pCross/3-pm0)/(eranum^4);%随着种群向前进化,逐步增大变异率至1/2交叉率p(i)=pMutation;i=i+1;endt=1:eranum;plot(t,Trace(:,1)');title('函数优化的遗传算法');xlabel('进化世代数(eranum)');ylabel('每一代最优适应度(maxfitness)');[MaxFval,I]=max(Trace(:,1));X=Trace(I,(2:length(bits)+1));hold on; plot(I,MaxFval,'*');text(I+5,MaxFval,['FMAX=' num2str(MaxFval)]);str1=sprintf ('进化到%d 代,自变量为%s 时,得本次求解的最优值%f\n对应染色体是:%s',I,num2str(X),MaxFval,num2str(BestPop(I,:)));disp(str1);%figure(2);plot(t,p);%绘制变异值增大过程T2=clock;elapsed_time=T2-T1;if elapsed_time(6)<0elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;endif elapsed_time(5)<0elapsed_time(5)=elapsed_time(5)+60;elapsed_time(4)=elapsed_time(4)-1;end %像这种程序当然不考虑运行上小时啦str2=sprintf('程序运行耗时%d 小时%d 分钟%.4f 秒',elapsed_time(4),elapsed_time(5),elapsed_time(6));disp(str2);%初始化种群%采用二进制Gray编码,其目的是为了克服二进制编码的Hamming悬崖缺点function [initpop]=InitPopGray(popsize,bits)len=sum(bits);initpop=zeros(popsize,len);%The whole zero encoding individualfor i=2:popsize-1pop=round(rand(1,len));pop=mod(([0 pop]+[pop 0]),2);%i=1时,b(1)=a(1);i>1时,b(i)=mod(a(i-1)+a(i),2)%其中原二进制串:a(1)a(2)...a(n),Gray串:b(1)b(2)...b(n)initpop(i,:)=pop(1:end-1);endinitpop(popsize,:)=ones(1,len);%The whole one encoding individual%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%解码function [fval] = b2f(bval,bounds,bits)% fval - 表征各变量的十进制数% bval - 表征各变量的二进制编码串% bounds - 各变量的取值范围% bits - 各变量的二进制编码长度scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variablesnumV=size(bounds,1);cs=[0 cumsum(bits)];for i=1:numVa=bval((cs(i)+1):cs(i+1));fval(i)=sum(2.^(size(a,2)-1:-1:0).*a)*scale(i)+bounds(i,1);end%选择操作%采用基于轮盘赌法的非线性排名选择%各个体成员按适应值从大到小分配选择概率:%P(i)=(q/1-(1-q)^n)*(1-q)^i, 其中P(0)>P(1)>...>P(n), sum(P(i))=1function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)global m nselectpop=zeros(m,n);fit=zeros(m,1);for i=1:mfit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据endselectprob=fit/sum(fit);%计算各个体相对适应度(0,1)q=max(selectprob);%选择最优的概率x=zeros(m,2);x(:,1)=[m:-1:1]';[y x(:,2)]=sort(selectprob);r=q/(1-(1-q)^m);%标准分布基值newfit(x(:,2))=r*(1-q).^(x(:,1)-1);%生成选择概率newfit=cumsum(newfit);%计算各选择概率之和rNums=sort(rand(m,1));fitIn=1;newIn=1;while newIn<=mif rNums(newIn)<newfit(fitIn)selectpop(newIn,:)=pop(fitIn,:);newIn=newIn+1;elsefitIn=fitIn+1;endend%交叉操作function [NewPop]=CrossOver(OldPop,pCross,opts)%OldPop为父代种群,pcross为交叉概率global m n NewPopr=rand(1,m);y1=find(r<pCross);y2=find(r>=pCross);len=length(y1);if len>2&mod(len,2)==1%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数y2(length(y2)+1)=y1(len);y1(len)=[];endif length(y1)>=2for i=0:2:length(y1)-2if opts==0[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=EqualCrossOver(OldPop(y1(i+1),:),OldPop(y1(i+2),:));else[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=MultiPointCross(OldPop(y1(i+1),:),OldPop(y1(i+2),:));endendendNewPop(y2,:)=OldPop(y2,:);%采用均匀交叉function [children1,children2]=EqualCrossOver(parent1,parent2)global n children1 children2hidecode=round(rand(1,n));%随机生成掩码crossposition=find(hidecode==1);holdposition=find(hidecode==0);children1(crossposition)=parent1(crossposition);%掩码为1,父1为子1提供基因children1(holdposition)=parent2(holdposition);%掩码为0,父2为子1提供基因children2(crossposition)=parent2(crossposition);%掩码为1,父2为子2提供基因children2(holdposition)=parent1(holdposition);%掩码为0,父1为子2提供基因%采用多点交叉,交叉点数由变量数决定function [Children1,Children2]=MultiPointCross(Parent1,Parent2)global n Children1 Children2 VarNumChildren1=Parent1;Children2=Parent2;Points=sort(unidrnd(n,1,2*VarNum));for i=1:VarNumChildren1(Points(2*i-1):Points(2*i))=Parent2(Points(2*i-1):Points(2*i));Children2(Points(2*i-1):Points(2*i))=Parent1(Points(2*i-1):Points(2*i));end%变异操作function [NewPop]=Mutation(OldPop,pMutation,VarNum)global m n NewPopr=rand(1,m);position=find(r<=pMutation);len=length(position);if len>=1for i=1:lenk=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点for j=1:length(k)if OldPop(position(i),k(j))==1OldPop(position(i),k(j))=0;elseOldPop(position(i),k(j))=1;endendendendNewPop=OldPop;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%倒位操作function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r<=pInversion);len=length(PopIn);if len>=1for i=1:lend=sort(unidrnd(n,1,2));if d(1)~=1&d(2)~=nNewPop(PopIn(i),1:d(1)-1)=OldPop(PopIn(i),1:d(1)-1);NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1));NewPop(PopIn(i),d(2)+1:n)=OldPop(PopIn(i),d(2)+1:n);endendend遗传算法程序(二):function youhuafunD=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);while generation<=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=rnd tmp=A(ind);A(ind)=B(ind);B(ind)=tmp;% % 两点交叉% 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;% 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);for k=3:Ntmprnd=rand;tmpind=tmprnd difind=[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=11*300-maxV;plot(minV,'*');title('各代的目标函数值');F4=D(:,4);FF4=F4-fatherrand(:,1);FF4=max(FF4,1);D(:,5)=FF4;save DData Dfunction D=codeload youhua.mat% properties F2 and F3F1=A(:,1);F2=A(:,2);F3=A(:,3);if (max(F2)>1450)||(min(F2)<=900)error('DATA property F2 exceed it''s range (900,1450]')end% get group property F1 of data, according to F2 valueF4=zeros(size(F1));for ite=11:-1:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[F1,F2,F3,F4];function ScoreN=scorefun(fatherrand,D)F3=D(:,3);F4=D(:,4);N=size(fatherrand,2);FF4=F4*ones(1,N);FF4rnd=FF4-fatherrand;FF4rnd=max(FF4rnd,1);ScoreN=ones(1,N)*300*11;% 这里有待优化for k=1:NFF4k=FF4rnd(:,k);for ite=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;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%遗传算法程序(三):%IAGAfunction best=gaclearMAX_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_genfitness=fit(popus,RANGE); %求适应度f=fitness.f;picked=choose(popus,fitness); %选择popus=intercross(popus,picked); %杂交popus=aberrance(popus,picked); %变异if max(f)>best.max_fadvance_k=advance_k+1;x_better(advance_k)=fitness.x;best.max_f=max(f);best.popus=popus;best.x=fitness.x;endif mod(advance_k,SPEEDUP_INTER)==0RANGE=minmax(x_better);RANGEadvance=0;endendreturn;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:Mx=0;for n=1:Nx=x+popus(m,n)*(2^(n-1));endx=x*((B-A)/(2^N))+A;for k=1:5f(m,1)=f(m,1)-(k*sin((k+1)*x+k));endendf_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:Mx=find(f==f_t(k));%降序排列的个体序号d_order(k)=x(1);endfor m=1:Mpopus_t(m,:)=popus(d_order(m),:);endpopus=popus_t;f=f_t;p=f_std./sum(f_std); %选择概率c_p=cumsum(p)'; %累积概率for cn=1:choose_Npicked(cn,1)=roulette(c_p); %轮盘赌picked(cn,2)=roulette(c_p); %轮盘赌popus=intercross(popus,picked(cn,:));%杂交endpopus=aberrance(popus,picked);%变异return;function popus=intercross(popus,picked) %杂交[M_p,N_p]=size(picked);[M,N]=size(popus);for cn=1:M_pp(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;endreturn;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_pif U(2)>=P_a %如果大于变异概率,就不变异continue;endif U(1)>=0.5a=picked(kp,1);elsea=picked(kp,2);endp(1)=ceil(rand*N);%生成变异位置p(2)=ceil(rand*N);if popus(a,p(1))==1%0 1变换popus(a,p(1))=0;elsepopus(a,p(1))=1;endif popus(a,p(2))==1popus(a,p(2))=0;elsepopus(a,p(2))=1;endendreturn;function picked=roulette(c_p) %轮盘赌[M,N]=size(c_p);M=max([M N]);U=rand;if U<c_p(1)picked=1;return;endfor m=1:(M-1)if U>c_p(m) & U<c_p(m+1)picked=m+1;break;endend全方位的两点杂交、两点变异的改进的加速遗传算法(IAGA)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%。
用遗传算法求解多目标函数优化c++程序
遗传算法是一种优化搜索方法,它模拟了自然选择和遗传学中的一些概念,如基因突变、交叉和选择。
这种方法可以用于解决多目标优化问题,其中多个目标之间可能存在冲突。
以下是一个使用C++和OpenCV库实现遗传算法的基本示例。
这个例子解决的是一个简单的多目标优化问题,目标是找到一个最优的图像分割方案,使得两个目标(分割的精度和计算的效率)同时最大化。
注意:这个示例是为了演示遗传算法的基本概念,并不一定适用于所有问题。
你可能需要根据你的具体需求来调整遗传算法的参数和约束条件。
```cpp#include <iostream>#include <vector>#include <algorithm>#include <opencv2/opencv.hpp>// 多目标函数优化struct ObjectiveFunction {std::vector<double> values;void operator()(const std::vector<double>& x) const {// 这里应该根据你的具体问题来定义函数的具体形式// 这里只是一个简单的示例,只考虑了分割精度和计算效率两个目标values.resize(x.size(), 0); // 初始化所有目标值为0values[0] = 1.0; // 精度目标values[1] = 1.0; // 效率目标}};class GeneticAlgorithm {public:GeneticAlgorithm(int populationSize, int generations, double crossoverRate, double mutationRate) : populationSize(populationSize), generations(generations), crossoverRate(crossoverRate), mutationRate(mutationRate) {} std::vector<std::vector<double>> optimize(const std::vector<std::vector<double>>& inputs) {std::vector<std::vector<double>>bestSolution(inputs.size(),std::vector<double>(populationSize, 0)); // 初始化最优解double bestScore = -1; // 初始最佳分数为-1,通常需要先运行一次算法以找到初始最佳分数for (int generation = 0; generation <generations; ++generation) {std::vector<std::vector<double>>population(populationSize,std::vector<double>(populationSize, 0)); // 初始化种群for (int i = 0; i < populationSize; ++i) { std::vector<double>randomSolution(inputs.size(), 0); // 随机生成解for (int j = 0; j < inputs.size(); ++j) {randomSolution[j] = inputs[j][rand() % inputs[j].size()]; // 在输入范围内随机选择一个数作为解}population[i] = randomSolution; // 将随机解加入种群}while (!population.empty()) { // 当种群不为空时继续迭代std::sort(population.begin(), population.end(), [](const std::vector<double>& a, const std::vector<double>& b) { // 对种群进行排序,根据适应度进行排序(这里适应度是解的分数)return ObjectiveFunction()(a) > ObjectiveFunction()(b); // 如果分数更高,则适应度更好,优先选择这个解作为下一代解的一部分});std::vector<double>nextGeneration(population[0]); // 选择当前种群中的第一个解作为下一代解的一部分for (int j = 1; j < populationSize; ++j) { // 对剩余的解进行交叉和变异操作,生成下一代解if (rand() / double(RAND_MAX) < crossoverRate) { // 如果满足交叉条件,则进行交叉操作for (int k = 0; k < inputs.size(); ++k) { // 将两个解的部分基因进行交叉操作,生成新的基因序列nextGeneration[k] = population[j][k]; // 将两个解的部分基因复制到下一代解中if (rand() / double(RAND_MAX) < mutationRate) { // 如果满足变异条件,则对部分基因进行变异操作,增加种群的多样性nextGeneration[k] = nextGeneration[k] * (1 - mutationRate) + population[j][k] * mutationRate; // 对部分基因进行变异操作,增加种群的多样性}}} else { // 如果不满足交叉条件,则直接复制当前解作为下一代解的一部分for (int k = 0; k < inputs.size(); ++k) { // 将当前解的部分基因复制到下一代解中 nextGeneration[k] = population[。
用Python实现遗传算法(GA)(一)
用Python实现遗传算法(GA)(一)用Python实现遗传算法(GA)(一)遗传算法(Genetic Algorithm,GA)是一种模拟生物进化过程的优化算法。
它模拟了自然界中的遗传、交叉和变异等操作,通过不断优化种群中的个体来找到问题的最优解。
在本篇文章中,我们将用Python实现一个简单的遗传算法。
首先,我们需要定义问题的适应度函数。
适应度函数用来评估每个个体的优劣程度,它决定了个体在繁殖中的概率。
在这个例子中,我们将解决一个简单的函数最小化问题,即找到函数f(x)=x^2的最小值。
我们可以定义适应度函数如下:```pythondef fitness_function(x):return x**2```接下来,我们需要定义种群的初始化函数。
种群是由一组个体组成的,每个个体都表示问题的一个解。
在这个例子中,我们将随机生成一组初始解作为种群的初始状态。
```pythonimport randomdef initialize_population(population_size, chromosome_size): population = []for _ in range(population_size):chromosome = [random.randint(0, 1) for _ inrange(chromosome_size)]population.append(chromosome)return population```然后,我们需要定义选择操作。
选择操作用来根据个体的适应度值选择出下一代的个体。
常用的选择操作包括轮盘赌选择和排名选择等。
在这个例子中,我们将使用轮盘赌选择。
```pythondef roulette_wheel_selection(population, fitness_values):total_fitness = sum(fitness_values)probabilities = [fitness / total_fitness for fitness in fitness_values]cumulative_probabilities = [sum(probabilities[:i+1]) for i in range(len(probabilities))]selected_population = []for _ in range(len(population)):random_number = random.randomfor i in range(len(cumulative_probabilities)):if random_number <= cumulative_probabilities[i]:selected_population.append(population[i])breakreturn selected_population```接下来,我们需要定义交叉操作。
十进制遗传算法完整程序
• • • • • • • • • • • • • • • • • • • • • • • • • •
%--------------------------------------------% % % % % 交叉操作 % % %--------------------------------------------% function [pop]=crossover(pop,nvars,psize,pc) %----------采用算术交叉,pc为交叉概率 采用算术交叉, 为交叉概率 为交叉概率------------% 采用算术交叉 first=0; one=0; for i=1:psize ran1=rand; %----若随机数小于交叉概率,选择该个体进行交叉----% 若随机数小于交叉概率,选择该个体进行交叉 若随机数小于交叉概率 if ran1<pc first=first+1; if(mod(first,2)==0) % mod(first,2)--求余 求余 ran2=rand; for j=1:nvars pop(one,j)=pop(i,j)*ran2+pop(one,j)*(1-ran2); pop(i,j)=pop(one,j)*ran2+pop(i,j)*(1-ran2); end else one=i; end end end
• • • • • • • • • •
%--------------------------------------------% % % % 初始化 % % % %--------------------------------------------% function [pop]=initialize(nvars,psize) %--pop-种群,nvars-变量个数,psize-种群大小---% %------读入变量范围,注意数据文件的路径-------% load e:\abc.txt lbound=abc(:,1); %取矩阵的第一列为变量的下边 届 • ubound=abc(:,2); %取矩阵的第二列为变量的上边 届 • %----------------采用实数编码--------------% • • for i=1:psize • for j=1:nvars • pop(i,j)=rand*(ubound(j)-lbound(j))+lbound(j); %对变量进行初始 化,rand产生[0,1]内的随机数 • end • end
完整的遗传算法函数Matlab程序【精品毕业设计】(完整版)
完整的遗传算法函数Matlab程序function [x,endPop,bPop,traceInfo] = ga(bounds,eevalFN,eevalOps,startPop,opts,... termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)n=nargin;if n<2 | n==6 | n==10 | n==12disp('Insufficient arguements')endif n<3 %Default eevalation opts.eevalOps=[];endif n<5opts = [1e-6 1 0];endif isempty(opts)opts = [1e-6 1 0];endif any(eevalFN<48) %Not using a .m fileif opts(2)==1 %Float gae1str=['x=c1; c1(xZomeLength)=', eevalFN ';'];e2str=['x=c2; c2(xZomeLength)=', eevalFN ';'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...eevalFN ';'];endelse %Are using a .m fileif opts(2)==1 %Float gae1str=['[c1 c1(xZomeLength)]=' eevalFN '(c1,[gen eevalOps]);'];e2str=['[c2 c2(xZomeLength)]=' eevalFN '(c2,[gen eevalOps]);'];else %Binary gae1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' eevalFN ...'(x,[gen eevalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];endendif n<6 %Default termination informationtermOps=[100];termFN='maxGenTerm';endif n<12 %Default muatation informationif opts(2)==1 %Float GAmutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation']; mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];else %Binary GAmutFNs=['binaryMutation'];mutOps=[0.05];endendif n<10 %默认的交叉信息if opts(2)==1 %浮点编码xOverFNs=['arithXover heuristicXover simpleXover'];xOverOps=[2 0;2 3;2 0];else %Binary GAxOverFNs=['simpleXover'];xOverOps=[0.6];endendif n<9 %Default select opts only i.e. roullete wheel.selectOps=[];endif n<8 %Default select infoselectFN=['normGeomSelect'];selectOps=[0.08];endif n<6 %默认的算法终止准则termOps=[100];termFN='maxGenTerm';endif n<4 %初始种群为空startPop=[];endif isempty(startPop) %随机生成初始种群startPop=initializega(80,bounds,eevalFN,eevalOps,opts(1:2));endif opts(2)==0 %二进制编码bits=calcbits(bounds,opts(1));endxOverFNs=parse(xOverFNs);mutFNs=parse(mutFNs);xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness numVar = xZomeLength-1; %变量数目popSize = size(startPop,1); %种群中个体数目endPop = zeros(popSize,xZomeLength); %次种群矩阵c1 = zeros(1,xZomeLength); %个体c2 = zeros(1,xZomeLength); %个体numXOvers = size(xOverFNs,1); %交叉操作次数numMuts = size(mutFNs,1); %变异操作次数epsilon = opts(1); %适应度门限值oeval = max(startPop(:,xZomeLength)); %初始种群中的最优值bFoundIn = 1;done = 0;gen = 1;collectTrace = (nargout>3);floatGA = opts(2)==1;display = opts(3);while(~done)[beval,bindx] = max(startPop(:,xZomeLength)); %当前种群的最优值best = startPop(bindx,:);if collectTracetraceInfo(gen,1)=gen; %当前代traceInfo(gen,2)=startPop(bindx,xZomeLength); %最优适应度traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %平均适应度traceInfo(gen,4)=std(startPop(:,xZomeLength));endif ( (abs(beval - oeval)>epsilon) | (gen==1))if displayfprintf(1,'\n%d %f\n',gen,beval);endif floatGAbPop(bFoundIn,:)=[gen startPop(bindx,:)];elsebPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)... startPop(bindx,xZomeLength)];endbFoundIn=bFoundIn+1;oeval=beval;elseif displayfprintf(1,'%d ',gen);endendendPop = feeval(selectFN,startPop,[gen selectOps]); %选择操作if floatGAfor i=1:numXOvers,for j=1:xOverOps(i,1),a = round(rand*(popSize-1)+1); %一个父代个体b = round(rand*(popSize-1)+1); %另一个父代个体xN=deblank(xOverFNs(i,:)); %交叉函数[c1 c2] = feeval(xN,endPop(a,:),endPop(b,:),bounds,[gen… xOverOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseif c1(1:numVar)==endPop(b,(1:numVar))c1(xZomeLength)=endPop(b,xZomeLength);elseeeval(e1str);endif c2(1:numVar)==endPop(a,(1:numVar))c2(xZomeLength)=endPop(a,xZomeLength);elseif c2(1:numVar)==endPop(b,(1:numVar))c2(xZomeLength)=endPop(b,xZomeLength);elseeeval(e2str);endendPop(a,:)=c1;endPop(b,:)=c2;endendfor i=1:numMuts,for j=1:mutOps(i,1),a = round(rand*(popSize-1)+1);c1 = feeval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);if c1(1:numVar)==endPop(a,(1:numVar))c1(xZomeLength)=endPop(a,xZomeLength);elseeeval(e1str);endendPop(a,:)=c1;endendelse %遗传操作的统计模型for i=1:numXOvers,xN=deblank(xOverFNs(i,:));cp=find(rand(popSize,1)if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); endcp=reshape(cp,size(cp,1)/2,2);for j=1:size(cp,1)a=cp(j,1); b=cp(j,2);[endPop(a,:) endPop(b,:)] = feeval(xN,endPop(a,:),endPop(b,:), bounds,[gen xOverOps(i,:)]); endendfor i=1:numMutsmN=deblank(mutFNs(i,:));for j=1:popSizeendPop(j,:) = feeval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);eeval(e1str);endendend。
遗传算法程序
遗传算法程序functionret=Mutation(pmutation,lenchrom,chrom,sizepop,pop,bound) % 本函数完成变异操作% pcorss input : 变异概率% lenchrom input : 染色体长度% chrom input : 染色体群% sizepop input : 种群规模% pop input : 当前种群的进化代数和最大的进化代数信息% ret output : 变异后的染色体fori=1:sizepop% 随机选择一个染色体进行变异pick=rand;while pick==0pick=rand;endindex=ceil(pick*sizepop);% 变异概率决定该轮循环是否进行变异pick=rand;if pick>pmutationcontinue;endflag=0;while flag==0% 变异位置pick=rand;while pick==0pick=rand;endpos=ceil(pick*sum(lenchrom)); %随机选择了染色体变异的位置,即选择了第pos个变量进行变异v=chrom(i,pos);v1=v-bound(pos,1);v2=bound(pos,2)-v;pick=rand; %变异开始if pick>0.5delta=v2*(1-pick^((1-pop(1)/pop(2))^2));chrom(i,pos)=v+delta;elsedelta=v1*(1-pick^((1-pop(1)/pop(2))^2));chrom(i,pos)=v-delta;end %变异结束flag=test(lenchrom,bound,chrom(i,:)); %检验染色体的可行性endendret=chrom;Ga优化pso%% GA 优化PSO%% 清空环境clc;clearclose all%% 参数初始化lenchrom=7; %字符串长度(个体长度),染色体编码长度pc=0.7; %设置交叉概率,本例中交叉概率是定值,若想设置变化的交叉概率可用表达式表示,或从写一个交叉概率函数,例如用神经网络训练得到的值作为交叉概率pm=0.3; %设置变异概率,同理也可设置为变化的%粒子群算法中的两个参数c1 = 1.49445;c2 = 1.49445;maxgen=20; % 进化次数popsize=30; %种群规模%粒子更新速度Vmax=1;Vmin=-1;%种群popmax=50;popmin=-50;% 变量取值范围bound=[popminpopmax;popminpopmax;popminpopmax;p opminpopmax;popminpopmax;popminpopmax;popminpopmax]; %变量范围% 优化粒子数目par_num=7;%% 产生初始粒子和速度fori=1:popsize%随机产生一个种群pop(i,:)=popmax*rands(1,par_num); %初始种群V(i,:)=rands(1,par_num); %初始化速度%计算适应度fitness(i)=fun(pop(i,:)); %染色体的适应度end%找最好的染色体[bestfitnessbestindex]=min(fitness);zbest=pop(bestindex,:); %全局最佳gbest=pop; %个体最佳fitnessgbest=fitness; %个体最佳适应度值fitnesszbest=bestfitness; %全局最佳适应度值%% 迭代寻优fori=1:maxgenifor j=1:popsize%速度更新PSO选择更新V(j,:) = V(j,:) + c1*rand*(gbest(j,:) - pop(j,:)) + c2*rand*(zbest - pop(j,:));V(j,find(V(j,:)>Vmax))=Vmax;V(j,find(V(j,:)< p="">%种群更新PSO选择更新pop(j,:)=pop(j,:)+0.5*V(j,:);pop(j,find(pop(j,:)>popmax))=popmax;pop(j,find(pop(j,:)< p="">% 交叉操作GAGApop=Cross(pc,lenchrom,pop,popsize,bound);% 变异操作GA变异GApop=Mutation(pm,lenchrom,GApop,popsize,[imaxgen],b ound);pop=GApop; % GA pop --> PSO pop% 适应度值-->约束条件if0.072*pop(j,1)+0.063*pop(j,2)+0.057*pop(j,3)+0.05*pop(j,4 )+0.032*pop(j,5)+0.0442*pop(j,6)+0 .0675*pop(j,7)<=264.4 if128*pop(j,1)+78.1*pop(j,2)+64.1*pop(j,3)+43*pop(j,4)+58. 1*pop(j,5)+36.9*pop(j,6)+50.5*pop(j, 7)<=69719fitness(j)=fun(pop(j,:));endend%个体最优更新if fitness(j) <fitnessgbest(j)< p="">gbest(j,:) = pop(j,:);fitnessgbest(j) = fitness(j);end%群体最优更新if fitness(j) <fitnesszbest< p="">zbest = pop(j,:);fitnesszbest = fitness(j);endendyy(i)=fitnesszbest;end%% 结果disp '*************best particle number****************' zbest %%plot(yy,'linewidth',2);grid ontitle(['适应度曲线' '终止代数=' num2str(maxgen)]); xlabel('进化代数');ylabel('适应度');</fitnesszbest<></fitnessgbest(j)<><><>。
(完整版)遗传算法matlab实现源程序
附页:一.遗传算法源程序:clc; clear;population;%评价目标函数值for uim=1:popsizevector=population(uim,:);obj(uim)=hanshu(hromlength,vector,phen);end%obj%min(obj)clear uim;objmin=min(obj);for sequ=1:popsizeif obj(sequ)==objminopti=population(sequ,:);endendclear sequ;fmax=22000;%==for gen=1:maxgen%选择操作%将求最小值的函数转化为适应度函数for indivi=1:popsizeobj1(indivi)=1/obj(indivi);endclear indivi;%适应度函数累加总合total=0;for indivi=1:popsizetotal=total+obj1(indivi);endclear indivi;%每条染色体被选中的几率for indivi=1:popsizefitness1(indivi)=obj1(indivi)/total;endclear indivi;%各条染色体被选中的范围for indivi=1:popsizefitness(indivi)=0;for j=1:indivifitness(indivi)=fitness(indivi)+fitness1(j);endendclear j;fitness;%选择适应度高的个体for ranseti=1:popsizeran=rand;while (ran>1||ran<0)ran=rand;endran;if ran〈=fitness(1)newpopulation(ranseti,:)=population(1,:);elsefor fet=2:popsizeif (ran〉fitness(fet—1))&&(ran<=fitness(fet))newpopulation(ranseti,:)=population(fet,:);endendendendclear ran;newpopulation;%交叉for int=1:2:popsize-1popmoth=newpopulation(int,:);popfath=newpopulation(int+1,:);popcross(int,:)=popmoth;popcross(int+1,:)=popfath;randnum=rand;if(randnum〈 P>cpoint1=round(rand*hromlength);cpoint2=round(rand*hromlength);while (cpoint2==cpoint1)cpoint2=round(rand*hromlength);endif cpoint1>cpoint2tem=cpoint1;cpoint1=cpoint2;cpoint2=tem;endcpoint1;cpoint2;for term=cpoint1+1:cpoint2for ss=1:hromlengthif popcross(int,ss)==popfath(term)tem1=popcross(int,ss);popcross(int,ss)=popcross(int,term);popcross(int,term)=tem1;endendclear tem1;endfor term=cpoint1+1:cpoint2for ss=1:hromlengthif popcross(int+1,ss)==popmoth(term)tem1=popcross(int+1,ss);popcross(int+1,ss)=popcross(int+1,term);popcross(int+1,term)=tem1;endendclear tem1;endendclear term;endclear randnum;popcross;%变异操作newpop=popcross;for int=1:popsizerandnum=rand;if randnumcpoint12=round(rand*hromlength);cpoint22=round(rand*hromlength);if (cpoint12==0)cpoint12=1;endif (cpoint22==0)cpoint22=1;endwhile (cpoint22==cpoint12)cpoint22=round(rand*hromlength);if cpoint22==0;cpoint22=1;endendtemp=newpop(int,cpoint12);newpop(int,cpoint12)=newpop(int,cpoint22);newpop(int,cpoint22)=temp;。
遗传算法程序代码-- 背包问题
背包问题:clearclcpopsize=500;%种群大小n=50;CW=1000;%背包大小可容纳的总重量w=[80 82 85 70 72 70 66 50 55 25 50 55 40 48 50 32 22 60 30 32 ...40 38 35 32 25 28 30 22 50 30 45 30 60 50 20 65 20 25 30 10 ...20 25 15 10 10 10 4 4 2 1];%各个物品的重量,50个个体v=[220 208 198 192 180 180 165 162 160 158 155 130 125 122 120 118 115 110 105 101 ...100 100 98 96 95 90 88 82 80 77 75 73 72 70 69 66 65 63 60 58 ...56 50 30 20 15 10 8 5 3 1];%各个物品的价值,50个个体t=100;%迭代次数pc=0.9;%交叉率pm=0.05;%变异率pop=initpop(popsize,n); %产生初始种群for i=1:500[objvalue]=calobjvalue(pop,n,popsize,v,w,CW); %计算目标函数[fitvalue]=calfitvalue(objvalue);%计算群体中每个个体的适应度[newpop]=selection(pop,fitvalue);%进行选择计算[newpop1]=crossover(newpop,pc);%进行交叉计算[newpop2]=mutation(newpop1,pm);%进行变异计算[newobjvalue]=newcalobjvalue(newpop2,n,popsize,v,w,CW); %计算最新代目标函数值,经过选择交叉变异后的下一代[newfitvalue]=newcalfitvalue(newobjvalue);%计算最新代的个体适应度[bestweight,bestvalue]=best(newpop2,newfitvalue,w); %计算最优个体重量,价值,和位置y(i)=max(bestvalue);%记录最大价值g(i)=max(bestweight);%记录最大重量n(i)=i;%记录位置pop=newpop2;%迭代重复endi=1:500;plot(y(i),'-b*')xlabel('迭代次数')ylabel('最大价值');title('最优点变化趋势');legend('最优点');grid on[z index]=max(y);po=n(index)%最优代数位置W=g(index)%最优重量V=z%最优价值%误差率计算%文献中的结果:算法最大迭代次数总价值为总重量为%传统的算法4003077999%佳点集算法7031031000%遗传算法7531031000%本程序中的计算与文献结果的比较p1=(3077-V)/3077%与传统算法相比的误差率p2=(3103-V)/3103%与佳点集算法相比的误差率p3=(3103-V)/3103%与贪心算法遗传算法相比的误差率function [bestweight,bestvalue]=best(newpop2,newfitvalue,w) %寻找最优个体,包括其重量和价值。
遗传算法的流程图
一需求分析1.本程序演示的是用简单遗传算法随机一个种群,然后根据所给的交叉率,变异率,世代数计算最大适应度所在的代数2.演示程序以用户和计算机的对话方式执行,即在计算机终端上显示“提示信息”之后,由用户在键盘上输入演示程序中规定的命令;相应的输入数据和运算结果显示在其后。
3.测试数据输入初始变量后用y=100*(x1*x1-x2)*(x1*x2-x2)+(1-x1)*(1-x1)其中-2.048<=x1,x2<=2.048作适应度函数求最大适应度即为函数的最大值二概要设计1.程序流程图2.类型定义int popsize; //种群大小int maxgeneration; //最大世代数double pc; //交叉率double pm; //变异率struct individual{char chrom[chromlength+1];double value;double fitness; //适应度};int generation; //世代数int best_index;int worst_index;struct individual bestindividual; //最佳个体struct individual worstindividual; //最差个体struct individual currentbest;struct individual population[POPSIZE];3.函数声明void generateinitialpopulation();void generatenextpopulation();void evaluatepopulation();long decodechromosome(char *,int,int);void calculateobjectvalue();void calculatefitnessvalue();void findbestandworstindividual();void performevolution();void selectoperator();void crossoveroperator();void mutationoperator();void input();void outputtextreport();4.程序的各函数的简单算法说明如下:(1).void generateinitialpopulation ()和void input ()初始化种群和遗传算法参数。
遗传算法解决TSP问题的matlab程序
1.遗传算法解决TSP 问题(附matlab源程序)2.知n个城市之间的相互距离,现有一个推销员必须遍访这n个城市,并且每个城市3.只能访问一次,最后又必须返回出发城市。
如何安排他对这些城市的访问次序,可使其4.旅行路线的总长度最短?5.用图论的术语来说,假设有一个图g=(v,e),其中v是顶点集,e是边集,设d=(dij)6.是由顶点i和顶点j之间的距离所组成的距离矩阵,旅行商问题就是求出一条通过所有顶7.点且每个顶点只通过一次的具有最短距离的回路。
8.这个问题可分为对称旅行商问题(dij=dji,,任意i,j=1,2,3,…,n)和非对称旅行商9.问题(dij≠dji,,任意i,j=1,2,3,…,n)。
10.若对于城市v={v1,v2,v3,…,vn}的一个访问顺序为t=(t1,t2,t3,…,ti,…,tn),其中11.ti∈v(i=1,2,3,…,n),且记tn+1= t1,则旅行商问题的数学模型为:12.min l=σd(t(i),t(i+1)) (i=1,…,n)13.旅行商问题是一个典型的组合优化问题,并且是一个np难问题,其可能的路径数目14.与城市数目n是成指数型增长的,所以一般很难精确地求出其最优解,本文采用遗传算法15.求其近似解。
16.遗传算法:17.初始化过程:用v1,v2,v3,…,vn代表所选n个城市。
定义整数pop-size作为染色体的个数18.,并且随机产生pop-size个初始染色体,每个染色体为1到18的整数组成的随机序列。
19.适应度f的计算:对种群中的每个染色体vi,计算其适应度,f=σd(t(i),t(i+1)).20.评价函数eval(vi):用来对种群中的每个染色体vi设定一个概率,以使该染色体被选中21.的可能性与其种群中其它染色体的适应性成比例,既通过轮盘赌,适应性强的染色体被22.选择产生后台的机会要大,设alpha∈(0,1),本文定义基于序的评价函数为eval(vi)=al23.pha*(1-alpha).^(i-1) 。
遗传算法matlab程序代码
function [R,Rlength]= GA_TSP(xyCity,dCity,Population,nPopulation,pCrossover,percent,pMutation,generation,nR,rr,rang eCity,rR,moffspring,record,pi,Shock,maxShock)clear allA=load('d.txt');AxyCity=[A(1,:);A(2,:)]; %x,y为各地点坐标xyCityfigure(1)grid onhold onscatter(xyCity(1,:),xyCity(2,:),'b+')grid onnCity=50;nCityfor i=1:nCity %计算城市间距离for j=1:nCitydCity(i,j)=abs(xyCity(1,i)-xyCity(1,j))+abs(xyCity(2,i)-xyCity(2,j));endend %计算城市间距离xyCity; %显示城市坐标dCity %显示城市距离矩阵%初始种群k=input('取点操作结束'); %取点时对操作保护disp('-------------------')nPopulation=input('种群个体数量:'); %输入种群个体数量if size(nPopulation,1)==0nPopulation=50; %默认值endfor i=1:nPopulationPopulation(i,:)=randperm(nCity-1); %产生随机个体endPopulation %显示初始种群pCrossover=input('交叉概率:'); %输入交叉概率percent=input('交叉部分占整体的百分比:'); %输入交叉比率pMutation=input('突变概率:'); %输入突变概率nRemain=input('最优个体保留最大数量:');pi(1)=input('选择操作最优个体被保护概率:');%输入最优个体被保护概率pi(2)=input('交叉操作最优个体被保护概率:');pi(3)=input('突变操作最优个体被保护概率:');maxShock=input('最大突变概率:');if size(pCrossover,1)==0pCrossover=0.85;endif size(percent,1)==0percent=0.5;endif size(pMutation,1)==0pMutation=0.05;endShock=0;rr=0;Rlength=0;counter1=0;counter2=0;R=zeros(1,nCity-1);[newPopulation,R,Rlength,counter2,rr]=select(Population,nPopulation,nCity,dCity,Rlength,R,coun ter2,pi,nRemain);R0=R;record(1,:)=R;rR(1)=Rlength;Rlength0=Rlength;generation=input('算法终止条件A.最多迭代次数:');%输入算法终止条件if size(generation,1)==0generation=200;endnR=input('算法终止条件B.最短路径连续保持不变代数:');if size(nR,1)==0nR=10;endwhile counter1<generation&counter2<nRif counter2<nR*1/5Shock=0;elseif counter2<nR*2/5Shock=maxShock*1/4-pMutation;elseif counter2<nR*3/5Shock=maxShock*2/4-pMutation;elseif counter2<nR*4/5Shock=maxShock*3/4-pMutation;elseShock=maxShock-pMutation;endcounter1newPopulationoffspring=crossover(newPopulation,nCity,pCrossover,percent,nPopulation,rr,pi,nRemain);offspringmoffspring=Mutation(offspring,nCity,pMutation,nPopulation,rr,pi,nRemain,Shock);[newPopulation,R,Rlength,counter2,rr]=select(moffspring,nPopulation,nCity,dCity,Rlength,R,coun ter2,pi,nRemain);counter1=counter1+1;rR(counter1+1)=Rlength;record(counter1+1,:)=R;endR0;Rlength0;R;Rlength;minR=min(rR);disp('最短路经出现代数:')rr=find(rR==minR)disp('最短路经:')record(rr,:);mR=record(rr(1,1),:)disp('终止条件一:')counter1disp('终止条件二:')counter2disp('最短路经长度:')minRdisp('最初路经长度:')rR(1)figure(2)plotaiwa(xyCity,mR,nCity)figure(3)i=1:counter1+1;plot(i,rR(i))grid onfunction[newPopulation,R,Rlength,counter2,rr]=select(Population,nPopulation,nCity,dCity,Rlength,R,coun ter2,pi,nRemain)Distance=zeros(nPopulation,1); %零化路径长度Fitness=zeros(nPopulation,1); %零化适应概率Sum=0; %路径长度for i=1:nPopulation %计算个体路径长度for j=1:nCity-2Distance(i)=Distance(i)+dCity(Population(i,j),Population(i,j+1));end %对路径长度调整,增加起始点到路径首尾点的距离Distance(i)=Distance(i)+dCity(Population(i,1),nCity)+dCity(Population(i,nCity-1),nCity);Sum=Sum+Distance(i); %累计总路径长度end %计算个体路径长度if Rlength==min(Distance)counter2=counter2+1;elsecounter2=0;endRlength=min(Distance); %更新最短路径长度Rlength;rr=find(Distance==Rlength);R=Population(rr(1,1),:); %更新最短路径for i=1:nPopulationFitness(i)=(max(Distance)-Distance(i)+0.001)/(nPopulation*(max(Distance)+0.001)-Sum); %适应概率=个体/总和。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
遗传算法程序(一):说明: fga.m 为遗传算法的主程序; 采用二进制Gray编码,采用基于轮盘赌法的非线性排名选择, 均匀交叉,变异操作,而且还引入了倒位操作!function [BestPop,Trace]=fga(FUN,LB,UB,eranum,popsize,pCross,pMutation,pInversion,options) % [BestPop,Trace]=fmaxga(FUN,LB,UB,eranum,popsize,pcross,pmutation) % Finds a maximum ofa function of several variables.% fmaxga solves problems of the form:% max F(X) subject to: LB <= X <= UB% BestPop - 最优的群体即为最优的染色体群% Trace - 最佳染色体所对应的目标函数值% FUN - 目标函数% LB - 自变量下限% UB - 自变量上限% eranum - 种群的代数,取100--1000(默认200)% popsize - 每一代种群的规模;此可取50--200(默认100)% pcross - 交叉概率,一般取0.5--0.85之间较好(默认0.8)% pmutation - 初始变异概率,一般取0.05-0.2之间较好(默认0.1)% pInversion - 倒位概率,一般取0.05-0.3之间较好(默认0.2)% options - 1*2矩阵,options(1)=0二进制编码(默认0),option(1)~=0十进制编%码,option(2)设定求解精度(默认1e-4)%% ------------------------------------------------------------------------T1=clock;if nargin<3, error('FMAXGA requires at least three input arguments'); endif nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e -4];endif nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];endif nargin==7, pInversion=0.15;options=[0 1e-4];endif find((LB-UB)>0)error('数据输入错误,请重新输入(LB<UB):');ends=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));disp(s);global m n NewPop children1 children2 VarNumbounds=[LB;UB]';bits=[];VarNum=size(bounds,1);precision=options(2);%由求解精度确定二进制编码长度bits=ceil(log2((bounds(:,2)-bounds(:,1))' ./ precision));%由设定精度划分区间[Pop]=InitPopGray(popsize,bits);%初始化种群[m,n]=size(Pop);NewPop=zeros(m,n);children1=zeros(1,n);children2=zeros(1,n);pm0=pMutation;BestPop=zeros(eranum,n);%分配初始解空间BestPop,TraceTrace=zeros(eranum,length(bits)+1);i=1;while i<=eranumfor j=1:mvalue(j)=feval(FUN(1,:),(b2f(Pop(j,:),bounds,bits)));%计算适应度end[MaxValue,Index]=max(value);BestPop(i,:)=Pop(Index,:);Trace(i,1)=MaxValue;Trace(i,(2:length(bits)+1))=b2f(BestPop(i,:),bounds,bits);[selectpop]=NonlinearRankSelect(FUN,Pop,bounds,bits);%非线性排名选择[CrossOverPop]=CrossOver(selectpop,pCross,round(unidrnd(eranum-i)/eranum));%采用多点交叉和均匀交叉,且逐步增大均匀交叉的概率%round(unidrnd(eranum-i)/eranum)[MutationPop]=Mutation(CrossOverPop,pMutation,VarNum);%变异[InversionPop]=Inversion(MutationPop,pInversion);%倒位Pop=InversionPop;%更新pMutation=pm0+(i^4)*(pCross/3-pm0)/(eranum^4);%随着种群向前进化,逐步增大变异率至1/2交叉率p(i)=pMutation;i=i+1;endt=1:eranum;plot(t,Trace(:,1)');title('函数优化的遗传算法');xlabel('进化世代数(eranum)');ylabel('每一代最优适应度(maxfitness)');[MaxFval,I]=max(Trace(:,1));X=Trace(I,(2:length(bits)+1));hold on; plot(I,MaxFval,'*');text(I+5,MaxFval,['FMAX=' num2str(MaxFval)]);str1=sprintf ('进化到 %d 代 ,自变量为 %s 时,得本次求解的最优值 %f\n对应染色体是:%s',I,num2str(X),MaxFval,num2str(BestPop(I,:))); disp(str1);%figure(2);plot(t,p);%绘制变异值增大过程T2=clock;elapsed_time=T2-T1;if elapsed_time(6)<0elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;endif elapsed_time(5)<0elapsed_time(5)=elapsed_time(5)+60;elapsed_time(4)=elapsed_time(4)-1;end %像这种程序当然不考虑运行上小时啦str2=sprintf('程序运行耗时 %d 小时 %d 分钟 %.4f 秒',elapsed_time(4),elapsed_time(5),elapsed_time(6));disp(str2);%初始化种群%采用二进制Gray编码,其目的是为了克服二进制编码的Hamming悬崖缺点 function [initpop]=InitPopGray(popsize,bits)len=sum(bits);initpop=zeros(popsize,len);%The whole zero encoding individualfor i=2:popsize-1pop=round(rand(1,len));pop=mod(([0 pop]+[pop 0]),2);%i=1时,b(1)=a(1);i>1时,b(i)=mod(a(i-1)+a(i),2)%其中原二进制串:a(1)a(2)...a(n),Gray串:b(1)b(2)...b(n)initpop(i,:)=pop(1:end-1);endinitpop(popsize,:)=ones(1,len);%The whole one encoding individual%解码function [fval] = b2f(bval,bounds,bits)% fval - 表征各变量的十进制数% bval - 表征各变量的二进制编码串% bounds - 各变量的取值范围% bits - 各变量的二进制编码长度scale=(bounds(:,2)-bounds(:,1))'./(2.^bits-1); %The range of the variables numV=size(bounds,1);cs=[0 cumsum(bits)];for i=1:numVa=bval((cs(i)+1):cs(i+1));fval(i)=sum(2.^(size(a,2)-1:-1:0).*a)*scale(i)+bounds(i,1);end%选择操作%采用基于轮盘赌法的非线性排名选择%各个体成员按适应值从大到小分配选择概率:%P(i)=(q/1-(1-q)^n)*(1-q)^i, 其中 P(0)>P(1)>...>P(n), sum(P(i))=1function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)global m nselectpop=zeros(m,n);fit=zeros(m,1);for i=1:mfit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据endselectprob=fit/sum(fit);%计算各个体相对适应度(0,1)q=max(selectprob);%选择最优的概率x=zeros(m,2);x(:,1)=[m:-1:1]';[y x(:,2)]=sort(selectprob);r=q/(1-(1-q)^m);%标准分布基值newfit(x(:,2))=r*(1-q).^(x(:,1)-1);%生成选择概率newfit=cumsum(newfit);%计算各选择概率之和rNums=sort(rand(m,1));fitIn=1;newIn=1;while newIn<=mif rNums(newIn)<newfit(fitIn)selectpop(newIn,:)=pop(fitIn,:);newIn=newIn+1;elsefitIn=fitIn+1;endend%交叉操作function [NewPop]=CrossOver(OldPop,pCross,opts)%OldPop为父代种群,pcross为交叉概率global m n NewPopr=rand(1,m);y1=find(r<pCross);y2=find(r>=pCross);len=length(y1);if len>2&mod(len,2)==1%如果用来进行交叉的染色体的条数为奇数,将其调整为偶数 y2(length(y2)+1)=y1(len);endif length(y1)>=2for i=0:2:length(y1)-2if opts==0[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=EqualCrossOver(OldPop(y1(i+1),:),OldPop(y1(i+2),:)) ;else[NewPop(y1(i+1),:),NewPop(y1(i+2),:)]=MultiPointCross(OldPop(y1(i+1),:),OldPop(y1(i+2),:) );endendendNewPop(y2,:)=OldPop(y2,:);%采用均匀交叉function [children1,children2]=EqualCrossOver(parent1,parent2)global n children1 children2hidecode=round(rand(1,n));%随机生成掩码crossposition=find(hidecode==1);holdposition=find(hidecode==0);children1(crossposition)=parent1(crossposition);%掩码为1,父1为子1提供基因children1(holdposition)=parent2(holdposition);%掩码为0,父2为子1提供基因children2(crossposition)=parent2(crossposition);%掩码为1,父2为子2提供基因children2(holdposition)=parent1(holdposition);%掩码为0,父1为子2提供基因%采用多点交叉,交叉点数由变量数决定function [Children1,Children2]=MultiPointCross(Parent1,Parent2)global n Children1 Children2 VarNumChildren1=Parent1;Children2=Parent2;Points=sort(unidrnd(n,1,2*VarNum));for i=1:VarNumChildren1(Points(2*i-1):Points(2*i))=Parent2(Points(2*i-1):Points(2*i));Children2(Points(2*i-1):Points(2*i))=Parent1(Points(2*i-1):Points(2*i));end%变异操作function [NewPop]=Mutation(OldPop,pMutation,VarNum)global m n NewPopposition=find(r<=pMutation);len=length(position);if len>=1for i=1:lenk=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点 for j=1:length(k)if OldPop(position(i),k(j))==1OldPop(position(i),k(j))=0;elseOldPop(position(i),k(j))=1;EndendendendNewPop=OldPop;%倒位操作function [NewPop]=Inversion(OldPop,pInversion)global m n NewPopNewPop=OldPop;r=rand(1,m);PopIn=find(r<=pInversion);len=length(PopIn);if len>=1for i=1:lend=sort(unidrnd(n,1,2));if d(1)~=1&d(2)~=nNewPop(PopIn(i),1:d(1)-1)=OldPop(PopIn(i),1:d(1)-1);NewPop(PopIn(i),d(1):d(2))=OldPop(PopIn(i),d(2):-1:d(1)); NewPop(PopIn(i),d(2)+1:n)=OldPop(PopIn(i),d(2)+1:n);Endendend遗传算法程序(二):function youhuafunD=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);while generation<=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=rnd tmp=A(ind);A(ind)=B(ind);B(ind)=tmp;% % 两点交叉% 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;% 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);for k=3:Ntmprnd=rand;tmpind=tmprnd difind=[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=11*300-maxV;plot(minV,'*');title('各代的目标函数值');F4=D(:,4);FF4=F4-fatherrand(:,1);FF4=max(FF4,1);D(:,5)=FF4;save DData Dfunction D=codeload youhua.mat% properties F2 and F3F1=A(:,1);F2=A(:,2);F3=A(:,3);if (max(F2)>1450)||(min(F2)<=900)error('DATA property F2 exceed it''s range (900,1450]') end% get group property F1 of data, according to F2 value F4=zeros(size(F1));for ite=11:-1:1index=find(F2<=900+ite*50);F4(index)=ite;endD=[F1,F2,F3,F4];function ScoreN=scorefun(fatherrand,D)F3=D(:,3);F4=D(:,4);N=size(fatherrand,2);FF4=F4*ones(1,N);FF4rnd=FF4-fatherrand;FF4rnd=max(FF4rnd,1);ScoreN=ones(1,N)*300*11;% 这里有待优化for k=1:NFF4k=FF4rnd(:,k);for ite=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;遗传算法程序(三):%IAGAfunction best=gaclearMAX_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_genfitness=fit(popus,RANGE); %求适应度f=fitness.f;picked=choose(popus,fitness); %选择popus=intercross(popus,picked); %杂交popus=aberrance(popus,picked); %变异if max(f)>best.max_fadvance_k=advance_k+1;x_better(advance_k)=fitness.x;best.max_f=max(f);best.popus=popus;best.x=fitness.x;endif mod(advance_k,SPEEDUP_INTER)==0RANGE=minmax(x_better);RANGEadvance=0;endendreturn;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:Mx=0;for n=1:Nx=x+popus(m,n)*(2^(n-1));endx=x*((B-A)/(2^N))+A;for k=1:5f(m,1)=f(m,1)-(k*sin((k+1)*x+k));endendf_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:Mx=find(f==f_t(k));%降序排列的个体序号d_order(k)=x(1);endfor m=1:Mpopus_t(m,:)=popus(d_order(m),:);endpopus=popus_t;f=f_t;p=f_std./sum(f_std); %选择概率c_p=cumsum(p)'; %累积概率for cn=1:choose_Npicked(cn,1)=roulette(c_p); %轮盘赌picked(cn,2)=roulette(c_p); %轮盘赌popus=intercross(popus,picked(cn,:));%杂交endpopus=aberrance(popus,picked);%变异return;function popus=intercross(popus,picked) %杂交[M_p,N_p]=size(picked);[M,N]=size(popus);for cn=1:M_pp(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;endreturn;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_pif U(2)>=P_a %如果大于变异概率,就不变异continue;endif U(1)>=0.5a=picked(kp,1);elsea=picked(kp,2);endp(1)=ceil(rand*N);%生成变异位置p(2)=ceil(rand*N);if popus(a,p(1))==1%0 1变换popus(a,p(1))=0;elsepopus(a,p(1))=1;endif popus(a,p(2))==1popus(a,p(2))=0;elsepopus(a,p(2))=1;endendreturn;function picked=roulette(c_p) %轮盘赌[M,N]=size(c_p);M=max([M N]);U=rand; if U<c_p(1)picked=1;return;endfor m=1:(M-1)if U>c_p(m) & U<c_p(m+1)picked=m+1;break;endend全方位的两点杂交、两点变异的改进的加速遗传算法(IAGA)遗传算法优化pid参数matlab程序chap5_4m%GA(Generic Algorithm) program to optimize Parameters of PID clear all;clear all;global rin yout timefG=100;Size=30;CodeL=10;MinX(1)=zeros(1);MaxX(1)=20*ones(1);MinX(2)=zeros(1);MaxX(2)=1.0*ones(1);MinX(3)=zeros(1);MaxX(3)=1.0*ones(1);E=round(rand(Size,3*CodeL));%Initian Code!BsJ=0;for kg=1:1:Gtime(kg)=kg;for s=1:1:Sizem=E(s,:);y1=0;y2=0;y3=0;m1=m(1:1:CodeL);for i=1:1:CodeLy1=y1+m1(i)*2^(i-1);endKpid(s,1)=(MaxX(1)-MinX(1))*y1/1023+MinX(1);m2=m(CodeL+1:1:2*CodeL);for i=1:1:CodeLy2=y2+m2(i)*2^(i-1);endKpid(s,2)=(MaxX(2)-MinX(2))*y2/1023+MinX(2);m3=m(2*CodeL+1:1:3*CodeL);for i=1:1:CodeLy3=y3+m3(i)*2^(i-1);endKpid(s,3)=(MaxX(3)-MinX(3))*y3/1023+MinX(3);%*******Step 1:Evaluate Best J*******Kpidi=Kpid(s,:);[Kpidi,BsJ]=chap5_3f(Kpidi,BsJ);BsJi(s)=BsJ;end[OderJi,IndexJi]=sort(BsJi);BestJ(kg)=OderJi(1);BJ=BestJ(kg);Ji=BsJi+1e-10;fi=1./Ji;%Cm=max(Ji);%fi=Cm-Ji; %Avoiding deviding zero[Oderfi,Indexfi]=sort(fi);%Arranging fi small to bigger%Bestfi=Oderfi(Size); %Let Bestfi=max(fi)%BestS=Kpid(Indexfi(Size),:); %Let BestS=E(m),m is the Indexfi belong to %max(fi)Bestfi=Oderfi(Size);%Let Bestfi=max(fi)BestS=E(Indexfi(Size),:);%Let BestS=E(m),m is the Indexfi belong to max(fi)kgBJBestS;%****Step 2:Select and Reproduct Operation***fi_sum=sum(fi);fi_Size=(Oderfi/fi_sum)*Size;fi_S=floor(fi_Size); %Selecting Bigger fi valuekk=1;for i=1:1:Sizefor j=1:1:fi_S(i) %Select and ReproduceTempE(kk,:)=E(Indexfi(i),:);kk=kk+1; %kk is used to reproduceendend%**********Step 3:Crossover Operation******pc=0.06;n=ceil(20*rand);for i=1:2:(Size-1)temp=rand;if pc>tempfor j=n:1:20TempE(i,j)=E(i+1,j);TempE(i+1,j)=E(i,j);endendendTempE(Size,:)=BestS;E=TempE;%***************Step 4: Mutation Operation************** %pm=0.001;pm=0.001-[1:1:Size]*(0.001)/Size;%Bigger fi,smaller pm%pm=0.0; %No mutation%pm=0.1; %Big mutationfor i=1:1:Sizefor j=1:1:3*CodeLtemp=rand;if pm>temp %Mutation Conditionif TempE(i,j)==0TempE(i,j)=1;elseTempE(i,j)=0;Endendendend%Guarantee TempE(Size,:)belong to the best individualTempE(Size,:)=BestS;E=TempE;%*************************************************** endBestfiBestSKpidiBest_J=BestJ(G)figure(1);plot(time,BestJ);xlabel('Time');ylabel('Best J');figure(2);plot(timef,rin,'r',timef,yout,'b');xlabel('Time(s)');ylabel('ran,yout');chap5_3f.mfunction [Kpidi,BsJ]=pid_gaf(Kpidi,BsJ)global rin yout timefts=0.001;sys=tf(400,[1,50,0]);dsys=c2d(sys,ts,'z');[num,den]=tfdata(dsys,'v');rin=1.0;u_1=0.0;u_2=0.0;y_1=0.0;y_2=0.0;x=[0,0,0]'; B=0;error_1=0;tu=1;s=0;P=100;for k=1:1:Ptimef(k)=k*ts;r(k)=rin;u(k)=Kpidi(1)*x(1)+Kpidi(2)*x(2)+Kpidi(3)*x(3);if u(k)>=10u(k)=10;endif u(k)<=-10u(k)=-10;endyout(k)=-den(2)*y_1-den(3)*y_2+num(2)*u_1+num(3)*u_2; error(k)=r(k)-yout(k);%-------------------Return of PID parameters----------------u_2=u_1;u_1=u(k);y_2=y_1;y_1=yout(k);x(1)=error(k); % Calculating Px(2)=(error(k)-error_1)/ts; % Dx(3)=x(3)+error(k)*ts; % Ierror_2=error_1;error_1=error(k);if s==0if yout(k)>0.95&yout(k)<1.05tu=timef(k);s=1;endendendfor i=1:1:PJi(i)=0.999*abs(error(i))+0.01*u(i)^2*0.1; B=B+Ji(i);f i>1erry(i)=yout(i)-yout(i-1);if erry(i)<0B=B+100*abs(erry(i));EndEndendBsj=B+0.2*tu*10。