How to use OutputFcn with fitnlm

7 次查看(过去 30 天)
Hi all,
How do I execute an OutputFcn function in each iteration inside fitlm? I have tried to run the following code but it does not print anything or throw an exception.
load carbig
tbl = table(Horsepower,Weight,MPG);
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + ...
b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
opts = statset("fitnlm");
opts.OutputFcn = @(x)disp(x);
mdl = fitnlm(tbl,modelfun,beta0,"Options",opts);
  1 个评论
dpb
dpb 2024-8-4
fitnlm doesn't document the 'OutputFcn' field in the options list; I'm guessing it's being ignored.
Try nlinfit instead.
This penchant for multiple nearly identical functions is maddening, indeed...
which -all fitnlm
/MATLAB/toolbox/stats/classreg/fitnlm.m
which -all nlinfit
/MATLAB/toolbox/stats/stats/nlinfit.m

请先登录,再进行评论。

回答(1 个)

Matt J
Matt J 2024-8-4
编辑:Matt J 2024-8-5
Only Optimization Toolbox solvers have an OutputFcn option. Perhaps you are thinking of lsqcurvefit,
load carbig
tbl = table(Horsepower,Weight,MPG);
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + ...
b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
opts = optimoptions('lsqcurvefit',OutputFcn=@outfun);
beta1 = lsqcurvefit(modelfun,tbl{:,1:2},tbl{:,3},beta0,"Options",opts);
function stop = outfun(x,optimValues,state)
stop = false;
% Check whether directional derivative norm is less than .01.
if strcmp(state,'iter')
disp(x)
end
end
  3 个评论
Torsten
Torsten 2024-8-5
If statistics for the fitted parameter were accessible when using "lsqcurvefit", it would be mentionned on the documentation page as possible output from the solver:
But it isn't.
Matt J
Matt J 2024-8-5
once you have solved with lsqcurvefit, you can take the solution beta1 and use it for beta0 with fitnlm:
load carbig
tbl = table(Horsepower,Weight,MPG);
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + ...
b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
opts = optimoptions('lsqcurvefit',OutputFcn=@outfun);
beta1 = lsqcurvefit(modelfun,tbl{:,1:2},tbl{:,3},beta0,"Options",opts);
mdl = fitnlm(tbl,modelfun,beta1,"Options",statset("fitnlm"));
You can then use mdl for whatever statistical analysis you had originally planned.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Nonlinear Regression 的更多信息

产品


版本

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by