我正在lsqnonlin
用作我的优化例程。我需要在每次迭代时绘制成本函数,同时显示所有先前的值。所以我想展示一些东西像这样:
但是,使用lsqnonlin
,我只能在当前迭代中绘制成本函数的值。使用这些选项:
options = optimset('TolFun', 1e-5, 'TolX',1e-5, 'MaxFunEvals', 10000, 'PlotFcns', @optimplotfval,'Display','iter')
有没有办法设置选项,lsqnonlin
以便我得到类似于上图所示的内容?
如果您查看程序optimplotfval.m
(在 MATLAB 的终端中输入,edit optimplotfval.m
您将看到以下注释:
% STOP = OPTIMPLOTFVAL(X,OPTIMVALUES,STATE) plots OPTIMVALUES.fval. If
% the function value is not scalar, a bar plot of the elements at the
% current iteration is displayed. If the OPTIMVALUES.fval field does not
% exist, the OPTIMVALUES.residual field is used.
因此,例如,fminsearch
您将获得目标/成本函数值与迭代次数的图,但在这种情况下,lsqnonlin
您似乎在给定迭代中获得残差值的条形图。
解决方法是基于optimplotfval.m
. 复制粘贴optimplotfval.m
到另一个文件中,例如,my_opt_plot.m
然后更改程序初始部分中的剩余选项:
stop = false;
switch state
case 'iter'
if isfield(optimValues,'fval')
if isscalar(optimValues.fval)
plotscalar(optimValues.iteration,optimValues.fval);
else
plotvector(optimValues.iteration,optimValues.fval);
end
else
% Plot the squared norm of residuals as a function of iteration number instead of bar plot of residual values at current iteration
fval = norm(optimValues.residual)^2;
% Call the scalar function instead
plotscalar(optimValues.iteration,fval);
end
您可以使用与调用相同的方式调用此新函数optimplotfval.m
:
options = optimoptions('lsqnonlin','Display','iter','PlotFcns',@my_opt_plot);
[x,resnorm,residual,exitflag,output] = lsqnonlin(@simple_fun,xc0,[],[],options);
在我的例子中 simple_fun 基于 MATLAB 文档条目中的一个示例lsqnonlin
:
function f = simple_fun(xc)
x = [0.9 1.5 13.8 19.8 24.1 28.2 35.2 60.3 74.6 81.3];
y = [455.2 428.6 124.1 67.3 43.2 28.1 13.1 -0.4 -1.3 -1.5];
f = xc(1)*exp(xc(2)*x)-y;
end
如果将绘制的目标函数值与打印在屏幕上的目标函数值进行比较,它们确实匹配。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句