遺傳演算法神經網路matlab
① MATLAB線性神經網路的程序,跪求。。
美國Michigan 大學的 Holland 教授提出的遺傳演算法(GeneticAlgorithm, GA)是求解復雜的組合優化問題的有效方法 ,其思想來自於達爾文進化論和門德爾松遺傳學說 ,它模擬生物進化過程來從龐大的搜索空間中篩選出較優秀的解,是戚鎮一種高效而且具有強魯棒性方法。所以,遺傳演算法在求解TSP和 MTSP問題中得到了廣泛的應用。
matlab程序如下:
function[opt_rte,opt_brk,min_dist] =mtspf_ga(xy,dmat,salesmen,min_tour,pop_size,num_iter)
%%
%實例
% n = 20;%城市個數
% xy = 10*rand(n,2);%城市坐標 隨機產生,也可以自己設定
% salesmen = 5;%旅行商個數
% min_tour = 3;%每個旅行商最少訪問的城市數
% pop_size = 80;%種群個數
% num_iter = 200;%迭代次數
% a = meshgrid(1:n);
% dmat =reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),n,n);
% [opt_rte,opt_brk,min_dist] = mtspf_ga(xy,dmat,salesmen,min_tour,...
% pop_size,num_iter);%函數
%%
[N,dims]= size(xy); %城市矩陣大小
[nr,nc]= size(dmat); %城市距離矩陣大小
n = N -1;% 除去起始的城市後剩餘的城市的數
% 初始化路線、斷點的選擇
num_brks= salesmen-1;
dof = n- min_tour*salesmen; %初始化路線、斷點的選擇
addto =ones(1,dof+1);
for k =2:num_brks
addto = cumsum(addto);
end
cum_prob= cumsum(addto)/sum(addto);
%% 初始化種群
pop_rte= zeros(pop_size,n); % 種群路徑
pop_brk= zeros(pop_size,num_brks); % 斷點集合的種群
for k =1:pop_size
pop_rte(k,:) = randperm(n)+1;
pop_brk(k,:) = randbreaks();
end
% 畫圖路徑曲線顏色
clr =[1 0 0; 0 0 1; 0.67 0 1; 0 1 0; 1 0.5 0];
ifsalesmen > 5
clr = hsv(salesmen);
end
%%
% 基於遺傳演算法的MTSP
global_min= Inf; %初始化最短路徑
total_dist= zeros(1,pop_size);
dist_history= zeros(1,num_iter);
tmp_pop_rte= zeros(8,n);%當前的路徑設置
tmp_pop_brk= zeros(8,num_brks); %當前的斷點設置
new_pop_rte= zeros(pop_size,n);%更新的路徑設置
new_pop_brk= zeros(pop_size,num_brks);%更新的斷點設置
foriter = 1:num_iter
% 計算適應值
for p = 1:pop_size
d = 0;
p_rte = pop_rte(p,:);
p_brk = pop_brk(p,:);
rng = [[1 p_brk+1];[p_brk n]]';
for s = 1:salesmen
d = d + dmat(1,p_rte(rng(s,1)));% 添加開始的路徑
for k = rng(s,1):rng(s,2)-1
d = d + dmat(p_rte(k),p_rte(k+1));
end
滲旁 d = d + dmat(p_rte(rng(s,2)),1); % 添加結束的的路徑
end
叢仔橡 total_dist(p) = d;
end
% 找到種群中最優路徑
[min_dist,index] = min(total_dist);
dist_history(iter) = min_dist;
if min_dist < global_min
global_min = min_dist;
opt_rte = pop_rte(index,:); %最優的最短路徑
opt_brk = pop_brk(index,:);%最優的斷點設置
rng = [[1 opt_brk+1];[opt_brk n]]';%設置記錄斷點的方法
figure(1);
for s = 1:salesmen
rte = [1 opt_rte(rng(s,1):rng(s,2))1];
plot(xy(rte,1),xy(rte,2),'.-','Color',clr(s,:));
title(sprintf('城市數目為 = %d,旅行商數目為 = %d,總路程 = %1.4f, 迭代次數 =%d',n+1,salesmen,min_dist,iter));
hold on
grid on
end
plot(xy(1,1),xy(1,2),'ko');
hold off
end
% 遺傳操作
rand_grouping = randperm(pop_size);
for p = 8:8:pop_size
rtes = pop_rte(rand_grouping(p-7:p),:);
brks = pop_brk(rand_grouping(p-7:p),:);
dists =total_dist(rand_grouping(p-7:p));
[ignore,idx] = min(dists);
best_of_8_rte = rtes(idx,:);
best_of_8_brk = brks(idx,:);
rte_ins_pts = sort(ceil(n*rand(1,2)));
I = rte_ins_pts(1);
J = rte_ins_pts(2);
for k = 1:8 %產生新種群
tmp_pop_rte(k,:) = best_of_8_rte;
tmp_pop_brk(k,:) = best_of_8_brk;
switch k
case 2% 倒置操作
tmp_pop_rte(k,I:J) =fliplr(tmp_pop_rte(k,I:J));
case 3 % 互換操作
tmp_pop_rte(k,[I J]) =tmp_pop_rte(k,[J I]);
case 4 % 滑動平移操作
tmp_pop_rte(k,I:J) =tmp_pop_rte(k,[I+1:J I]);
case 5% 更新斷點
tmp_pop_brk(k,:) = randbreaks();
case 6 % 倒置並更新斷點
tmp_pop_rte(k,I:J) =fliplr(tmp_pop_rte(k,I:J));
tmp_pop_brk(k,:) =randbreaks();
case 7 % 互換並更新斷點
tmp_pop_rte(k,[I J]) =tmp_pop_rte(k,[J I]);
tmp_pop_brk(k,:) =randbreaks();
case 8 % 評議並更新斷點
tmp_pop_rte(k,I:J) =tmp_pop_rte(k,[I+1:J I]);
tmp_pop_brk(k,:) =randbreaks();
otherwise
end
end
new_pop_rte(p-7:p,:) = tmp_pop_rte;
new_pop_brk(p-7:p,:) = tmp_pop_brk;
end
pop_rte = new_pop_rte;
pop_brk = new_pop_brk;
end
figure(2)
plot(dist_history,'b','LineWidth',2);
title('歷史最優解');
xlabel('迭代次數')
ylabel('最優路程')
% 隨機產生一套斷點 的集合
function breaks = randbreaks()
if min_tour == 1 % 一個旅行商時,沒有斷點的設置
tmp_brks = randperm(n-1);
breaks =sort(tmp_brks(1:num_brks));
else % 強制斷點至少找到最短的履行長度
num_adjust = find(rand <cum_prob,1)-1;
spaces =ceil(num_brks*rand(1,num_adjust));
adjust = zeros(1,num_brks);
for kk = 1:num_brks
adjust(kk) = sum(spaces == kk);
end
breaks = min_tour*(1:num_brks) +cumsum(adjust);
end
end
disp('最優路徑為:/n')
disp(opt_rte);
disp('其中斷點為為:/n')
disp(opt_brk);
end
② 運行遺基於遺傳演算法的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 中求二元函數最小值
你最好能提供具體的二元函數表達式,這樣就可以有目的去幫你解決。一般遺傳演算法可以用ga()函數來求解。例如:
fun = @(x) (x(1) - 0.2)^2 + (x(2) - 1.7)^2
x = ga(fun,2)
執行結果
x = 0.20208 1.6766
④ 遺傳演算法優化概率神經網路的matlab代碼
原理大概是,設置一個初始種群,種群里的個體就是平滑因子,經過遺傳演算法的選擇、交叉、變異後,逐漸找到一個最佳的spread,即為最終結果。
附件是一個GA-BP演算法的程序,雖然不同,但是原理是相近的,可以參考。
遺傳演算法的基本運算過程如下:
a)初始化:設置進化代數計數器t=0,設置最大進化代數T,隨機生成M個個體作為初始群體P(0)。
b)個體評價:計算群體P(t)中各個個體的適應度。
c)選擇運算:將選擇運算元作用於群體。選擇的目的是把優化的個體直接遺傳到下一代或通過配對交叉產生新的個體再遺傳到下一代。選擇操作是建立在群體中個體的適應度評估基礎上的。
d)交叉運算:將交叉運算元作用於群體。遺傳演算法中起核心作用的就是交叉運算元。
e)變異運算:將變異運算元作用於群體。即是對群體中的個體串的某些基因座上的基因值作變動。
群體P(t)經過選擇、交叉、變異運算之後得到下一代群體P(t+1)。
f)終止條件判斷:若t=T,則以進化過程中所得到的具有最大適應度個體作為最優解輸出,終止計算。
⑤ matlab的遺傳演算法優化BP神經網路
對y=x1^2+x2^2非線性系統進行建模,用1500組數據對網路進行構建網路,500組數據測試網路。由於BP神經網路初始神經元之間的權值和閾值一般隨機選擇,因此容易陷入局部最小值。本方法使用遺傳演算法優化初始神經元之間的權值和閾值,並對比使用遺傳演算法前後的效果。
步驟:
未經遺傳演算法優化的BP神經網路建模
1、 隨機生成2000組兩維隨機數(x1,x2),並計算對應的輸出y=x1^2+x2^2,前1500組數據作為訓練數據input_train,後500組數據作為測試數據input_test。並將數據存儲在data中待遺傳演算法中使用相同的數據。
2、 數據預處理:歸一化處理。
3、 構建BP神經網路的隱層數,次數,步長,目標。
4、 使用訓練數據input_train訓練BP神經網路net。
⑥ 如何使用遺傳演算法或神經網路在MATLAB 中求二元函數最小值
% 2008年4月12日修改
%**********************%主函數*****************************************
function main()
global chrom lchrom oldpop newpop varible fitness popsize sumfitness %定義全局變數
global pcross pmutation temp bestfit maxfit gen bestgen length epop efitness val varible2 varible1
global maxgen po pp mp np val1
length=18;
lchrom=30; %染色體長度
popsize=30; %種群大小
pcross=0.6; %交叉概率
pmutation=0.01; %變異概率
maxgen=1000; %最大代數
mp=0.1; %保護概率
%
initpop; % 初始種群
%
for gen=1:maxgen
generation;
end
%
best;
bestfit % 最佳個體適應度值輸出
bestgen % 最佳個體所在代數輸出
x1= val1(bestgen,1)
x2= val1(bestgen,2)
gen=1:maxgen;
figure
plot(gen,maxfit(1,gen)); % 進化曲線
title('精英保留');
%
%********************** 產生初始種群 ************************************
%
function initpop()
global lchrom oldpop popsize
oldpop=round(rand(popsize,lchrom)); %生成的oldpop為30行12列由0,1構成的矩陣
%其中popsize為種群中個體數目lchrom為染色體編碼長度
%
%*************************%產生新一代個體**********************************
%
function generation()
global epop oldpop popsize mp
objfun; %計算適應度值
n=floor(mp*popsize); %需要保留的n個精英個體
for i=1:n
epop(i,:)=oldpop((popsize-n+i),:);
% efitness(1,i)=fitness(1,(popsize-n+i))
end
select; %選擇操作
crossover;
mutation;
elite; %精英保留
%
%************************%計算適應度值************************************
%
function objfun()
global lchrom oldpop fitness popsize chrom varible varible1 varible2 length
global maxfit gen epop mp val1
a1=-3; b1=3;
a2=-2;b2=2;
fitness=0;
for i=1:popsize
%前一未知數X1
if length~=0
chrom=oldpop(i,1:length);% before代表節點位置
c=decimal(chrom);
varible1(1,i)=a1+c*(b1-a1)/(2.^length-1); %對應變數值
%後一未知數
chrom=oldpop(i,length+1:lchrom);% before代表節點位置
c=decimal(chrom);
varible2(1,i)=a2+c*(b2-a2)/(2.^(lchrom-length)-1); %對應變數值
else
chrom=oldpop(i,:);
c=decimal(chrom);
varible(1,i)=a1+c*(b1-a1)/(2.^lchrom-1); %對應變數值
end
%兩個自變數
fitness(1,i)=4*varible1(1,i)^2-2.1*varible1(1,i)^4+1/3*varible1(1,i)^6+varible1(1,i)*varible2(1,i)-4*varible2(1,i)^2+4*varible2(1,i)^4;
%fitness(1,i) = 21.5+varible1(1,i)*sin(4*pi*varible1(1,i))+varible2(1,i) *sin(20*pi*varible2(1,i));
%一個自變數
%fitness(1,i) = 20*cos(0.25*varible(1,i))-12*sin(0.33*varible(1,i))+40 %個體適應度函數值
end
lsort; % 個體排序
maxfit(1,gen)=max(fitness); %求本代中的最大適應度值maxfit
val1(gen,1)=varible1(1,popsize);
val1(gen,2)=varible2(1,popsize);
%************************二進制轉十進制**********************************
%
function c=decimal(chrom)
c=0;
for j=1:size(chrom,2)
c=c+chrom(1,j)*2.^(size(chrom,2)-j);
end
%
%************************* 個體排序 *****************************
% 從小到大順序排列
%
function lsort()
global popsize fitness oldpop epop efitness mp val varible2 varible1
for i=1:popsize
j=i+1;
while j<=popsize
if fitness(1,i)>fitness(1,j)
tf=fitness(1,i); % 適應度值
tc=oldpop(i,:); % 基因代碼
fitness(1,i)=fitness(1,j); % 適應度值互換
oldpop(i,:)=oldpop(j,:); % 基因代碼互換
fitness(1,j)=tf;
oldpop(j,:)=tc;
end
j=j+1;
end
val(1,1)=varible1(1,popsize);
val(1,2)=varible2(1,popsize);
end
%*************************轉輪法選擇操作**********************************
%
function select()
global fitness popsize sumfitness oldpop temp mp np
sumfitness=0; %個體適應度之和
for i=1:popsize % 僅計算(popsize-np-mp)個個體的選擇概率
sumfitness=sumfitness+fitness(1,i);
end
%
for i=1:popsize % 僅計算(popsize-np-mp)個個體的選擇概率
p(1,i)=fitness(1,i)/sumfitness; % 個體染色體的選擇概率
end
%
q=cumsum(p); % 個體染色體的累積概率(內部函數),共(popsize-np-mp)個
%
b=sort(rand(1,popsize)); % 產生(popsize-mp)個隨機數,並按升序排列。mp為保護個體數
j=1;
k=1;
while j<=popsize % 從(popsize-mp-np)中選出(popsize-mp)個個體,並放入temp(j,:)中;
if b(1,j)<q(1,k)
temp(j,:)=oldpop(k,:);
j=j+1;
else
k=k+1;
end
end
%
j=popsize+1; % 從統一挪過來的(popsize-np-mp)以後個體——優秀個體中選擇
for i=(popsize+1):popsize % 將mp個保留個體放入交配池temp(i,:),以保證群體數popsize
temp(i,:)=oldpop(j,:);
j=j+1;
end
%
%**************************%交叉操作***************************************
%
function crossover()
global temp popsize pcross lchrom mp
n=floor(pcross*popsize); %交叉發生的次數(向下取整)
if rem(n,2)~=0 % 求余
n=n+1; % 保證為偶數個個體,便於交叉操作
end
%
j=1;
m=0;
%
% 對(popsize-mp)個個體將進行隨機配對,滿足條件者將進行交叉操作(按順序選擇要交叉的對象)
%
for i=1:popsize
p=rand; % 產生隨機數
if p<pcross % 滿足交叉條件
parent(j,:)=temp(i,:); % 選出1個父本
k(1,j)=i;
j=j+1; % 記錄父本個數
m=m+1 ; % 記錄雜交次數
if (j==3)&(m<=n) % 滿足兩個父本(j==3),未超過交叉次數(m<=n)
pos=round(rand*(lchrom-1))+1; % 確定隨機位數(四捨五入取整)
for i=1:pos
child1(1,i)=parent(1,i);
child2(1,i)=parent(2,i);
end
for i=(pos+1):lchrom
child1(1,i)=parent(2,i);
child2(1,i)=parent(1,i);
end
i=k(1,1);
j=k(1,2);
temp(i,:)=child1(1,:);
temp(j,:)=child2(1,:);
j=1;
end
end
end
%
%****************************%變異操作*************************************
%
function mutation()
global popsize lchrom pmutation temp newpop oldpop mp
m=lchrom*popsize; % 總的基因數
n=round(pmutation*m); % 變異發生的次數
for i=1:n % 執行變異操作循環
k=round(rand*(m-1))+1; %確定變異位置(四捨五入取整)
j=ceil(k/lchrom); % 確定個體編號(取整)
l=rem(k,lchrom); %確定個體中變位基因的位置(求余)
if l==0
temp(j,lchrom)=~temp(j,lchrom); % 取非操作
else
temp(j,l)=~temp(j,l); % 取非操作
end
end
for i=1:popsize
oldpop(i,:)=temp(i,:); %產生新的個體
end
%
%*********************%精英選擇%*******************************************
%
function elite()
global epop oldpop mp popsize
objfun; %計算適應度值
n=floor(mp*popsize); %需要保留的n個精英個體
for i=1:n
oldpop(i,:)=epop(i,:);
% efitness(1,i)=fitness(1,(popsize-n+i))
end;
%
%*********************%最佳個體********************************************
%
function best()
global maxfit bestfit gen maxgen bestgen
bestfit=maxfit(1,1);
gen=2;
while gen<=maxgen
if bestfit<maxfit(1,gen)
bestfit=maxfit(1,gen);
bestgen=gen;
end
gen=gen+1;
end
%**************************************************************************
⑦ 遺傳演算法的matlab代碼實現是什麼
遺傳演算法我懂,我的論文就是用著這個演算法,具體到你要遺傳演算法是做什麼?優化什麼的。。。我給你一個標准遺傳演算法程序供你參考:
該程序是遺傳演算法優化BP神經網路函數極值尋優:
%% 該代碼為基於神經網路遺傳演算法的系統極值尋優
%% 清空環境變數
clc
clear
%% 初始化遺傳演算法參數
%初始化參數
maxgen=100; %進化代數,即迭代次數
sizepop=20; %種群規模
pcross=[0.4]; %交叉概率選擇,0和1之間
pmutation=[0.2]; %變異概率選擇,0和1之間
lenchrom=[1 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)=fun(x); %染色體的適應度
end
%找最好的染色體
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色體
avgfitness=sum(indivials.fitness)/sizepop; %染色體的平均適應度
% 記錄每一代進化中最好的適應度和平均適應度
trace=[avgfitness bestfitness];
%% 迭代尋優
% 進化開始
for i=1:maxgen
i
% 選擇
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)=fun(x);
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);
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]);
⑧ matlab宸ュ叿綆變腑鐨勭炵粡緗戠粶鍜岄仐浼犵畻娉曡佹庝箞璋冪敤錛
閮芥槸鏈変袱縐嶈皟鐢ㄦ柟娉曪紝涓縐嶅浘褰㈢晫闈㈢殑錛岃繖涓浠庡紑濮嬭彍鍗曪紝鐒跺悗宸ュ叿錛岀劧鍚庝粠閲岄潰鎵劇炵粡緗戠粶 neural network錛岄仐浼犵畻娉曞伐鍏鋒槸 鍏ㄥ矓浼樺寲宸ュ叿綆遍噷闈㈢殑錛実lobal optimization銆
鍙﹀ 涓縐嶉氳繃鍛戒護琛岃皟鐢錛岃繖涓闇瑕佷綘鐞嗚В浣犻兘瑕佸仛浠涔堬紝鎴戠敤紲炵粡緗戠粶涓句緥銆傜涓姝ラ渶瑕佸厛鏁寸悊鍑鴻緭鍏ュ彉閲忓拰杈撳嚭鍙橀噺錛岀浜屾ヨ捐″苟鍒濆嬪寲紲炵粡緗戠粶錛岀涓夐儴璁緇冿紝絎鍥涢儴鑾峰緱緇撴灉銆
濡傛灉浣犳兂緇撳悎榪欎袱鑰咃紝灝變細鏇村姞澶嶆潅錛岃︾粏鐨勪綘鍙浠ュ啀闂銆傛垜鏇劇粡鍋氳繃鐢ㄩ仐浼犵畻娉曚紭鍖栫炵粡緗戠粶鐨勫伐鍏楓