遗传算法是最优化算法的一种,具体算法步骤如下:
(1) 首先,预先设定染色体数目GeneSize, 基因的最大最小范围maxGene/minGene, 变异概率mutepro, 交叉概率crosspro,迭代次数iterate_num,并定义适应值函数。
(2)然后,根据基因范围,初始化染色体,并计算所有染色体的适应值。
(3)接下来,根据染色体适应值,对染色体进行选择。常用的选择算法有下几种:
1.轮盘赌算法:轮盘赌算法原理,相当于将一个圆盘,根据每个染色体适应值占适应值之和的比例进行划分,然后随机选择。适应值越高的,有更大的几率被选择。每个染色体的选择概率:
function [BestGene] = GeneticAgorithm(MaxGeneration, GeneSize, Data, Label, MaxGene, MinGene, CrossPro, MutePro)
%遗传算法用于特征选择或参数寻优
%返回说明:最优解
%参数说明:MaxGeneration ----最大迭代数
% GeneSize ---- 基因数目
% Data ---- 数据集
% Label ---- 数据值
% MaxGene ---- 最大基因值
% MinGene ---- 最小基因值
global Maxg
Maxg = MaxGene;
global Ming
Ming = MinGene;
[~,GeneNum] = size(Data);
ValParents = zeros(GeneSize,1);
Children = zeros(GeneSize,GeneNum);
%%第一步:初始化基因,并计算适应值
Parents = rand(GeneSize,GeneNum).*(MaxGene-MinGene)+MinGene;
for j = 1:MaxGeneration
for i = 1:GeneSize
ValParents(i,1) = fitness(Data, Label, Parents(i,:));
end
%%第二步:轮盘赌,选择适应值高基因
SelectedParents = GAchoose(Parents, ValParents);
%%第三步:选择相邻的个体进行交叉,交叉采用单点交叉
for i = 1:GeneSize/2
Children(2*i-1:2*i,:) = GAcross(SelectedParents(2*i-1,:),SelectedParents(2*i,:),CrossPro);
end
%%第四步:个体变异,采用
for i = 1:GeneSize
Children(i,:) = GAmute(Children(i,:),mutepro);
end
Parents = Children;
end
end
function Children = GAchoose(Parents, ValParents)
%UNTITLED 轮盘赌算法进行父代选择
% parents 父代
% fitness 适应值
Children = zeros(size(Parents));
SelectPro = ValParents./sum(ValParents); %选择概率
val = 0;
for i = 1:GeneSize
val = val + SelectPro(i);
CumulaPro = val; %累计概率
end
for i = 1:GeneSize
k = find(CumulaPro>rand, 1, first);
Children(i,:) = Parents(k,:);
end
end
function [Child1, Child2] = GAcross(Parent1, Parent2, pro)
%UNTITLED3 杂交函数, 单点交叉
% Parent1 ---- 父1
% Parent2 ---- 父2
% pro ---- 杂交概率,如果小于这个概率就进行杂交
if(rand < pro)
num = length(Parent1);
location = round(rand*num);
if(location ~=1 && location ~=0)
Child1 = [Parent1(1:location), Parent2(location+1:end)];
Child2 = [Parent2(1:location), Parent1(location+1:end)];
end
end
function child = GAmute(child, mutepro)
%UNTITLED 这里采用均匀变异算子
% 此处显示详细说明
global Maxg Ming;
if(randround(rand*length(child))+1;
if(location<length(child))
child(location)=rand*(Maxg(location)-Ming(location))+Ming(location);
end
end
end