我在 MATLAB 中编写了一个脚本来生成遗传算法。问题是我不知道为什么算法会快速收敛。事实上,它在第一次迭代中收敛。我不知道我的主脚本或我写的“Crossover”和“Mutation”函数哪里错了。我使用过“单点交叉”和“二进制突变”。以下代码如下:
function [y1,y2] = SinglePointCv(p1,p2)
nVar = numel(p1);
CutPoint = randi([1,nVar-1]);
y1 = [p1(1:CutPoint),p2(CutPoint+1:end)]; % Vector of First Children
y2 = [p2(1:CutPoint),p1(CutPoint+1:end)]; % Vector of Second Children
end
function Child = Binary_Mutation(Parent)
nVar = numel(Parent); % Number of Variables
Index = randi([1,nVar]);
Child = Parent;
Child(Index) = 1-Parent(Index); % Binary Mutation
end
主要脚本如下:
% { My Simple Binary GA }
%% Initialization
nPop = 46;
nVar = 4;
pc = 0.6; % X_Rate
pm = 0.2; % Mut_Rate
nc = 2*round(pc*nPop); % Selected Population for CrossOver
nm = 2*round(pm*nPop); % Selected Population for Mutation
CostFunction = @(x) 1-sum(x.^2);
f = CostFunction;
popSize = [nPop,nVar];
pop = randi([0,1],popSize); % Each Row is a Chromosome with nVar Variables
Costs = f(pop');
% Sort Costs
[Costs,SortIndex] = sort(Costs);
pop = pop(SortIndex,:);
MaxIter = 100; % Maximum Iteration
BestCosts = zeros(1,MaxIter);
%% Main Loop
for i=1:MaxIter
OffSprings = cell(nc/2,2);
OffSprings_Costs = zeros(nc/2,2);
%% CrossOver
for k=1:nc/2
Index_For_Parents = randsample(nPop,2);
% Indices for Both Parents
I1 = Index_For_Parents(1);
I2 = Index_For_Parents(2);
% Selected Parents for Xover
Parent1 = pop(I1,:);
Parent2 = pop(I2,:);
% Children Vectors
[OffSprings{k,1},OffSprings{k,2}] = SinglePointCv(Parent1,Parent2);
OffSprings_Costs(k,1) = f(OffSprings{k,1});
OffSprings_Costs(k,2) = f(OffSprings{k,2});
end
OffSprings = reshape(OffSprings,[],1);
OffSprings_Costs = reshape(OffSprings_Costs,[],1);
Off = zeros(size(OffSprings,1),nVar);
for Mat = 1:size(OffSprings,1)
Off(Mat,:) = OffSprings{Mat};
end
OffSprings = Off;
Mutants = zeros(nm,nVar);
Mutants_Costs = zeros(nm,1);
%% Mutation
for j = 1:nm
Parent_Index = randi([1,nPop]); % Mutation Parent Index
Parent = pop(Parent_Index,:); % Selected Parent For Mutation
Mutants(j,:) = Binary_Mutation(Parent);
Mutants_Costs(j) = f(Mutants(j,:));
end
%% Merge, Sort, Truncate
% Merge
pop=[pop
OffSprings
Mutants];
pop_Costs = [Costs'
OffSprings_Costs
Mutants_Costs]; % The vEctor Of Costs vALues
% Sort
[SortedCosts,SortOrder] = sort(pop_Costs);
pop = pop(SortOrder,:);
% Truncate
pop = pop(1:nPop,:);
BestSolution = pop(1,:); % First Row is the Best ANswer
BestCosts(i) = SortedCosts(1);
end
plot(BestCosts,'k','LineWidth',2)
grid on