我使用lsqnonlin作为我的优化例程。我需要绘制每次迭代的成本函数,同时显示所有以前的值。所以我想展示像this这样的东西

然而,使用lsqnonlin,我只能在当前迭代中绘制成本函数的值。使用以下选项:
options = optimset('TolFun', 1e-5, 'TolX',1e-5, 'MaxFunEvals', 10000, 'PlotFcns', @optimplotfval,'Display','iter')有没有办法设置lsqnonlin的选项,使我得到类似上图的内容?
发布于 2017-08-12 06:46:58
如果您查看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的情况下,您似乎获得了给定迭代的残差值的条形图。
对is的修复是基于optimplotfval.m创建自己的绘图函数。将残差复制粘贴到另一个文件中,例如my_opt_plot.m,然后在程序的初始部分更改optimplotfval.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如果将绘制的目标函数值与屏幕上打印的目标函数值进行比较,它们确实是匹配的。
https://stackoverflow.com/questions/45637520
复制相似问题