最近在学习用遗传算法计算多元函数极值,在网上查到了一个经典的例子
[img][/img]
有许多种编程方法,但都大同小异,且得到了稳定收敛的结果。截取其中一种如下
%% Do Some Cleaning
clcclear all;close all;%% Set the initial parameters
lbx = -2; ubx = 2;%x belongs to [-2,2]
lby = -2; uby = 2;%y belongs to [-2,2]
%% Plot
figure(1);
ezmesh('y*sin(2*pi*x) + x*cos(2*pi*y)',[lbx,ubx,lby,uby],50);
xlabel('x/X')
ylabel('y/Y')
hold on;
%% Define the parameters of GA
NIND = 40;%size of the group
MAXGEN = 20;%max generations
PRECI = 20;%length of a individual
GGAP = 0.95;%gap
px = 0.7;%the possibility of cross production
pm = 0.01;%the possibility of mutation
trace = zeros(3,MAXGEN);%init value of algorithm寻优函数
FieldD = [PRECI PRECI;lbx lby;ubx uby;1 1;0 0;1 1;1 1];%Field discriber
Chrom = crtbp(NIND,PRECI*2);%creat random discrete group
%% Optimizations
gen = 0;%counter of generations
XY = bs2rv(Chrom,FieldD);%bin to dec
X = XY(:,1);
Y = XY(:,2);
ObjV = Y.*sin(2*pi*X) + X.*cos(2*pi*Y);%cal the f(x,y)
while gen < MAXGEN
FitnV = ranking(-ObjV);%allocate the adaptness
SelCh = select('sus',Chrom,FitnV,GGAP);%select
SelCh = recombin('xovsp',SelCh,px);%recombine
SelCh = mut(SelCh, pm);%mutate
XY = bs2rv(SelCh,FieldD);%bin to dec
X = XY(:,1); Y = XY(:,2);
ObjVSel = Y.*sin(2*pi*X) + X.*cos(2*pi*Y);%cal the next-gen's target f(x)
[Chrom, ObjV] = reins(Chrom, SelCh, 1, 1, ObjV, ObjVSel);%reinsert them to father-gen
XY = bs2rv(Chrom,FieldD);
gen = gen + 1;%counter+=1 %get every gen's answers and it's nums, Y stant for best f(x), I for %nums;
[Y, I] = max(ObjV);
trace(1:2,gen) = XY(I,:);
trace(3,gen) = Y;
end
%% Plot
plot3(trace(1,:),trace(2,:),trace(3,:),'bo');%plot every gen's answergrid on;
plot3(XY(:,1),XY(:,2),ObjV,'b*');hold off%% Plot the evolutionfigure(2);
plot(1:MAXGEN,trace(3,:));
grid on
xlabel('count of generations')y
label('answer')title('procedure')
bestX = trace(1,end)
bestY = trace(2,end)
bestZ = trace(3,end)
然而问题是,无论在matlab上运行哪一个程序,每次收敛的结果都不同,且仅有少数几次收敛到了实例给出的正确结果。我想问一下,这是什么原因,是实例本身就是错误的吗?我尝试改变了其中几个参数的值,算法效果也没有得到明显改善,不知道这是编程的问题, 还是该算法固有的弊端。如果遇到这种每次收敛结果不稳定的情况,该如何解决?