ga算法

Posted semen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ga算法相关的知识,希望对你有一定的参考价值。

ga算法是模拟生物进化过程中,适者生存,优胜劣汰规则的一种算法,ga算子有选择,交叉,变异,个体对环境的适应度用适应度函数来衡量,每个个体对应一个适应度值,选择算子淘汰劣质个体,交叉和变异产生新个体,个体组成的种群不断进化,直到产生最优个体。

与普通智能算法不同的是ga算法从多个解开始搜索,对多个值同时进行评估,很少会陷入局部最优解,普通智能算法的缺点就是容易陷入局部最优解,例如粒子群算法,每次都只迭代更新一个个体,一旦陷入局部最小值,很难跳出

下面是matlab实现的ga算法

function testga()
size=20;
chromelen=8;
lr=0.8;
mr=0.1;
pop=init(size,chromelen);
pop2=binary2int(pop);
gim=ones(500,8);
for i=1:50
    fitvalue=calfitvalue(pop);
    newpop=selection(pop,fitvalue);
    renewpop=crossover(newpop,lr);
    uppop=mutation(renewpop,mr);
    [bestindividual,bestfit]=best(uppop,fitvalue);
    gim(i,:)=bestindividual;
    y(i)=bestfit;
    pop=uppop;
end
ymax=find(y==max(y));
ymax=max(ymax);
tt=gim(ymax,:);
xmax=binary2int(tt)*2*pi/1023;
plot(xmax,ymax,\'r*\');
hold on;
fplot(\'11*sin(6*x)+7*cos(5*x)\',[-pi,pi]);
end

function pop=init(size,chromelen)
pop=round(rand(size,chromelen));
end

function pop2=binary2int(pop)
[px,py]=size(pop);
for i=1:py
    pop1(:,i)=2.^(py-i).*pop(:,i);
end
pop2=sum(pop1,2);
end

function fitvalue=calfitvalue(pop)
temp=binary2int(pop);
x=temp*2*pi/1023;
fitvalue=11*sin(6*x)+7*cos(5*x);
end

function newpop=selection(pop,fitvalue)
sumfit=sum(fitvalue);
profit=fitvalue/sumfit;
cumpro=cumsum(profit);
[px,py]=size(pop);
randval=sort(rand(px,1));
newin=1;
fitin=1;
while newin<=px
    if randval(newin)<cumpro(fitin)
        newpop(newin,:)=pop(fitin,:);
        newin=newin+1;
    else
        fitin=fitin+1;
    end
end
end

function renewpop=crossover(newpop,lr)
[px,py]=size(newpop);
renewpop=ones(size(newpop));
for i=1:2:px-1
    if rand<lr
        c=round(rand*py);
        renewpop(i,:)=[newpop(i,1:c),newpop(i+1,c+1:py)];
        renewpop(i+1,:)=[newpop(i+1,1:c),newpop(i,c+1:py)];
    else
        renewpop(i,:)=newpop(i,:);
        renewpop(i+1,:)=newpop(i+1,:);
    end
end
end
function uppop=mutation(renewpop,mr)
[px,py]=size(renewpop);
uppop=ones(size(renewpop));
for i=1:px
    if rand<mr
        c=round(rand*py);
        if c<=0
            c=1;
        end
        uppop(i,:)=renewpop(i,:);
        if any(uppop(i,c))==0
            uppop(i,c)=1;
        else
            uppop(i,c)=0;
        end
    else
        uppop(i,:)=renewpop(i,:);
    end
end
end

function [bestindividual,bestfit]=best(uppop,fitvalue)
bestindividual=uppop(1,:);
bestfit=fitvalue(1);
[px,py]=size(uppop);
for i=2:px
    if bestfit<fitvalue(i)
        bestfit=fitvalue(i);
        bestindividual=uppop(i,:);
    end
end
end

 

以上是关于ga算法的主要内容,如果未能解决你的问题,请参考以下文章

基于GA遗传算法的异构网络垂直切换优化算法的matlab仿真

GA TSP基于matlab遗传算法求解旅行商问题含Matlab源码 1909期

遗传算法GA--TSP旅行商问题(Python)

遗传算法GA--计算函数最值(Python)

MATLAB教程案例12基于GA遗传优化算法的函数极值计算matlab仿真及其他应用

ga算法