一个遗传算法matlab源代码的matlab程序,求大神帮看

播放列表加载中...
正在载入...
分享视频:
嵌入代码:
拍下二维码,随时随地看视频
【Matlab数学建模辅导】遗传算法的旅行商问题求解源...
上 传 者:
内容介绍:
【Matlab数学建模辅导】遗传算法的旅行商问题求解源码程序
Channel Me 精选
我来说点啥
版权所有 CopyRight
| 京网文[0号 |
| 京公网安备:
互联网药品信息服务资格证:(京)-非经营性- | 广播电视节目制作经营许可证:(京)字第403号
<img src="" width="34" height="34"/>
<img src=""/>
<li data-vid="">
<img src=""/><i data-vid="" class="ckl_plays">
<img width="132" height="99" src=""/>
在线人数:
<li data-vid="">
<img src=""/><i data-vid="" class="ckl_plays">
<img src="///img/blank.png" data-src=""/>
<img src="///img/blank.png" data-src="http://"/>
<li data-vid="" class="cfix">
src="///img/blank.png" data-src=""/>
<i data-vid="" class="ckl_plays">
<li data-vid="" class="cfix">
src="///img/blank.png" data-src=""/><i data-vid="" class="ckl_plays">
没有数据!
{upload_level_name}
粉丝 {fans_count}
{video_count}
{description}&&&&一个简单的遗传算法例子——MATLAB源程序
一个简单的遗传算法例子——MATLAB源程序
一个一个简单的遗传算法例子,代码注释详尽,很适合初学者进行学习。代码已经经过测试,请放心下载
若举报审核通过,可奖励20下载分
被举报人:
huanhuanding
举报的资源分:
请选择类型
资源无法下载
资源无法使用
标题与实际内容不符
含有危害国家安全内容
含有反动色情等内容
含广告内容
版权问题,侵犯个人或公司的版权
*详细原因:
VIP下载&&免积分60元/年(1200次)
您可能还需要
开发技术下载排行苹果/安卓/wp
苹果/安卓/wp
积分 520, 距离下一级还需 280 积分
权限: 自定义头衔, 签名中使用图片
道具: 彩虹炫, 雷达卡, 热点灯, 雷鸣之声, 涂鸦板, 金钱卡, 显身卡, 匿名卡, 抢沙发下一级可获得
权限: 隐身
购买后可立即获得
权限: 隐身
道具: 金钱卡, 雷鸣之声, 彩虹炫, 雷达卡, 涂鸦板, 热点灯
开心签到天数: 21 天连续签到: 1 天[LV.4]偶尔看看III
TSP问题遗传算法matlab源程序
(23 KB, 售价: 1 个论坛币)
15:12:17 上传
TSP问题遗传算法matlab源程序
售价: 1 个论坛币
支持楼主:、
购买后,论坛将奖励 10 元论坛资金给楼主,以表示您对TA发好贴的支持
载入中......
奖励积极上传好的资料
总评分:&热心指数 + 2&
帮助他人,快乐自己~~[
论坛好贴推荐
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
为做大做强论坛,本站接受风险投资商咨询,请联系(010-)
邮箱:service@pinggu.org
合作咨询电话:(010)
广告合作电话:(刘老师)
投诉电话:(010)
不良信息处理电话:(010)
京ICP证090565号
京公网安备号
论坛法律顾问:王进律师GA 简单遗传算法MATLAB实现,详细的介绍了 的 过程,并以一个 的函数优
238万源代码下载-
&文件名称: GA
& & & & &&]
&&所属分类:
&&开发工具: matlab
&&文件大小: 4 KB
&&上传时间:
&&下载次数: 2
&&提 供 者:
&详细说明:简单遗传算法MATLAB实现,详细的介绍了简单遗传算法的实现过程,并以一个简单的函数优化作为案例说明了其应用。但是由于该测试函数过于简单,在实际的应用过程中,还需要对相关参数进行调整,使其效率得到更大的提高。-Simple genetic algorithm based on MATLAB realize, describes in detail the process of simple genetic algorithm, and a simple function optimization as a case illustrate its application. However, since the test function is too simple, in the actual application process, the relevant parameters need to be adjusted to greater increase efficiency.
文件列表(点击判断是否您需要的文件,如果是垃圾请在下面评价投诉):
&&plotGA.m&&rank.m&&run_ga.m&&selection.m&&crossover.m&&fitness.m&&GeneticAlgorithm.m&&initilize.m&&mutation.m
&输入关键字,在本站238万海量源码库中尽情搜索:
&[] - 采用遗传算法求最小值,比较实用,经过多个测试函数测试查看: 31604|回复: 45|关注: 0
遗传算法解决 TSP 问题(附matlab源程序)
关注者: 17
已知n个城市之间的相互距离,现有一个推销员必须遍访这n个城市,并且每个城市
只能访问一次,最后又必须返回出发城市。如何安排他对这些城市的访问次序,可使其
旅行路线的总长度最短?
用图论的术语来说,假设有一个图g=(v,e),其中v是顶点集,e是边集,设d=(dij)
是由顶点i和顶点j之间的距离所组成的距离矩阵,旅行商问题就是求出一条通过所有顶
点且每个顶点只通过一次的具有最短距离的回路。
这个问题可分为对称旅行商问题(dij=dji,,任意i,j=1,2,3,…,n)和非对称旅行商
问题(dij≠dji,,任意i,j=1,2,3,…,n)。
若对于城市v={v1,v2,v3,…,vn}的一个访问顺序为t=(t1,t2,t3,…,ti,…,tn),其中
ti∈v(i=1,2,3,…,n),且记tn+1= t1,则旅行商问题的数学模型为:
min l=σd(t(i),t(i+1)) (i=1,…,n)
旅行商问题是一个典型的组合优化问题,并且是一个np难问题,其可能的路径数目
与城市数目n是成指数型增长的,所以一般很难精确地求出其最优解,本文采用遗传算法
求其近似解。
遗传算法:
初始化过程:用v1,v2,v3,…,vn代表所选n个城市。定义整数pop-size作为染色体的个数
,并且随机产生pop-size个初始染色体,每个染色体为1到18的整数组成的随机序列。
适应度f的计算:对种群中的每个染色体vi,计算其适应度,f=σd(t(i),t(i+1)).
评价函数eval(vi):用来对种群中的每个染色体vi设定一个概率,以使该染色体被选中
的可能性与其种群中其它染色体的适应性成比例,既通过轮盘赌,适应性强的染色体被
选择产生后台的机会要大,设alpha∈(0,1),本文定义基于序的评价函数为eval(vi)=al
pha*(1-alpha).^(i-1) 。[随机规划与模糊规划]
选择过程:选择过程是以旋转赌轮pop-size次为基础,每次旋转都为新的种群选择一个
染色体。赌轮是按每个染色体的适应度进行选择染色体的。
step1 、对每个染色体vi,计算累计概率qi,q0=0;qi=σeval(vj) j=1,…,i;i=1,
…pop-size.
step2、从区间(0,pop-size)中产生一个随机数r;
step3、若qi-1 step4、重复step2和step3共pop-size次,这样可以得到pop-size个复制的染色体。
grefenstette编码:由于常规的交叉运算和变异运算会使种群中产生一些无实际意义的
染色体,本文采用grefenstette编码《遗传算法原理及应用》可以避免这种情况的出现
。所谓的grefenstette编码就是用所选队员在未选(不含淘汰)队员中的位置,如:
8 15 2 16 10 7 4 3 11 14 6 12 9 5 18 13 17 1
对应:
8 14 2 13 8 6 3 2 5 7 3 4 3 2 4 2 2 1。
交叉过程:本文采用常规单点交叉。为确定交叉操作的父代,从 到pop-size重复以下过
程:从[0,1]中产生一个随机数r,如果r 将所选的父代两两组队,随机产生一个位置进行交叉,如:
8 14 2 13 8 6 3 2 5 7 3 4 3 2 4 2 2 1
6 12 3 5 6 8 5 6 3 1 8 5 6 3 3 2 1 1
交叉后为:
8 14 2 13 8 6 3 2 5 1 8 5 6 3 3 2 1 1
6 12 3 5 6 8 5 6 3 7 3 4 3 2 4 2 2 1
变异过程:本文采用均匀多点变异。类似交叉操作中选择父代的过程,在r 选择多个染色体vi作为父代。对每一个选择的父代,随机选择多个位置,使其在每位置
按均匀变异(该变异点xk的取值范围为[ukmin,ukmax],产生一个[0,1]中随机数r,该点
变异为x'k=ukmin+r(ukmax-ukmin))操作。如:
8 14 2 13 8 6 3 2 5 7 3 4 3 2 4 2 2 1
变异后:
8 14 2 13 10 6 3 2 2 7 3 4 5 2 4 1 2 1
反grefenstette编码:交叉和变异都是在grefenstette编码之后进行的,为了循环操作
和返回最终结果,必须逆grefenstette编码过程,将编码恢复到自然编码。
循环操作:判断是否满足设定的带数xzome,否,则跳入适应度f的计算;是,结束遗传
操作,跳出。
matlab 代码
distTSP.txt
0 6 18 4 8
7 0 17 3 7
4 4 0 4 5
20 19 24 0 22
8 8 16 6 0
%GATSP.m
function gatsp1()
load distTSP.
distance=distTSP;
N=5;
ngen=100;
ngpool=10;
%ngen=input('# of generations to evolve = ');
%ngpool=input('# of chromosoms in the gene pool = '); % size of genepool
gpool=zeros(ngpool,N+1); % gene pool
for i=1:ngpool, % intialize gene pool
gpool(i,:)=[1 randomize([2:N]')' 1];
for j=1:i-1
while gpool(i,:)==gpool(j,:)
gpool(i,:)=[1 randomize([2:N]')' 1];
costmin=100000;
tourmin=zeros(1,N);
cost=zeros(1,ngpool);
increase=1;resultincrease=1;
for i=1:ngpool,
cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));
end
% record current best solution
[costmin,idx]=min(cost);
tourmin=gpool(idx,:);
disp([num2str(increase) 'minmum trip length = ' num2str(costmin)])
costminold2=200000;costminold1=150000;resultcost=100000;
tourminold2=zeros(1,N);
tourminold1=zeros(1,N);
resulttour=zeros(1,N);
while (abs(costminold2-costminold1) ;100)&(abs(costminold1-costmin) ;100)&(500)
costminold2=costminold1; tourminold2=tourminold1;
costminold1=tourminold1=
increase=increase+1;
if resultcost&costmin
resultcost=
resulttour=
resultincrease=increase-1;
for i=1:ngpool,
cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));
% record current best solution
[costmin,idx]=min(cost);
tourmin=gpool(idx,:);
%==============
% copy gens in th gpool according to the probility ratio
% &1.1 copy twice
% &=0.9 copy once
% ;0.9 remove
[csort,ridx]=sort(cost);
% sort from small to big.
csum=sum(csort);
caverage=csum/
cprobilities=caverage./
copynumbers=0;removenumbers=0;
for i=1:ngpool,
if cprobilities(i) &1.1
copynumbers=copynumbers+1;
if cprobilities(i) &0.9
removenumbers=removenumbers+1;
copygpool=min(copynumbers,removenumbers);
for i=1:copygpool
for j=ngpool:-1:2*i+2 gpool(j,:)=gpool(j-1,:);
gpool(2*i+1,:)=gpool(i,:);
if copygpool==0
gpool(ngpool,:)=gpool(1,:);
%=========
%when genaration is more than 50,or the patterns in a couple are too close,do mutation
for i=1:ngpool/2
sameidx=[gpool(2*i-1,:)==gpool(2*i,:)];
diffidx=find(sameidx==0);
if length(diffidx)&=2
gpool(2*i,:)=[1 randomize([2:12]')' 1];
%===========
%cross gens in couples
for i=1:ngpool/2
[gpool(2*i-1,:),gpool(2*i,:)]=crossgens(gpool(2*i-1,:),gpool(2*i,:));
for i=1:ngpool,
cost(i)=sum(diag(distance(gpool(i,:)',rshift(gpool(i,:))')));
% record current best solution
[costmin,idx]=min(cost);
tourmin=gpool(idx,:);
disp([num2str(increase) 'minmum trip length = ' num2str(costmin)])
end
disp(['cost function evaluation: ' int2str(increase) ' times!'])
disp(['n:' int2str(resultincrease)])
disp(['minmum trip length = ' num2str(resultcost)])
disp('optimum tour = ')
disp(num2str(resulttour))
%====================================================
function B=randomize(A,rowcol)
% Usage: B=randomize(A,rowcol)
% randomize row orders or column orders of A matrix
% rowcol: if =0 or omitted, row order (default)
% if = 1, column order
rand('state',sum(100*clock))
if nargin == 1,
rowcol=0;
end
if rowcol==0,
[m,n]=size(A);
p=rand(m,1);
[p1,I]=sort(p);
B=A(I,:);
elseif rowcol==1,
Ap=A';
[m,n]=size(Ap);
p=rand(m,1);
[p1,I]=sort(p);
B=Ap(I,:)';
end
%=====================================================
function y=rshift(x,dir)
% Usage: y=rshift(x,dir)
% rotate x vector to right (down) by 1 if dir = 0 (default)
% or rotate x to left (up) by 1 if dir = 1
2, dir=0; end
[m,n]=size(x);
if n == 1,
elseif n&1,
error('x must be a vector! break');
end % x is a column vectorelseif m == 1,
if n == 1, y=x;
elseif n&1,
col=0; % x is a row vector endend
if dir==1, % rotate left or up
if col==0, % row vector, rotate left
y = [x(2:n) x(1)];
elseif col==1,
y = [x(2:n); x(1)]; % rotate up
end
elseif dir==0, % default rotate right or down
if col==0,
y = [x(n) x(1:n-1)];
elseif col==1 % column vector
y = [x(n); x(1:n-1)];
end
end
%==================================================
function [L1,L2]=crossgens(X1,X2)
% Usage:[L1,L2]=crossgens(X1,X2)
s=randomize([2:12]')';
n1=min(s(1),s(11));n2=max(s(1),s(11));
X3=X1;X4=X2;
for i=n1:n2,
for j=1:13,
if X2(i)==X3(j),
if X1(i)==X4(j), X4(j)=0;
end
end
j=13;k=13;
for i=12:-1:2,
if X3(i)~=0,
t=X3(j);X3(j)=X3(i);X3(i)=t;
if X4(i)~=0,
t=X4(k);X4(k)=X4(i);X4(i)=t;
end
end
for i=n1:n2
X3(2+i-n1)=X2(i);
X4(2+i-n1)=X1(i);
end
L1=X3;L2=X4;
%=======================复制代码
关注者: 17
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)
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.3(当x为7.8562时,f(x)取最大值24.8553)
注:遗传算法一般用来取得近似最优解,而不是最优解。 复制代码
关注者: 17
用遗传算法优化BP神经网络的Matlab编程实例
程序一:GA训练BP权值的主函数
function net=GABPNET(XX,YY)
%--------------------------------------------------------------------------
% GABPNET.m
% 使用遗传算法对BP网络权值阈值进行优化,再用BP算法训练网络
%--------------------------------------------------------------------------
%数据归一化预处理
nntwarn off
XX=premnmx(XX);
YY=premnmx(YY);
%创建网络
net=newff(minmax(XX),[19,25,1],{'tansig','tansig','purelin'},'trainlm');
%下面使用遗传算法对网络进行优化
P=XX;
T=YY;
R=size(P,1);
S2=size(T,1);
S1=25;%隐含层节点数
S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
aa=ones(S,1)*[-1,1];
popu=50;%种群规模
initPpp=initializega(popu,aa,'gabpEval');%初始化种群
gen=100;%遗传代数
%下面调用gaot工具箱,其中目标函数定义为gabpEval
[x,endPop,bPop,trace]=ga(aa,'gabpEval',[],initPpp,[1e-6 1 1],'maxGenTerm',gen,...
'normGeomSelect',[0.09],['arithXover'],[2],'nonUnifMutation',[2 gen 3]);
%绘收敛曲线图
figure(1)
plot(trace(:,1),1./trace(:,3),'r-');
hold on
plot(trace(:,1),1./trace(:,2),'b-');
xlabel('Generation');
ylabel('Sum-Squared Error');
figure(2)
plot(trace(:,1),trace(:,3),'r-');
hold on
plot(trace(:,1),trace(:,2),'b-');
xlabel('Generation');
ylabel('Fittness');
%下面将初步得到的权值矩阵赋给尚未开始训练的BP网络
[W1,B1,W2,B2,P,T,A1,A2,SE,val]=gadecod(x);
net.LW{2,1}=W1;
net.LW{3,2}=W2;
net.b{2,1}=B1;
net.b{3,1}=B2;
XX=P;
YY=T;
%设置训练参数
net.trainParam.show=1;
net.trainParam.lr=1;
net.trainParam.epochs=50;
net.trainParam.goal=0.001;
%训练网络
net=train(net,XX,YY);
程序二:适应值函数
function [sol, val] = gabpEval(sol,options)
% val - the fittness of this individual
% sol - the individual, returned to allow for Lamarckian evolution
% options - [current_generation]
load data2
nntwarn off
XX=premnmx(XX);
YY=premnmx(YY);
P=XX;
T=YY;
R=size(P,1);
S2=size(T,1);
S1=25;%隐含层节点数
S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
for i=1:S,
x(i)=sol(i);
[W1, B1, W2, B2, P, T, A1, A2, SE, val]=gadecod(x);
程序三:编解码函数
function [W1, B1, W2, B2, P, T, A1, A2, SE, val]=gadecod(x)
load data2
nntwarn off
XX=premnmx(XX);
YY=premnmx(YY);
P=XX;
T=YY;
R=size(P,1);
S2=size(T,1);
S1=25;%隐含层节点数
S=R*S1+S1*S2+S1+S2;%遗传算法编码长度
% 前R*S1个编码为W1
for i=1:S1,
for k=1:R,
W1(i,k)=x(R*(i-1)+k);
end
end
% 接着的S1*S2个编码(即第R*S1个后的编码)为W2
for i=1:S2,
for k=1:S1,
W2(i,k)=x(S1*(i-1)+k+R*S1);
end
end
% 接着的S1个编码(即第R*S1+S1*S2个后的编码)为B1
for i=1:S1,
B1(i,1)=x((R*S1+S1*S2)+i);
end
% 接着的S2个编码(即第R*S1+S1*S2+S1个后的编码)为B2
for i=1:S2,
B2(i,1)=x((R*S1+S1*S2+S1)+i);
end
% 计算S1与S2层的输出
A1=tansig(W1*P,B1);
A2=purelin(W2*A1,B2);
% 计算误差平方和
SE=sumsqr(T-A2);
val=1/SE; % 遗传算法的适应值复制代码
关注者: 17
遗传算法程序 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=
if nargin&3, error('FMAXGA requires at least three input arguments'); end
if nargin==3, eranum=200;popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];end
if nargin==4, popsize=100;pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];end
if nargin==5, pCross=0.8;pMutation=0.1;pInversion=0.15;options=[0 1e-4];end
if nargin==6, pMutation=0.1;pInversion=0.15;options=[0 1e-4];end
if nargin==7, pInversion=0.15;options=[0 1e-4];end
if find((LB-UB)&0)
error('数据输入错误,请重新输入(LB&UB):');
&/UB):');
end
s=sprintf('程序运行需要约%.4f 秒钟时间,请稍等......',(eranum*popsize/1000));
disp(s);
global m n NewPop children1 children2 VarNum
bounds=[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=pM
BestPop=zeros(eranum,n);%分配初始解空间BestPop,Trace
Trace=zeros(eranum,length(bits)+1);
i=1;
while i&=eranum
for j=1:m
value(j)=feval(FUN(1,:),(b2f(Pop(j,:),bounds,bits)));%计算适应度
end
[MaxValue,Index]=max(value);
BestPop(i,:)=Pop(Index,:);
Trace(i,1)=MaxV
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=InversionP%更新
pMutation=pm0+(i^4)*(pCross/3-pm0)/(eranum^4);
%随着种群向前进化,逐步增大变异率至1/2交叉率
p(i)=pM
i=i+1;
end
t=1:
plot(t,Trace(:,1)');
title('函数优化的遗传算法');xlabel('进化世代数(eranum)');ylabel('每一代最优适应度(maxfitness)');
[MaxFval,I]=max(Trace(:,1));
X=Trace(I,(2:length(bits)+1));
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=
elapsed_time=T2-T1;
if elapsed_time(6)&0
elapsed_time(6)=elapsed_time(6)+60; elapsed_time(5)=elapsed_time(5)-1;
end
if elapsed_time(5)&0
elapsed_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 individual
for i=2:popsize-1
pop=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);
end
initpop(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:numV
a=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))=1
function [selectpop]=NonlinearRankSelect(FUN,pop,bounds,bits)
global m n
selectpop=zeros(m,n);
fit=zeros(m,1);
for i=1:m
fit(i)=feval(FUN(1,:),(b2f(pop(i,:),bounds,bits)));%以函数值为适应值做排名依据
end
selectprob=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&=m
if rNums(newIn)&NEWFIT(FITIN)
selectpop(newIn,:)=pop(fitIn,:);
newIn=newIn+1;
else
fitIn=fitIn+1;
end
end
%交叉操作
function [NewPop]=CrossOver(OldPop,pCross,opts)
%OldPop为父代种群,pcross为交叉概率
global m n NewPop
r=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)=[];
end
if length(y1)&=2
for i=0:2:length(y1)-2
if 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),:));
end
end
end
NewPop(y2,:)=OldPop(y2,:);
%采用均匀交叉
function [children1,children2]=EqualCrossOver(parent1,parent2)
global n children1 children2
hidecode=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 VarNum
Children1=Parent1;
Children2=Parent2;
Points=sort(unidrnd(n,1,2*VarNum));
for i=1:VarNum
Children1(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 NewPop
r=rand(1,m);
position=find(r&=pMutation);
len=length(position);
if len&=1
for i=1:len
k=unidrnd(n,1,VarNum); %设置变异点数,一般设置1点
for j=1:length(k)
if OldPop(position(i),k(j))==1
OldPop(position(i),k(j))=0;
else
OldPop(position(i),k(j))=1;
end
end
end
end
NewPop=OldP
function [NewPop]=Inversion(OldPop,pInversion)
global m n NewPop
NewPop=OldP
r=rand(1,m);
PopIn=find(r&=pInversion);
len=length(PopIn);
if len&=1
for i=1:len
d=sort(unidrnd(n,1,2));
if d(1)~=1&d(2)~=n
NewPop(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);
end
end
end复制代码
initializega这个函数显示未定义呢 该如何解决?
第一个程序,遗传算法解决TSP问题怎么不能运行啊。
我刚学MATLAB 没几天,该程序是不是要连接一个含有城市坐标的文件?
具体该怎么操作啊?
呵呵,不错,正好用得到。
真是好强大
不得不说,很强大
站长推荐 /2
Powered by

我要回帖

更多关于 遗传算法tsp matlab 的文章

 

随机推荐