经典的遗传算法求解小规模的旅行商问题(TSP)

GA求解TSP问题的matlab代码

本文的遗传算法的思想比较简单,是比较经典的遗传算法的实现。本文的遗传算法求解TSP问题采用的是顺序编码,交叉方式是循环交叉,变异方式有两种,已在代码中注明。

主程序

% Author: Chauncy_xu
% date:2019年4月1日
clc;
clear all;
close all;
[len_side,city]=City();%len_side存放的是边的权重。city存放的是30个城市的坐标
%%  参数设置
Num_pop=200; %初始种群大小
Num_gen=800;  %最大代数
P_c=0.85; %交叉概率
P_m=0.4; %变异概率
%% 产生初始种群
pop=zeros(Num_pop,30);%pop是一个种群,。每一行是一个个体,即一个可行解
for i=1:Num_pop %随机生成初始种群
    pop(i,:)=randperm(30);
end
[~,p_sum]=Fitness(pop,len_side);%计算适应度值和累计概率
Gen=1;
ymean=zeros(Gen,1);%记录平均适应度值
ymax=zeros(Gen,1);  %记录最优适应度值
xmax=zeros(Num_pop,30);
temp_pop=zeros(Num_pop,30);
new_pop=zeros(Num_pop,30);
%% 开始迭代
while Gen<=Num_gen
    %该算法选择交叉变异都是只选择两个个体进行
    sel_pop=Select(p_sum,pop); %选择操作
    cross_pop=Cross(sel_pop,P_c);  %交叉操作
    muta_pop=Mutate(cross_pop,P_m);  %变异操作
    pop=muta_pop;  %产生了新的种群
    [fit,p_sum]=Fitness(pop,len_side);  %计算新种群的适应度
    %记录当前代最好和平均的适应度
    [fitness_max,nun_max]=max(fit);
    ymean(Gen)=1000/mean(fit);
    ymax(Gen)=1000/fitness_max;
    %记录当前代的最佳个体
    best_indivi=pop(nun_max,:);
    xmax(Gen,:)=best_indivi;
%   Draw(city,best_indivi,ymax(Gen),Gen,0);
    Gen=Gen+1;
end
[min_ymax,index]=min(ymax);
Draw(city,xmax(index,:),min_ymax,index,1);
%%  绘图
h2=figure(2);
plot(ymax,'b-');
hold on;
plot(ymean,'k-');
grid;
title('迭代曲线','FontSize',16);
fprintf('求得的最短距离:%.2f\n',min_ymax);
fprintf('最短回路');
disp(xmax(index,:));
grid  on
h1=legend('每代最小值','每代平均值');
set(h1,'FontSize',10);
xlabel('\bf迭代次数');ylabel('\bf适应度值');

适应度值计算

function [fit,p]=Fitness(pop,len_side)
[size_pop,len_code]=size(pop);
%% 计算每个个体的总长度
fit=zeros(size_pop,1); %适应度函数初始化为0
for i=1:size_pop    
    f=0;
    for j=1:(len_code-1)
        f=f+len_side(pop(i,j),pop(i,j+1));
    end
    f=f+len_side(pop(i,len_code),pop(i,1));
    fit(i)=f;
end
%% 适应值函数标定
fit=1000./fit'; %取距离倒数
%根据个体的适应度计算其被选择的概率
sum_fit=0;%总的适应度值
for i=1:size_pop
    sum_fit=sum_fit+fit(i)^30;% 让适应度越好的个体被选择概率越高
end
p_indivi=zeros(size_pop,1);
for i=1:size_pop
    p_indivi(i)=fit(i)^30/sum_fit;
end
%% 计算累积概率
p=zeros(1,size_pop);%p是累计概率矩阵
p(1)=p_indivi(1);
for i=2:size_pop
    p(i)=p(i-1)+p_indivi(i);
end
end

选择算子

function sle_pop=Select(sum_p,pop)
[m,n]=size(pop);
temp_pop=zeros(m,n);
for i=1:m
    p=rand;
    while p==0
        p=rand;
    end
    j=1;
    while p>sum_p(j)
        j=j+1;
    end
    temp_pop(i,:)=pop(j,:);
end
sle_pop=temp_pop;
 end       

交叉算子

function cross_pop=Cross(sel_pop,P_c)
[size_pop,len_code]=size(sel_pop);%获取种群的列数
cross_pop=sel_pop;
for i=1:2:size_pop-1
    flag=0;
    p=rand();
    if p<=P_c
        flag=1;
    end
    father(1,:)=sel_pop(i,:);  %获得父代
    father(2,:)=sel_pop(i+1,:);%获得母代
    if flag==1
        temp_spot1=round(rand*(len_code-2))+1;  %产生交叉位置1
        temp_spot2=round(rand*(len_code-2))+1;  %产生交叉位置2
        while temp_spot2==temp_spot1
             temp_spot2=round(rand*(len_code-2))+1;
        end
        spot1=min(temp_spot1,temp_spot2);       %交叉开始的地方
        spot2=max(temp_spot1,temp_spot2);       %交叉结束的地方
        %% 交叉前准备
        temp1=zeros(1,len_code);
        temp2=zeros(1,len_code);
        o=1; q=spot2+1;xx=1;
        while xx<2*len_code
            if q<=len_code
                temp1(o)=father(1,q);
                temp2(o)=father(2,q);
                o=o+1;
                q=q+1;
            end
            xx=xx+1;
        end
            q=1;xx=1;
            while xx<2*len_code
                if q<=spot2
                    temp1(o)=father(1,q);
                    temp2(o)=father(2,q);
                    o=o+1;
                    q=q+1;
                end
                xx=xx+1;
            end
        C1=zeros(1,len_code);
        C2=zeros(1,len_code);
        %% 交换中间位置
        C2(1,spot1+1:spot2)=father(1,spot1+1:spot2);
        C1(1,spot1+1:spot2)=father(2,spot1+1:spot2);
        %% 修复其他位置
        S=spot2+1;
        r=1;
        f=0;
        w=1;%w用来记录有多少个点被添加进来 
      while r<=len_code
              if S<=len_code 
                if (~(ismember(temp1(r),C1)))
                    C1(S)=temp1(r);
                    S=S+1;
                    w=w+1;
                end
              end
             r=r+1;
      end
        S=1;
        r=w;
      while r<=len_code
          if S<=len_code
                if (~(ismember(temp1(r),C1)))
                    C1(S)=temp1(r);
                    S=S+1;
                end
          end
            r=r+1;
      end
        S=spot2+1;
        r=1;
        w=1;
      while r<=len_code
              if(S<=len_code)
                if (~(ismember(temp2(r),C2)))
                    C2(S)=temp2(r);
                    S=S+1;
                    w=w+1;
                end
              end
             r=r+1;
      end
        S=1;
        r=w;
      while r<=len_code
            if(S<=len_code)
                if (~(ismember(temp2(r),C2)))
                    C2(S)=temp2(r);
                    S=S+1;
                    w=w+1; 
                end
            end
            r=r+1;
      end
      cross_pop(i,:)=C1(1,:);
      cross_pop(i+1,:)=C2(1,:);
    end
end
end

变异算子

function mut_pop=Mutate(pop,P_m)
[size_pop,len_code]=size(pop);
mut_pop=pop;
for i=1:size_pop
    flag=0;
    p=rand();
    if p<=P_m
        flag=1;
    end
    if flag==1
        temp_spot1=round(rand*(len_code-1))+1;
        temp_spot2=round(rand*(len_code-1))+1;
        spot1=min(temp_spot1,temp_spot2);
        spot2=max(temp_spot1,temp_spot2);
%           temp=pop(i,spot1+1:spot2);
%          mut_pop(i,spot1+1:spot2)=fliplr(temp);
         %两种变异方式
          temp=mut_pop(i,spot1);
         mut_pop(i,spot1)=mut_pop(i,spot2);
          mut_pop(i,spot2)=temp;

    end
end
end

City函数

function [Len,city_loc]=City()
Len=zeros(30,30);%Len是一个30*30的矩阵,city_location是一个30行两列的矩阵
    city=[41 94;37 84;54 67;25 62;7 64;2 99;68 58;71 44;54 62;83 69;64 60;18 54;22 60;%每一行是一个城市坐标
        83 46;91 38;25 38;24 42;58 69;71 71;74 78;87 76;18 40;13 40;82 7;62 32;58 35;45 21;41 26;44 35;4 50];%30 cities d'=423.741 by D B Fogel
    for i=1:29
        for j=i+1:30
            Len(i,j)=((city(i,1)-city(j,1))^2+(city(i,2)-city(j,2))^2)^0.5;
            Len(j,i)=Len(i,j);
        end
    end
    city_loc=city;
end
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
遗传算法matlab程序(2009-04-14 18:25:19)转载标签: 遗传算法二进制编码if杂谈 遗传算法程序: 说明: 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'); 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):'); 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=pMutation; BestPop=zeros(eranum,n);%分配初始解空间BestPop,Trace Trace=zeros(eranum,length(bits)+1); i=1; while i<=eranum for j=1:m value(j)=feval_r(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; end t=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)<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_r(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=OldPop; %倒位操作 function [NewPop]=Inversion(OldPop,pInversion) global m n NewPop NewPop=OldPop; 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值