遗传算法求最大值
主程序
clc,clear,close all
lb = -1;
ub = 2;
%f = @(x) 11 *
sin(6*x) + 7 * cos(5*x);
f = @(x) 10 + x.*cos(5*pi*x);
popsize = 20;
chromlength = 16;
pc = 0.7;
pm = 0.02;
generation = 20;
pop = initpop(popsize,chromlength);
fplot(f,[lb,ub])
hold on
BestIndividual =
zeros(generation,1);
BestFitness = zeros(generation,1);
for i
= 1:generation
[~,phenotype] =
gene2pheno(pop,f,lb,ub,chromlength);
fitvalue =
fitness(phenotype,popsize);
pop = select(pop,fitvalue);
pop = crossover(pop,pc);
pop = mutate(pop,pm);
[BestIndividual(i),BestFitness(i)] =
FindBest(pop,f,lb,ub,chromlength);
disp(['第',num2str(i),'代'])
disp(['最大值点:',num2str(BestIndividual(i))])
disp(['最大值:',num2str(BestFitness(i))])
plot(BestIndividual(i),BestFitness(i),'r*')
end
f2 = @(x) -f(x) ;
[x,fval] = ga(f2,1,[],[],[],[],lb,ub) %matlab自带遗传算法工具箱
x = 2.0000
fval = -12.0000
plot(x,-fval,'gd')
xlim('auto')
ylim('auto')
初始化种群
function
pop = initpop(popsize, chromlength)
pop =
round(rand(popsize,chromlength));
end
由基因型计算表现型
基因逆转录
function
pop2 = decodebinary(pop)
py = size(pop,2);
pop1 = pop*2.^(0:(py-1))';
pop2 = sum(pop1,2);
end
染色体逆转录
function
pop2 = decodechrom(pop,spoint,genelength)
pop1 = pop(:,spoint:spoint + genelength -
1);
pop2 = decodebinary(pop1);
end
计算表现型
function
[genetype,phenotype] = gene2pheno(pop,f,lb,ub,chromlength)
temp1 =
decodechrom(pop,1,chromlength);
genetype = lb + (ub-lb)/(2^chromlength-1)
*temp1;
phenotype = f(genetype);
end
计算个体适应度
function
fitvalue = fitness(phenotype,popsize)
Cmin = 0;
fitvalue = zeros(popsize,1);
for i
= 1:popsize
if
phenotype(i) + Cmin > 0
fitvalue(i) = Cmin + phenotype(i);
end
end
end
选择复制
function
newpop = select(pop,fitvalue)
fitvalue =
cumsum(fitvalue/sum(fitvalue));
px = size(pop,1);
newpop = pop;
SelectRate = sort(rand(px,1));
FitIdx = 1;
NewIdx = 1;
while
NewIdx <= px
if
SelectRate(NewIdx) < fitvalue(FitIdx)
newpop(NewIdx,:) = pop(FitIdx,:);
NewIdx = NewIdx + 1;
else
FitIdx = FitIdx + 1;
end
end
end
交叉
function
newpop = crossover(pop,pc)
[px,py] = size(pop);
newpop = pop;
for i
= 1:2:px-1
if
rand < pc
cpoint = ceil(rand * py);
newpop(i,cpoint+1:end) =
pop(i+1,cpoint+1:end);
newpop(i+1,cpoint+1:end) =
pop(1,cpoint+1:end);
end
end
end
变异
function
newpop = mutate(pop,pm)
[px,py] = size(pop);
newpop = pop;
for i
= 1:px
if(rand < pm)
mpoint = ceil(rand * py);
newpop(i,mpoint) = ~pop(i,mpoint);
end
end
end
求出最大适应值及个体
function
[BestIndividual,BestFitness] = FindBest(pop,f,lb,ub,chromlength)
[genetype,phenotype] =
gene2pheno(pop,f,lb,ub,chromlength);
[BestFitness, BestIdx] =
max(phenotype);
BestIndividual = genetype(BestIdx);
end
本文由 joe_zhouman 创作,采用 知识共享署名4.0
国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:2019-07-10 19:25:23