主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

使用 ga 最小化拉斯特里金函数(基于问题)

此示例说明如何在基于问题的方法中使用遗传算法最小化具有多个最小值的函数。对于两个变量 xy,拉斯特里金函数定义如下。

ras = @(x, y) 20 + x.^2 + y.^2 - 10*(cos(2*pi*x) + cos(2*pi*y));

绘制在每个方向上缩放 10 倍的函数。

rf3 = @(x, y) ras(x/10, y/10);
fsurf(rf3,[-30 30],"ShowContours","on")
title("rastriginsfcn([x/10,y/10])")
xlabel("x")
ylabel("y")

Figure contains an axes object. The axes object with title rastriginsfcn([x/10,y/10]), xlabel x, ylabel y contains an object of type functionsurface.

该函数有许多局部最小值和一个全局最小值 0(位于 x = 0、y = 0 处)。请参阅 什么是全局优化?

创建优化变量 xy。指定变量以 ±100 为界。

x = optimvar("x","LowerBound",-100,"UpperBound",100);
y = optimvar("y","LowerBound",-100,"UpperBound",100);

用目标函数 rastriginsfcn(x) 创建一个优化问题。

prob = optimproblem("Objective",ras(x,y));

注意:如果您的非线性函数不是由多项式、有理式和初等函数(如 exp)组成的,可以使用 fcn2optimexpr 将其转换为优化表达式。请参阅将非线性函数转换为优化表达式优化变量和表达式支持的运算

创建 ga 选项以使用 gaplotbestf 绘图函数。

options = optimoptions("ga","PlotFcn","gaplotbestf");

使用 ga 作为求解器求解该问题。

rng default % For reproducibility
[sol,fval] = solve(prob,"Solver","ga","Options",options)
Solving problem using ga.
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.

Figure Genetic Algorithm contains an axes object. The axes object with title Best: 1.98992 Mean: 1.98992, xlabel Generation, ylabel Fitness value contains 2 objects of type scatter. These objects represent Best fitness, Mean fitness.

sol = struct with fields:
    x: 0.9950
    y: 0.9950

fval = 
1.9899

得到的函数值是最低的最小值吗?再次执行搜索。由于 ga 是随机算法,结果可能会有所不同。

[sol2,fval2] = solve(prob,"Solver","ga","Options",options)
Solving problem using ga.
ga stopped because the average change in the fitness value is less than options.FunctionTolerance.

Figure Genetic Algorithm contains an axes object. The axes object with title Best: 0.994959 Mean: 0.99496, xlabel Generation, ylabel Fitness value contains 2 objects of type scatter. These objects represent Best fitness, Mean fitness.

sol2 = struct with fields:
    x: 0.9950
    y: -4.9289e-06

fval2 = 
0.9950

第二个解更好,因为其函数值更低。ga 返回的解无法保证是全局解。

另请参阅

| |

主题