遗传算法matlab程序
❶ 求遗传算法的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代码
我发一些他们的源程序你,都是我在文献中搜索总结出来的:
%
下面举例说明遗传算法
%
%
求下列函数的最大值
%
%
f(x)=10*sin(5x)+7*cos(4x)
x∈[0,10]
%
%
将
x
的值用一个10位的二值形式表示为二值问题,一个10位的二值数提供的分辨率是每为
(10-0)/(2^10-1)≈0.01
。
%
%
将变量域
[0,10]
离散化为二值域
[0,1023],
x=0+10*b/1023,
其中
b
是
[0,1023]
中的一个二值数。
%
%
%
%--------------------------------------------------------------------------------------------------------------%
%--------------------------------------------------------------------------------------------------------------%
%
编程
%-----------------------------------------------
%
2.1初始化(编码)
%
initpop.m函数的功能是实现群体的初始化,popsize表示群体的大小,chromlength表示染色体的长度(二值数的长度),
%
长度大小取决于变量的二进制编码的长度(在本例中取10位)。
%遗传算法子程序
%Name:
initpop.m
%初始化
function
pop=initpop(popsize,chromlength)
pop=round(rand(popsize,chromlength));
%
rand随机产生每个单元为
{0,1}
行数为popsize,列数为chromlength的矩阵,
%
roud对矩阵的每个单元进行圆整。这样产生的初始种群。
%
2.2.2
将二进制编码转化为十进制数(2)
%
decodechrom.m函数的功能是将染色体(或二进制编码)转换为十进制,参数spoint表示待解码的二进制串的起始位置
%
(对于多个变量而言,如有两个变量,采用20为表示,每个变量10为,则第一个变量从1开始,另一个变量从11开始。本例为1),
%
参数1ength表示所截取的长度(本例为10)。
%遗传算法子程序
%Name:
decodechrom.m
%将二进制编码转换成十进制
function
pop2=decodechrom(pop,spoint,length)
pop1=pop(:,spoint:spoint+length-1);
pop2=decodebinary(pop1);
%
2.4
选择复制
%
选择或复制操作是决定哪些个体可以进入下一代。程序中采用赌轮盘选择法选择,这种方法较易实现。
%
根据方程
pi=fi/∑fi=fi/fsum
,选择步骤:
%
1)
在第
t
代,由(1)式计算
fsum
和
pi
%
2)
产生
{0,1}
的随机数
rand(
.),求
s=rand(
.)*fsum
%
3)
求
∑fi≥s
中最小的
k
,则第
k
个个体被选中
%
4)
进行
N
次2)、3)操作,得到
N
个个体,成为第
t=t+1
代种群
%遗传算法子程序
%Name:
selection.m
%选择复制
function
[newpop]=selection(pop,fitvalue)
totalfit=sum(fitvalue);
%求适应值之和
fitvalue=fitvalue/totalfit;
%单个个体被选择的概率
fitvalue=cumsum(fitvalue);
%如
fitvalue=[1
2
3
4],则
cumsum(fitvalue)=[1
3
6
10]
[px,py]=size(pop);
ms=sort(rand(px,1));
%从小到大排列
fitin=1;
newin=1;
while
newin<=px
if(ms(newin))
评论
0
0
加载更多
❸ 怎么用遗传算法求一函数的极小值,编写matlab程序。
需要很多的子函数
%子程序:新物种交叉操作,函数名称存储为crossover.m
function scro=crossover(population,seln,pc);
BitLength=size(population,2);
pcc=IfCroIfMut(pc);%根据交叉概率决定是否进行交叉操作,1则是,0则否
if pcc==1
chb=round(rand*(BitLength-2))+1;%在[1,BitLength-1]范围内随机产生一个交叉位
scro(1,:)=[population(seln(1),1:chb) population(seln(2),chb+1:BitLength)]
scro(2,:)=[population(seln(2),1:chb) population(seln(1),chb+1:BitLength)]
else
scro(1,:)=population(seln(1),:);
scro(2,:)=population(seln(2),:);
end
%子程序:计算适应度函数,函数名称存储为fitnessfun.m
function [Fitvalue,cumsump]=fitnessfun(population);
global BitLength
global boundsbegin
global boundsend
popsize=size(population,1);%有popsize个个体
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'+203;
%计算选择概率
fsum=sum(Fitvalue);
Pperpopulation=Fitvalue/fsum;
%计算累计概率
cumsump(1)=Pperpopulation(1);
for i=2:popsize
cumsump(i)=cumsump(i-1)+Pperpopulation(i);
end
cumsump=cumsump';
%子程序:判断遗传运算是否需要进行交叉或变异,函数名称存储为IfCroIfMut.m
function pcc=IfCroIfMut(mutORcro);
test(1:100)=0;
l=round(100*mutORcro);
test(1:l)=1;
n=round(rand*99)+1;
pcc=test(n);
%子程序:新种群变异操作,函数名称存储为mutation.m
function snnew=mutation(snew,pmutation);
BitLength=size(snew,2);
snnew=snew;
pmm=IfCroIfMut(pmutation);%根据变异概率决定是否进行变异操作,1则是,0则否
if pmm==1
chb=round(rand*(BitLength-1))+1;%在[1,BitLength]范围内随机产生一个变异位
snnew(chb)=abs(snew(chb)-1);
end
%子程序:新种群选择操作,函数名称存储为selection.m
function seln=selection(population,cumsump);
%从种群中选择两个个体
for i=1:2
r=rand;%产生一个随机数
prand=cumsump-r;
j=1;
while prand(j)<0
j=j+1;
end
seln(i)=j;%选中个体的序号
end
%子程序:对于优化最大值或极大值函数问题,目标函数可以作为适应度函数
%函数名称存储为targetfun.m
function y=targetfun(x);%目标函数
%子程序:将二进制数转换为十进制数,函数名称存储为transform2to10.m
function x=transform2to10(Population);
BitLength=size(Population,2);
x=Population(BitLength);
for i=1:BitLength-1
x=x+Population(BitLength-i)*power(2,i);
end
k=[0 0.1 0.2 0.3 0.5 1];
for i=1:1:5
%主程序:用遗传算法求解targetfun.m中目标函数在区间[-2,2]的最大值
clc;
clear all;
close all;
global BitLength
global boundsbegin
global boundsend
bounds=[-2 2];%一维自变量的取值范围
precision=0.0001;%运算精度
boundsbegin=bounds(:,1);
boundsend=bounds(:,2);
%计算如果满足求解精度至少需要多长的染色体
BitLength=ceil(log2((boundsend-boundsbegin)'./precision));
popsize=50;%初始种群大小
Generationmax=12;%最大代数
pcrossover=0.90;%交配概率
pmutation=0.09;%变异概率
%产生初始种群
population=round(rand(popsize,BitLength));
%计算适应度值,返回Fitvalue和累计概率cumsump
[Fitvalue,cumsump]=fitnessfun(population);
Generation=1;
while Generation<Generationmax+1
for j=1:2:popsize
%选择操作
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);
fmean=mean(Fitvalue);
ymax(Generation)=fmax;
ymean(Generation)=fmean;
%记录当前代的最佳染色体个体
x=transform2to10(population(nmax,:));
%自变量取值范围是[-2 2],需要把经过遗传运算的最佳染色体整合到[-2 2]区间
xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)-1);
xmax(Generation)=xx;
Generation=Generation+1;
end
Generation=Generation-1;
Bestpopuation=xx;
Besttargetfunvalue=targetfun(xx);
%绘制经过遗传运算后的适应度曲线。一般地,如果进化过程中种群的平均适应度与最大适
%应度在曲线上有相互趋同的形态,表示算法收敛进行得很顺利,没有出现震荡;在这种前
%提下,最大适应度个体连续若干代都没有发生进化表明种群已经成熟
figure(1);
hand1=plot(1:Generation,ymax);
set(hand1,'linestyle','-','linewidth',1.8,'marker','*','markersize',6)
hold on;
hand2=plot(1:Generation,ymean);
set(hand2,'color','r','linestyle','-','linewidth',1.8,'marker','h','markersize',6)
xlabel('进化代数');ylabel('(最大/平均适应度)');xlim([1 Generationmax]);
legend('最大适应度','平均适应度');
box off;hold off;
y=(x(i)-k(i))^2-10*sin(2*pi*(x(i)-k(i)))+10;
end
❹ matlab,遗传算法,求大佬帮忙
用遗传算法求最大值问题,可以这样来解决。
1、将最大值问题转换为最小值问题,即 max Z =- min Z;
2、建立其自定义函数,即
z=-(f1*40^1.5/1+f2*30^1.5/2+f2*20^1.5/2+。。。+f12*127^1.5/2+f12*5^1.5/4)
其中:f1,f2,f3,。。。f11,f12为0,1变量,可以用sign()符号函数来处理。
3、用遗传算法ga()函数求解,使用方法
objectivef=@ga_func;
nvars=12;
[x, fval] =ga(objectivef,nvars)
4、编程运行后得到
f1=1,f2=1,f3=1,f4=0,f5=1,f6=0,f7=1,f8=1,f9=1,f10=1,f11=1,f12=1
Zmax=27329.5018
❺ matlab遗传算法程序
在matlab里没有
for
i
=
1
to
80
...
endfor
这样的语法的
在matlab里应该是:
for
i
=
1:
1:
80
...
end
1:1:80
第一个1是初始值,第二个是每次+1的意思
当然如果是我古若寡闻那也请见谅~~哈哈~~
❻ MATLAB遗传算法编程(多目标优化)
多目标是通过分布性 和非劣解来进行评价的
❼ 遗传算法的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实现
function [x fx string]=fun_SuiJiSuanFa2(N,genLenth,Pc,Pm,downbound,upbound,generation)
%[x fx string]=fun_SuiJiSuanFa2(6,16,0.7,0.01,-3,3,100)
%f 表示函数
%N表示染色体种群大小
%genLenth表示染色体长度
%Pc表示交叉概率
%Pm表示突变概率
%downbound
%upbound
%generation循环代数
%进制编码,此处编写为二进制
num=2;
initdata=randi([0 num-1],N,genLenth);
%二进制编码的权值
weight=(num).^(genLenth/2-1:-1:0);
weights=repmat(weight,N,1);
%保存每代的最好值和平均值,
meanally=zeros(1,generation);
maxally=zeros(1,generation);
Nowx=zeros(generation,genLenth);
for k=1:generation
%解码后的整数
allx1=sum(initdata(:,1:genLenth/2).*weights,2);
allx2=sum(initdata(:,genLenth/2+1:end).*weights,2);
%映射到取值范围
delt=(upbound-downbound)/(num^(genLenth/2)-1);
allx1=allx1.*delt+downbound;
allx2=allx2.*delt+downbound;
%染色体的适应性
ally=f(allx1,allx2);
%平均值,最大值
meanally(k)=mean(ally);
maxally(k)=max(ally);
%找下标,确定是哪条染色体
index=find(ally==maxally(k));
Nowx(k,:)=initdata(index(1),:);
%最大值没有提高就取上次的
if(k>=2&&maxally(k)<maxally(k-1))
maxally(k)=maxally(k-1);
Nowx(k,:)=Nowx(k-1,:);
end
%染色体的适应性比率
ratio=ally./sum(ally);
%交叉,变异
%??交叉几个,从第几个开始。
%此处只交叉1个(总共才6个),随机给一个。
sumRatio=cumsum(ratio);
data=zeros(N,genLenth);
for i=1:N/2
Select1=find(sumRatio>=rand);
Select2=find(sumRatio>=rand);
data(2*i-1,:)=initdata(Select1(1),:);
data(2*i,:)=initdata(Select2(1),:);
if(rand<Pc)
%交叉
location=randi([1,genLenth]);
temp=data(2*i-1,location:end);
data(2*i-1,location:end)=data(2*i,location:end);
data(2*i,location:end)=temp;
else
%变异
if(rand<Pm)
location=randi([1,genLenth]);
data(2*i-1,location)=1-data(2*i-1,location);
end
if(rand<Pm)
location=randi([1,genLenth]);
data(2*i,location)=1-data(2*i,location);
end
end
end
initdata=data;
end
fx=max(maxally);
lastIndex=find(maxally==fx);
string=Nowx(lastIndex(1),:);
x(1)=sum(string(1:genLenth/2).*weight).*(upbound-downbound)/(num^(genLenth/2)-1)+downbound;
x(2)=sum(string(1+genLenth/2:end).*weight).*(upbound-downbound)/(num^(genLenth/2)-1)+downbound;
%绘制性能图
%figure,hold on;
clf;figure(1),hold on;
plot((1:k)',meanally,'b.-');
plot((1:k)',maxally,'r.:');
end
function fun=f(x,y)
fun=(1-x).^2.*exp(-x.^2-(1+y).^2)-(x-x.^3-y.^3).*exp(-x.^2-y.^2);
%fun=-(x-1).^2-3.*(y-2).^2+100;
end
❾ 关于在matlab里实现遗传算法
遗传算法在matlab里有两个函数,分别是ga和gaoptimset,前者用来调用遗传算法,后者用来设定遗传算法的参数,具体内容可以doc
ga查看,遗传算法有哪些参数可以直接在命令窗口输入gaoptimset查看,祝好。
❿ 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]);