遗传算法(Genetic Algorithm)是常用的智能算法的一种,遗传算法GA(Genetic Algorithm)入门知识梳理 对GA进行了详尽的基本介绍,其结尾附的七个链接也让人很有启发。本文附上自己对遗传算法的学习理解与代码实现。
//挖坑
根据遗传算法基础知识,写出伪代码如下:
Initialization();
while less than maximum iterations
Crossover(parent, pCross) -> childrenCross
Mutation(parent, pMutation) -> childrenMutate
[childrenCross; cihldrenMutate] -> children
Calculate the fitness of children
select(children) -> parent
if Satisfy terminal condition
break
end
end
整体思路可以说是比较简单,生成种群->交叉、变异->遗传(自然选择)->下一代。生成种群需要一定的编码技巧(挖坑,以后填)。
下面给出具体MATLAB代码实现:
%%
%编码方式: 基本二进制编码
%Input: FitFunc: Any function
% pCrossover: probability of crossover, default 0.5
% pMutation: probability of mutation, default 0.04
% GroupNum: number of individuals of the virtual group, default 30
% MaxIter: maximum iterations
% MaxRepeat: (optional)determine the convergence standard 判断收敛
%parent.fitness
%parent.chrom
function Result = MyGA(FitFunc, pCrossover, pMutation, GroupNum, MaxIter, MaxRepeat)
%Default parameters
if nargin < 6
MaxRepeat = 10;
if nargin < 5
MaxIter = 1000;
if nargin < 4
GroupNum = 50;
if nargin < 3
pMutation = 0.04;
if nargin < 2
pCrossover = 0.5;
end
end
end
end
end
Result = [];
epsilon = 1e-5;
iter = 0;
iRepeat = 1;
bit = 22;
thisMax = 0;
parent = InitGroup(GroupNum, FitFunc, bit); %Generate initial populati