1
$\begingroup$

I'm generating a simple linear model ($y=mx+b$) by fitting to the background of some data, and then trying to plug in the x-values of the data I'm actually interested in.

I'm a bit surprised that FittedModels aren't listable, so I tried using Map. This turned out to be exceedingly slow. For example:

lm = LinearModelFit[Table[{x, 3 x + 6.2}, {x, 100}], x, x];
AbsoluteTiming[lm/@Range[300000];]
AbsoluteTiming[3 Range[300000] + 6.2;]
AbsoluteTiming[3 # + 6.2&/@Range[300000];]
AbsoluteTiming[Normal[lm]/.x -> Range[300000];]
(* {25.037, Null} *)
(* {0.002096, Null} *)
(* {0.010351, Null} *)
(* {0.004413, Null} *)

Using Normal seems to be the fastest way of using the linear model. Is this really the best way to extract values from a FittedModel?

What is the best (or most usual) way to extract many values from a model?

This seems like it would be a common problem, so I'm certain there must be something about it either here or elsewhere, but perhaps I'm not using the correct search terms.

$\endgroup$
4
$\begingroup$

Use lm["Function"]. (It is also listable in this case.)

lm = LinearModelFit[Table[{x, 3 x + 6.2}, {x, 100}], x, x];

AbsoluteTiming[res1 = lm["Function"] /@ Range[300000];]

(* {0.007482, Null} *)

AbsoluteTiming[res1a = lm["Function"][Range[300000]];]

(* {0.001949, Null} *)

AbsoluteTiming[res2 = lm /@ Range[300000];]

(* {21.0912, Null} *)

res1 == res1a == res2

(* True *)
$\endgroup$
  • $\begingroup$ This seems like it's probably the way that it's meant to be used. I either didn't see "Function" in the list of properties or didn't understand what it was meant to be used for. Thanks! $\endgroup$ – MassDefect Sep 6 at 16:01
  • $\begingroup$ Yeah, the function page of LinearModelFit is pretty big... $\endgroup$ – Anton Antonov Sep 6 at 16:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.