自动微分在基于问题的优化中的作用
当使用自动微分时,基于问题的 solve
函数通常需要更少的函数计算并且可以更加稳健地运行。
默认情况下,solve
使用自动微分来评估目标和非线性约束函数的梯度(如果适用)。自动微分适用于不使用fcn2optimexpr
函数,而以对优化变量的运算来表达的函数。请参阅Optimization Toolbox 中的自动微分和将非线性函数转换为优化表达式。
最小化问题
考虑最小化以下目标函数的问题:
创建一个表示这些变量和目标函数表达式的优化问题。
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;
最小化受非线性约束 的影响。
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.
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 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.
disp(fvalfd)
-0.5500
disp(outputfd.funcCount)
265
disp(outputfd.iterations)
46
使用有限差分梯度近似会导致 solve
需要进行 269 次函数计算,而之前只需 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
综上所述,自动微分在最优化中的主要作用是减少函数计算的次数。