遗传算法matlab代码
① 运行遗基于遗传算法的BP神经网络MATLAB代码程序时总是出错!!!
这个问题也困扰了我好久,终于解决了。给你个ga.m程序,新建m文件复制进去,再运行程序试试。
%ga.m
function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,...
termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)
% GA run a genetic algorithm
% function [x,endPop,bPop,traceInfo]=ga(bounds,evalFN,evalOps,startPop,opts,
% termFN,termOps,selectFN,selectOps,
% xOverFNs,xOverOps,mutFNs,mutOps)
%
% Output Arguments:
% x - the best solution found ring the course of the run
% endPop - the final population
% bPop - a trace of the best population
% traceInfo - a matrix of best and means of the ga for each generation
%
% Input Arguments:
% bounds - a matrix of upper and lower bounds on the variables
% evalFN - the name of the evaluation .m function
% evalOps - options to pass to the evaluation function ([NULL])
% startPop - a matrix of solutions that can be initialized
% from initialize.m
% opts - [epsilon prob_ops display] change required to consider two
% solutions different, prob_ops 0 if you want to apply the
% genetic operators probabilisticly to each solution, 1 if
% you are supplying a deterministic number of operator
% applications and display is 1 to output progress 0 for
% quiet. ([1e-6 1 0])
% termFN - name of the .m termination function (['maxGenTerm'])
% termOps - options string to be passed to the termination function
% ([100]).
% selectFN - name of the .m selection function (['normGeomSelect'])
% selectOpts - options string to be passed to select after
% select(pop,#,opts) ([0.08])
% xOverFNS - a string containing blank seperated names of Xover.m
% files (['arithXover heuristicXover simpleXover'])
% xOverOps - A matrix of options to pass to Xover.m files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([2 0;2 3;2 0])
% mutFNs - a string containing blank seperated names of mutation.m
% files (['boundaryMutation multiNonUnifMutation ...
% nonUnifMutation unifMutation'])
% mutOps - A matrix of options to pass to Xover.m files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([4 0 0;6 100 3;4 100 3;4 0 0])
% Binary and Real-Valued Simulation Evolution for Matlab
% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay
%
% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function
% optimization: A Matlab implementation. ACM Transactions on Mathmatical
% Software, Submitted 1996.
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 1, or (at your option)
% any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details. A of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
%%$Log: ga.m,v $
%Revision 1.10 1996/02/02 15:03:00 jjoine
% Fixed the ordering of imput arguments in the comments to match
% the actual order in the ga function.
%
%Revision 1.9 1995/08/28 20:01:07 chouck
% Updated initialization parameters, updated mutation parameters to reflect
% b being the third option to the nonuniform mutations
%
%Revision 1.8 1995/08/10 12:59:49 jjoine
%Started Logfile to keep track of revisions
%
n=nargin;
if n<2 | n==6 | n==10 | n==12
disp('Insufficient arguements')
end
if n<3 %Default evalation opts.
evalOps=[];
end
if n<5
opts = [1e-6 1 0];
end
if isempty(opts)
opts = [1e-6 1 0];
end
if any(evalFN<48) %Not using a .m file
if opts(2)==1 %Float ga
e1str=['x=c1; c1(xZomeLength)=', evalFN ';'];
e2str=['x=c2; c2(xZomeLength)=', evalFN ';'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',...
evalFN ';'];
end
else %Are using a .m file
if opts(2)==1 %Float ga
e1str=['[c1 c1(xZomeLength)]=' evalFN '(c1,[gen evalOps]);'];
e2str=['[c2 c2(xZomeLength)]=' evalFN '(c2,[gen evalOps]);'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' evalFN ...
'(x,[gen evalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];
end
end
if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<12 %Default muatation information
if opts(2)==1 %Float GA
mutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'];
mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];
else %Binary GA
mutFNs=['binaryMutation'];
mutOps=[0.05];
end
end
if n<10 %Default crossover information
if opts(2)==1 %Float GA
xOverFNs=['arithXover heuristicXover simpleXover'];
xOverOps=[2 0;2 3;2 0];
else %Binary GA
xOverFNs=['simpleXover'];
xOverOps=[0.6];
end
end
if n<9 %Default select opts only i.e. roullete wheel.
selectOps=[];
end
if n<8 %Default select info
selectFN=['normGeomSelect'];
selectOps=[0.08];
end
if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<4 %No starting population passed given
startPop=[];
end
if isempty(startPop) %Generate a population at random
%startPop=zeros(80,size(bounds,1)+1);
startPop=initializega(80,bounds,evalFN,evalOps,opts(1:2));
end
if opts(2)==0 %binary
bits=calcbits(bounds,opts(1));
end
xOverFNs=parse(xOverFNs);
mutFNs=parse(mutFNs);
xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness
numVar = xZomeLength-1; %Number of variables
popSize = size(startPop,1); %Number of indivials in the pop
endPop = zeros(popSize,xZomeLength); %A secondary population matrix
c1 = zeros(1,xZomeLength); %An indivial
c2 = zeros(1,xZomeLength); %An indivial
numXOvers = size(xOverFNs,1); %Number of Crossover operators
numMuts = size(mutFNs,1); %Number of Mutation operators
epsilon = opts(1); %Threshold for two fittness to differ
oval = max(startPop(:,xZomeLength)); %Best value in start pop
bFoundIn = 1; %Number of times best has changed
done = 0; %Done with simulated evolution
gen = 1; %Current Generation Number
collectTrace = (nargout>3); %Should we collect info every gen
floatGA = opts(2)==1; %Probabilistic application of ops
display = opts(3); %Display progress
while(~done)
%Elitist Model
[bval,bindx] = max(startPop(:,xZomeLength)); %Best of current pop
best = startPop(bindx,:);
if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
traceInfo(gen,4)=std(startPop(:,xZomeLength));
end
if ( (abs(bval - oval)>epsilon) | (gen==1)) %If we have a new best sol
if display
fprintf(1,'\n%d %f\n',gen,bval); %Update the display
end
if floatGA
bPop(bFoundIn,:)=[gen startPop(bindx,:)]; %Update bPop Matrix
else
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
startPop(bindx,xZomeLength)];
end
bFoundIn=bFoundIn+1; %Update number of changes
oval=bval; %Update the best val
else
if display
fprintf(1,'%d ',gen); %Otherwise just update num gen
end
end
endPop = feval(selectFN,startPop,[gen selectOps]); %Select
if floatGA %Running with the model where the parameters are numbers of ops
for i=1:numXOvers,
for j=1:xOverOps(i,1),
a = round(rand*(popSize-1)+1); %Pick a parent
b = round(rand*(popSize-1)+1); %Pick another parent
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
[c1 c2] = feval(xN,endPop(a,:),endPop(b,:),bounds,[gen xOverOps(i,:)]);
if c1(1:numVar)==endPop(a,(1:numVar)) %Make sure we created a new
c1(xZomeLength)=endPop(a,xZomeLength); %solution before evaluating
elseif c1(1:numVar)==endPop(b,(1:numVar))
c1(xZomeLength)=endPop(b,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
if 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);
else
%[c2(xZomeLength) c2] = feval(evalFN,c2,[gen evalOps]);
eval(e2str);
end
endPop(a,:)=c1;
endPop(b,:)=c2;
end
end
for i=1:numMuts,
for j=1:mutOps(i,1),
a = round(rand*(popSize-1)+1);
c1 = feval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);
if c1(1:numVar)==endPop(a,(1:numVar))
c1(xZomeLength)=endPop(a,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
endPop(a,:)=c1;
end
end
else %We are running a probabilistic model of genetic operators
for i=1:numXOvers,
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
cp=find(rand(popSize,1)<xOverOps(i,1)==1);
if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); end
cp=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,:)] = feval(xN,endPop(a,:),endPop(b,:),...
bounds,[gen xOverOps(i,:)]);
end
end
for i=1:numMuts
mN=deblank(mutFNs(i,:));
for j=1:popSize
endPop(j,:) = feval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);
eval(e1str);
end
end
end
gen=gen+1;
done=feval(termFN,[gen termOps],bPop,endPop); %See if the ga is done
startPop=endPop; %Swap the populations
[bval,bindx] = min(startPop(:,xZomeLength)); %Keep the best solution
startPop(bindx,:) = best; %replace it with the worst
end
[bval,bindx] = max(startPop(:,xZomeLength));
if display
fprintf(1,'\n%d %f\n',gen,bval);
end
x=startPop(bindx,:);
if opts(2)==0 %binary
x=b2f(x,bounds,bits);
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)...
startPop(bindx,xZomeLength)];
else
bPop(bFoundIn,:)=[gen startPop(bindx,:)];
end
if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
end
② MATLAB遗传算法
function ret=Code(lenchrom,bound)
%本函数将变量编码成染色体,用于随机初始化一个种群
% lenchrom input : 染色体长度
% bound input : 变量的取值范围
% ret output: 染色体的编码值
flag=0;
while flag==0
pick=rand(1,length(lenchrom));
ret=bound(:,1)'+(bound(:,2)-bound(:,1))'.*pick; %线性插值
flag=test(lenchrom,bound,ret); %检验染色体的可行性
end
function ret=Cross(pcross,lenchrom,chrom,sizepop,bound)
%本函数完成交叉操作
% pcorss input : 交叉概率
% lenchrom input : 染色体的长度
% chrom input : 染色体群
% sizepop input : 种群规模
% ret output : 交叉后的染色体
for i=1:sizepop
% 随机选择两个染色体进行交叉
pick=rand(1,2);
while prod(pick)==0
pick=rand(1,2);
end
index=ceil(pick.*sizepop);
% 交叉概率决定是否进行交叉
pick=rand;
while pick==0
pick=rand;
end
if pick>pcross
continue;
end
flag=0;
while flag==0
% 随机选择交叉位置
pick=rand;
while pick==0
pick=rand;
end
pos=ceil(pick.*sum(lenchrom)); %随机选择进行交叉的位置,即选择第几个变量进行交叉,注意:两个染色体交叉的位置相同
pick=rand; %交叉开始
v1=chrom(index(1),pos);
v2=chrom(index(2),pos);
chrom(index(1),pos)=pick*v2+(1-pick)*v1;
chrom(index(2),pos)=pick*v1+(1-pick)*v2; %交叉结束
flag1=test(lenchrom,bound,chrom(index(1),:)); %检验染色体1的可行性
flag2=test(lenchrom,bound,chrom(index(2),:)); %检验染色体2的可行性
if flag1*flag2==0
flag=0;
else flag=1;
end %如果两个染色体不是都可行,则重新交叉
end
end
ret=chrom;
clc
clear all
% warning off
%% 遗传算法参数
maxgen=50; %进化代数
sizepop=100; %种群规模
pcross=[0.6]; %交叉概率
pmutation=[0.1]; %变异概率
lenchrom=[1 1]; %变量字串长度
bound=[-5 5;-5 5]; %变量范围
%% 个体初始化
indivials=struct('fitness',zeros(1,sizepop), 'chrom',[]); %种群结构体
avgfitness=[]; %种群平均适应度
bestfitness=[]; %种群最佳适应度
bestchrom=[]; %适应度最好染色体
% 初始化种群
for i=1:sizepop
indivials.chrom(i,:)=Code(lenchrom,bound); %随机产生个体
x=indivials.chrom(i,:);
indivials.fitness(i)= (x(1)*exp(-(x(1)^2 + x(2)^2)));
%-20*exp(-0.2*sqrt((x(1)^2+x(2)^2)/2))-exp((cos(2*pi*x(1))+cos(2*pi*x(2)))/2)+20+2.71289
% 这个是我的测试函数
% 如果有这个函数的话,可以得到最优值
end
%找最好的染色体
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色体
avgfitness=sum(indivials.fitness)/sizepop; %染色体的平均适应度
% 记录每一代进化中最好的适应度和平均适应度
trace=[];
%% 进化开始
for i=1:maxgen
% 选择操作
indivials=Select(indivials,sizepop);
avgfitness=sum(indivials.fitness)/sizepop;
% 交叉操作
indivials.chrom=Cross(pcross,lenchrom,indivials.chrom,sizepop,bound);
% 变异操作
indivials.chrom=Mutation(pmutation,lenchrom,indivials.chrom,sizepop,[i maxgen],bound);
% 计算适应度
for j=1:sizepop
x=indivials.chrom(j,:);
indivials.fitness(j)=(x(1)*exp(-(x(1)^2 + x(2)^2)));
%-20*exp(-0.2*sqrt((x(1)^2+x(2)^2)/2))-exp((cos(2*pi*x(1))+cos(2*pi*x(2)))/2)+20+2.71289
% -20*exp(-0.2*sqrt((x(1)^2+x(2)^2)/2))-exp((cos(2*pi*x(1))+cos(2*pi*x(2)))/2)+20+2.71289;
end
%找到最小和最大适应度的染色体及它们在种群中的位置
[newbestfitness,newbestindex]=min(indivials.fitness);
[worestfitness,worestindex]=max(indivials.fitness);
% 代替上一次进化中最好的染色体
if bestfitness>newbestfitness
bestfitness=newbestfitness;
bestchrom=indivials.chrom(newbestindex,:);
end
indivials.chrom(worestindex,:)=bestchrom;
indivials.fitness(worestindex)=bestfitness;
avgfitness=sum(indivials.fitness)/sizepop;
trace=[trace;avgfitness bestfitness]; %记录每一代进化中最好的适应度和平均适应度
end
%进化结束
%% 结果显示
[r c]=size(trace);
figure
plot([1:r]',trace(:,1),'r-',[1:r]',trace(:,2),'b--');
title(['函数值曲线 ' '终止代数=' num2str(maxgen)],'fontsize',12);
xlabel('进化代数','fontsize',12);ylabel('函数值','fontsize',12);
legend('各代平均值','各代最佳值','fontsize',12);
ylim([-0.5 5])
disp('函数值 变量');
% 窗口显示
disp([bestfitness x]);
③ 求遗传算法的matlab程序
function
my_ga()
options=gaoptimset;
%设置变量范围
options=gaoptimset(options,'PopInitRange',[0;9]);
%设置种群大小
options=gaoptimset(options,'PopulationSize',100);
%设置迭代次数
options=gaoptimset(options,'Generations',100);
%选择选择函数
options=gaoptimset(options,'SelectionFcn',@selectionroulette);
%选择交叉函数
options=gaoptimset(options,'CrossoverFcn',@crossoverarithmetic);
%选择变异函数
options=gaoptimset(options,'MutationFcn',@mutationuniform);
%设置绘图:解的变化、种群平均值的变化
options=gaoptimset(options,'PlotFcns',{@gaplotbestf});
%执行遗传算法,fitness.m是函数文件
[x,fval]=ga(@fitness,1,options)
④ 遗传算法求解超越方程,matlab程序,tanx=1/x, x∈[0,60],需要程序代码
主程序代码如下饥姿。主文件其它代码及调用的其它函数详见私信压缩包。
for n=0:19;
x=linspace(0,60);
y1=tan(x);
y2=1./x;
figure(1);
plot(x,y1,'r',x,y2,'b')
title('函数曲线图')
xlabel('x')
ylabel('y')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%主程序%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
global BitLength %全局变量,计算如果满足求解精度至少需要编码的长度
global boundsbegin %全局变量,自变量的起始点
global boundsend %全局变量,自变量的终止点
bounds=[pi/2*2*n pi/2*(2*n+1)]; %一维自变量的取值范围棚猛
precision=0.0001; %运算精度
boundsbegin=bounds(:,1);
boundsend=bounds(:,2); %计算如果满足求解精度至少需要多长的染色体
BitLength=ceil(log2((boundsend-boundsbegin)' ./ precision));
popsize=60; %初始种群大小
Generationnmax=50; %最大代数
pcrossover=0.9999; %交配概率
pmutation=0.0001; %变异概率
population=round(rand(popsize,BitLength)); %初始种群,行代表一个个体,列代表不同个体
%计算适应度
[Fitvalue,cumsump]=fitnessfun(population); %输入群体population,返回适应度Fitvalue和累积概率cumsump
Generation=1;
while Generation<(Generationnmax+1)
for j=1:2:popsize %1对1对的群体进行如下操作(交叉,变异)
%选择
seln=selection(population,cumsump);
%交叉
scro=crossover(population,seln,pcrossover);
scnew(j,:)=scro(1,:);
scnew(j+1,:)=scro(2,:);
%变异
smnew(j,:)=mutation(scnew(j,:),pmutation);
smnew(j+1,:)=mutation(scnew(j+1,:),pmutation);
end
%产生了新的种群
population=smnew;
%计算新种群的适应度
[Fitvalue,cumsump]=fitnessfun(population); %记录当前代最好的适应度和平均适应度
[fmax,nmax]=max(Fitvalue); %最好的适应度为fmax(即函数值最大),其对应的个体为nmax
fmean=mean(Fitvalue); %平均适应度为fmean
ymax(Generation)=fmax; %每代中最好的适应度
ymean(Generation)=fmean; %每代中的平均链肢桥适应度
%记录当前代的最佳染色体个体
x=transform2to10(population(nmax,:));%population(nmax,:)为最佳染色体个体
xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)-1);
xmax(Generation)=xx;
Generation=Generation+1;
end
Generation=Generation-1;%Generation加1、减1的操作是为了能记录各代中的最佳函数值xmax(Generation)
targetfunvalue=targetfun(xmax);
[Besttargetfunvalue,nmax]=max(targetfunvalue);
Bestpopulation=xmax(nmax)
%绘制经过遗传运算后的适应度曲线
figure(2);
hand1=plot(1:Generation,ymax);
set(hand1,'linestyle','-','linewidth',1,'marker','*','markersize',8)
hold on;
hand2=plot(1:Generation,ymean);
set(hand2,'color','k','linestyle','-','linewidth',1, 'marker','h','markersize',8)
xlabel('进化代数');
ylabel('最大和平均适应度');
xlim([1 Generationnmax]);
legend('最大适应度','平均适应度');
box off;
hold off;
end
%%%%%%%%%%%计算适应度函数%%%%%%%%%%%%%%%%%%%%%%%%
[Fitvalue,cumsump]=fitnessfun(population);
global BitLength
global boundsbegin
global boundsend
popsize=size(population,1); %计算个体个数
for i=1:popsize
x=transform2to10(population(i,:)); %将二进制转换为十进制
%转化为[-2,2]区间的实数
xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)-1);
Fitvalue(i)=targetfun(xx); %计算函数值,即适应度
end
%给适应度函数加上一个大小合理的数以便保证种群适应值为正数
Fitvalue=Fitvalue'+230; %该处还有一个作用就是决定适应度是有利于选取几个有利个体(加强竞争),海深减弱竞争
%计算选择概率
fsum=sum(Fitvalue) ;
Pperpopulation=Fitvalue/fsum ; %适应度归一化,及被复制的概率
%计算累积概率
cumsump(1)=Pperpopulation(1) ;
for i=2:popsize
cumsump(i)=cumsump(i-1)+Pperpopulation(i); %求累计概率
end
cumsump=cumsump' ; %累计概率
⑤ matlab遗传算法代码检查错误
发现的几处错误:
1、适应蠢碰度函数里面if a[i]=4改为if a(i)==4,类似的还有if b[i]=4。不需要多解释了吧?一个是数组注意和C语言风格区别,另一个是判断相等的符号问题。
2、适应度函数应返回列向量,在fit函数最后加一句:fitness=fitness(:);
3、选择的结果是种群规模减小,不能使用固定的出示规模20,应把适应度函数里面两处循环for i=1:20改为for i=1:size(x,1)。
4、主函数里面rein应为reins。
代码写到一个M文件中:
functionzd
%%初始化遗传算法参数
%初始化参数
NIND=20;
MAXGEN=100;
NVAR=8;
PRECI=1;
GGAP=0.9;%进化代数,即迭代次数
%种群规模
%%初始化种群计算适应度值
%初始化种群
FieldD=[rep(PRECI,[1,NVAR]);rep([0;1],[1,NVAR]);rep([1;0;1;1],[1,NVAR])];
Chrom=crtbp(NIND,NVAR*PRECI);
ObjV=fit(bs2rv(Chrom,FieldD));
gen=0;
whilegen<MAXGEN
FitnV=ranking(ObjV);
衡弊SelCh=select('sus',Chrom,FitnV,GGAP);
SelCh=recombin('xovsp',SelCh,0.7);
SelCh=mut(SelCh,0.07);
ObjVSel=fit(bs2rv(SelCh,FieldD));
[ChromObjV]=reins(Chrom,SelCh,1,1,ObjV,ObjVSel);
咐档族gen=gen+1
%找最好的染色体
trace(gen,1)=min(ObjV);
trace(gen,2)=sum(ObjV)/length(ObjV);
end
plot(trace(:,1));holdon;
plot(trace(:,2));grid;
legend('average','bestfitness');
function[fitness]=fit(x)
fori=1:size(x,1)
i
%随机产生一个种群
if(x(i,6)*x(i,7)-x(i,8)*x(i,6))*(x(i,3)*x(i,2)-x(i,4)*x(i,1))==0
x(i,:)=unidrnd(2,1,8)-1;
end%染色体的适应度
end
a=x(:,1)+x(:,2)+x(:,3)+x(:,4);
b=x(:,5)+x(:,6)+x(:,7)+x(:,8);
fori=1:size(x,1)
i
ifa(i)==4
c=1;
else
c=0;
end
ifb(i)==4
d=1;
else
d=0;
end
fitness(i)=c+d;
end
fitness=fitness(:);
⑥ 在matlab中如何用遗传算法求极值
matlab有遗传算法工具箱。
核心函数:
(1)function [pop]=initializega(num,bounds,eevalFN,eevalOps,options)--初始种群的生成函数
【输出参数】
pop--生成的初始种群
【输入参数】
num--种群中的个体数目
bounds--代表变量的上下界的矩阵
eevalFN--适应度函数
eevalOps--传递给适应度函数的参数
options--选择编码形式(浮点编码或是二进制编码)[precision F_or_B],如
precision--变量进行二进制编码时指定的精度
F_or_B--为1时选择浮点编码,否则为二进制编码,由precision指定精度)
(2)function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,...
termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)--遗传算法函数
【输出参数】
x--求得的最优解
endPop--最终得到的种群
bPop--最优种群的一个搜索轨迹
【输入参数】
bounds--代表变量上下界的矩阵
evalFN--适应度函数
evalOps--传递给适应度函数的参数
startPop-初始种群
opts[epsilon prob_ops display]--opts(1:2)等同于initializega的options参数,第三个参数控制是否输出,一般为0。如[1e-6 1 0]
termFN--终止函数的名称,如['maxGenTerm']
termOps--传递个终止函数的参数,如[100]
selectFN--选择函数的名称,如['normGeomSelect']
selectOps--传递个选择函数的参数,如[0.08]
xOverFNs--交叉函数名称表,以空格分开,如['arithXover heuristicXover simpleXover']
xOverOps--传递给交叉函数的参数表,如[2 0;2 3;2 0]
mutFNs--变异函数表,如['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation']
mutOps--传递给交叉函数的参数表,如[4 0 0;6 100 3;4 100 3;4 0 0]
注意】matlab工具箱函数必须放在工作目录下
【问题】求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是传递给变异函数的参数。
⑦ 急求matlab车辆调度遗传算法代码,需求车辆行驶最优路径。
function [path,lmin]=ga(data,d) %data为点集,d为距离矩阵,即赋权图
tic
%======================
sj0=data;%开环最短路线
%=================================
% sj0=[data;data(1,:)]; %闭环最短路线
%=========================
x=sj0(:,1);y=sj0(:,2);
N=length(x);
%=========================
% d(N,:)=d(1,:);%闭环最短路线
% d(:,N)=d(:,1);%距离矩阵d
%======================
L=N; %sj0的长度
w=800;dai=1000;
%通过改良圈算法选取优良父代A
for k=1:w
c=randperm(L-2);
c1=[1,c+1,L];
flag=1;
while flag>0
flag=0;
for m=1:L-3
for n=m+2:L-1
if d(c1(m),c1(n))+d(c1(m+1),c1(n+1))<d(c1(m),c1(m+1))+d(c1(n),c1(n+1))
flag=1;
c1(m+1:n)=c1(n:-1:m+1);
<a href="https://www..com/s?wd=end&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">end</a>
<a href="https://www..com/s?wd=end&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">end</a>
<a href="https://www..com/s?wd=end&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">end</a>
end
J(k,c1)=1:L;
end
J=J/L;
J(:,1)=0;J(:,L)=1;
rand('state',sum(clock));
%遗传算法实现过程
A=J;
for k=1:dai %产生0~1 间随机数列进行编码
B=A;
c=randperm(w);
%交配产生子代B
for i=1:2:w
F=2+floor(100*rand(1));
temp=B(c(i),F:L);
B(c(i),F:L)=B(c(i+1),F:L);
B(c(i+1),F:L)=temp;
end;
%变异产生子代C
by=find(rand(1,w)<0.1);
if length(by)==0
by=floor(w*rand(1))+1;
end
C=A(by,:);
L3=length(by);
for j=1:L3
<a href="https://www..com/s?wd=bw&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">bw</a>=floor(1+fix(rand(1,3)*N)); %产生1-N的3个随机数
<a href="https://www..com/s?wd=bw&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">bw</a>=sort(<a href="https://www..com/s?wd=bw&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">bw</a>);
C(j,:)=C(j,[1:bw(1)-1,bw(2)+1:bw(3),bw(1):bw(2),bw(3)+1:L]);
end
G=[A;B;C];
<a href="https://www..com/s?wd=TL&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">TL</a>=size(G,1);
%在父代和子代中选择优良品种作为新的父代
[<a href="https://www..com/s?wd=dd&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">dd</a>,IX]=sort(G,2);
temp=[];
temp(1:<a href="https://www..com/s?wd=TL&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">TL</a>)=0;
for j=1:<a href="https://www..com/s?wd=TL&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">TL</a>
for i=1:L-1
temp(j)=temp(j)+d(IX(j,i),IX(j,i+1));
end
end
[DZ,IZ]=sort(temp);
A=G(IZ(1:w),:);
end
path=IX(IZ(1),:)
% for i=1:length(path)
% path(i)=path(i)-1;
% end
% path=path(2:end-1);
lmin=0;l=0;
for j=1:(length(path)-1)
<a href="https://www..com/s?wd=t1&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">t1</a>=path(j);t2=path(j+1);
l=d(<a href="https://www..com/s?wd=t1&tn=44039180_cpr&fenlei=-CEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-" target="_blank" class="-highlight">t1</a>,t2);
lmin=lmin+l;
end
xx=sj0(path,1);yy=sj0(path,2);
plot(xx,yy,'r-o');
axis equal
toc
⑧ 如何用matlab解决多元遗传算法问题
如何用matlab解决多元遗传算法的极值问题?可以按下列步骤做
1、首先,建立自定义带条件的最大值目标函数文件,ga_fun.m
if x(1)+x(2)>=-1
y=-(exp(-0.1*(x(1)^4+x(2)^4))+ exp(cos(2*pi*x(1))+cos(2*pi*x(2)))
)
else
y=inf
end
式中:x=x(1),y=x(2)
2、利用ga遗传算法工具箱求解
3、在工具箱中,Fitness function项输入@ga_fun;Number of variables项输入2;Lower项输入[-1,2];Upper项输入[2,1];
4、点击Start按钮,运行可以得到 fmax(0,0)值(Objective function value)。说明这里负号是最大值的标志
运行界面