# Using FittedModel without clashing symbols

For some FittedModel, the "BestFitParameters" are given in terms of the symbols used to define the model.

fit = NonlinearModelFit[{10,11,12},a*x+c,{a,c},x];
fit["BestFitParameters"]


returns {a->1.,c->9.}

This can be problematic if I define a or c somewhere else. One option is to use the model in a module, and try to localize variables but this generates unique keys that I have to keep track of:

fit=Module[ {a,c}, NonlinearModelFit[{10,11,12},a*x+c,{a,c},x] ];
fit["BestFitParameters"]


returns {a$768206 -> 1., c$768206 -> 9.}

Often I'll do something like

fit=Module[ {a,c,lf},  lf=NonlinearModelFit[{10,11,12},a*x+c,{a,c},x]; {"a"->a,"c"->c}/lf];
fit["BestFitParameters"]


which returns {"a"->1.,"c"->9.} with strings as keys.

I actually prefer this since now "a" and "c" can't clash with a definition of the symbols a or c, but it's a pain because I lose access to the FittedModel object which may be useful later on.

Since I can't use the strings "a" or "c" in the NonlinearModelFit function, my question is this: Is there a way to modify the FittedModel object, such that requesting "BestFitParameters" returns the a list of rules with strings as the keys?

Alternatively, does anyone have a more elegant way of working with these objects, so I don't have to keep track of what symbols I use in fits and make sure not to use the same symbols to define similar values elsewhere?

Why not use formal symbols, e.g., \[FormalA] or \[FormalC]? These symbols are protected, so they should never acquire a value:

fit = NonlinearModelFit[
{10,11,12},
\[FormalA] x + \[FormalC], {\[FormalA], \[FormalC]}, x
];
fit["BestFitParameters"]
fit[3]


• I didn't even know these existed! Thanks for the option. – N.J.Evans Mar 29 at 12:11
• Just a note, you can get a normal characters with esc-$a-esc or \[FormalA], greeks are available too, but you have to spell out the letter, esc-$Beta-esc or \[FormalBeta] - you can't use the character. – N.J.Evans Mar 29 at 12:56

One straightfoward way to handle this is to accept the unique keys generated inside the module and write a function that replaces these with de-unique-ified strings when the best fit parameters are needed:

getBestFit[fit_FittedModel] := Module[
{a, c, bf, newKeys, x, oldkeys},
bf = fit["BestFitParameters"];
oldkeys = Keys@bf;
newKeys = First /@ StringSplit[ToString /@ oldkeys, "\$"];
Rule @@@ Transpose@{newKeys, oldkeys /. bf}
];

fit = Module[
{a, c, x},
NonlinearModelFit[{10, 11, 12}, a*x + c, {a, c}, x]
];
fit["BestFitParameters"]


shows that the unique symbols generated inside the module are retained

{a$$772530 -> 1., c$$772530 -> 9.}


while

getBest@fit


returns the desired rules with strings as keys

{"a"->1.,"c"->9.}