遗传算法求函数最大值

遗传算法求函数最大值

目标函数

f ( x ) = 11 s i n ( 6 x ) + 7 c o s ( 5 x ) , x ∈ [ − π , π ] f(x) = 11sin(6x)+7cos(5x), x\in[-\pi,\pi] f(x)=11sin(6x)+7cos(5x),x[π,π]

主程序

clc,clear,close all

lb = -1;
ub = 2;
f = @(x) 11 * sin(6*x) + 7 * cos(5*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

matlab自带遗传算法工具箱调用及结果比较

f2 = @(x) -f(x) ;   
[x,fval] = ga(f2,1,[],[],[],[],lb,ub) %matlab自带遗传算法工具箱
plot(x,-fval,'gd')

相关函数

初始化种群

function pop = initpop(popsize, chromlength)
	pop = round(rand(popsize,chromlength));
end

逆转录(2进制到目标函数值)

逆转录基因

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

计算基因型和表现型(10进制函数自变量及函数值)

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)
	Cmin = 0;
	fitvalue = phenotype + Cmin;
	fitvalue(fitvalue < 0) = 0;
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

猜你喜欢

转载自blog.csdn.net/manmanaa/article/details/95512715