遗传算法,结合生物学遗传规则用于问题最优解求解,具有广泛的用途。
然而,由于其属于不确定性算法,故在搜索性能和最优解的稳定性上仍有待改善。
利用Matlab的遗传算法,编写代码如下:
function [ output_args ] = ga_test
clear;
%解:X = [0, 0, ...]
%nVar = 30
%dims: [-30, 30]
function fitness = sphere(vals)
prod = vals .* vals;
fitness = sum(prod, 2);
end
%f(x) = 1/4000 * sum^n_1(x_i)^2 - prod^n_1 * cos(x_i/sqrt(i)) + 1
%f* = 0, x* = [0, 0, ...];
%nVar = 30
%dims: [-600, 600]
function fitness = griewank(vals)
[h w] = size(vals);
p1 = vals.^2;
p1 = 1/4000 .* sum(p1, 2);
t = sqrt([1:w]);
p2 = vals ./ repmat(t, h, 1);
p2 = cos(p2);
p2 = prod(p2, 2);
fitness = p1 - p2 + 1;
end
%解: X* = [1, 1, 1, ...]
%nVar: 30
function fitness = RosenBroek(vals)
[k n] = size(vals);
vals1 = vals(:, 1:n-1);
vals2 = vals(:, 2:n);
tmp = vals2 - vals1 .* vals1;
tmp = 100 * tmp .* tmp;
tmp1 = (vals1 - 1).^2;
fitness = sum(tmp, 2) + sum(tmp1, 2);
end
%许多局部最小值,最优解:X = [0, 0], 固定2个变量
%nVar = 2
function fitness = Rastrigin (X)
v = X.^2 - 10 .* cos(2 * pi .* X) + 10;
fitness = sum(v, 2);
end
%参数
popSize = 50; % 群规模
Run = 4; % 测试轮次
option = gaoptimset('PopulationSize', popSize); %, 'UseParallel', true);
Ans = {};
for r = 1:Run %轮次
Func = r; % 测试适应度函数
switch Func
case 1
Func = @sphere
Xmin = -100;
Xmax = 100;
nVar = 30;
case 2
Func = @griewank
Xmin = -600;
Xmax = 600;
nVar = 30;
case 3
nVar = 30;
Func = @RosenBroek
Xmin = -100;
Xmax = 100;
case 4
nVar = 2;
Func = @Rastrigin
Xmin = -5.12;
Xmax = 5.12;
end;
tic;
[Ans{r}.bestGene, Ans{r}.bestFit] = ga(Func, nVar, [], [], [], [], repmat(Xmin, nVar, 1), repmat(Xmax, nVar, 1), [], option);
costt = toc
Ans{r}.costtime = costt;
end %可运行30轮,查看结果
for r = 1:Run
fprintf('fit=%f, costtime=%f(s) \n', Ans{r}.bestFit, Ans{r}.costtime);
%Ans{r}.bestGene
end;
end
运行结果:
Func =
@ga_test/sphere
Optimization terminated: average change in the fitness value less than options.TolFun.
costt =
4.2468
Func =
@ga_test/griewank
Optimization terminated: average change in the fitness value less than options.TolFun.
costt =
4.2952
Func =
@ga_test/RosenBroek
Optimization terminated: maximum number of generations exceeded.
costt =
14.4236
Func =
@ga_test/Rastrigin
Optimization terminated: average change in the fitness value less than options.TolFun.
costt =
0.2880
fit=0.000100, costtime=4.246814(s)
fit=0.000150, costtime=4.295222(s)
fit=1.511176, costtime=14.423554(s)
fit=0.000000, costtime=0.288025(s)
从运行时间来看,算法的性能不好。
故类似遗传算法、微分进化等方法,仍有待提出新的机制和算法以解决此类问题。