遺傳演算法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)。說明這里負號是最大值的標志
運行界面