主要内容

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

自动微分在基于问题的优化中的作用

当使用自动微分时,基于问题的 solve函数通常需要更少的函数计算并且可以更加稳健地运行。

默认情况下,solve 使用自动微分来评估目标和非线性约束函数的梯度(如果适用)。自动微分适用于那些用优化变量的运算来表示的函数。请参阅Optimization Toolbox 中的自动微分将非线性函数转换为优化表达式

最小化问题

考虑最小化以下目标函数的问题:

fun1=100(x2-x12)2+(1-x1)2fun2=exp(-(xi-yi)2)exp(-exp(-y1))sech(y2)objective=fun1-fun2.

创建一个表示这些变量和目标函数表达式的优化问题。

prob = optimproblem;
x = optimvar("x",2);
y = optimvar("y",2);
fun1 = 100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
fun2 = exp(-sum((x - y).^2))*exp(-exp(-y(1)))*sech(y(2));
prob.Objective = fun1 - fun2;

最小化受非线性约束 x12+x22+y12+y224 的影响。

prob.Constraints.cons = sum(x.^2 + y.^2) <= 4;

求解问题并检查求解过程

从初始点开始求解问题。

init.x = [-1;2];
init.y = [1;-1];
[xproblem,fvalproblem,exitflagproblem,outputproblem] = solve(prob,init);
Solving problem using fmincon.

Local minimum found that satisfies the constraints.

Optimization completed because the objective function is non-decreasing in 
feasible directions, to within the value of the optimality tolerance,
and constraints are satisfied to within the value of the constraint tolerance.

<stopping criteria details>
disp(fvalproblem)
   -0.5500
disp(outputproblem.funcCount)
    77
disp(outputproblem.iterations)
    46

output 结构体表明 solve 调用 fmincon,这需要 77 次函数计算和 46 次迭代才能求解问题。解处的目标函数值是 fvalproblem = -0.55

不使用自动微分来求解问题

为了确定自动微分带来的效率提升,请设置 solve 名称值对参量以使用有限差分梯度。

[xfd,fvalfd,exitflagfd,outputfd] = solve(prob,init,...
    ObjectiveDerivative="finite-differences",ConstraintDerivative="finite-differences");
Solving problem using fmincon.

Local minimum possible. Constraints satisfied.

fmincon stopped because the size of the current step is less than
the value of the step size tolerance and constraints are 
satisfied to within the value of the constraint tolerance.

<stopping criteria details>
disp(fvalfd)
   -0.5500
disp(outputfd.funcCount)
   278
disp(outputfd.iterations)
    47

使用有限差分梯度逼近法计算 solve 需要进行约 270 次函数计算,而上一节求解问题并考察解过程中使用自动微分法仅需 77 次函数计算。迭代次数几乎相同,解中报告的目标函数值也是如此。最终解点数相同,显示精度一致。

disp([xproblem.x,xproblem.y])
    0.8671    1.0433
    0.7505    0.5140
disp([xfd.x,xfd.y])
    0.8671    1.0433
    0.7505    0.5140

综上所述,自动微分在最优化中的主要作用是减少函数计算的次数。

另请参阅

主题