1
$\begingroup$

I see that the LinearModelFit function can give you the $R^2$ of the best fit, but I already have a model. I want to compare the data to the model (function) and have Mathematica tell me how good a fit it is. That is, I have a function, Mass[r], and I have a bunch of data, data = {{0, 1}, {1, 2}, {2, 4}, {3, 9}}. How can I tell how well Mass[r] matches data?

$\endgroup$
9
$\begingroup$

Here is a possible solution if you already have a model object:

rsquared[list___, model_] := 
 1 - SquaredEuclideanDistance[list[[;; , 2]], 
   model /@ list[[;; , 1]]]/
  SquaredEuclideanDistance[list[[;; , 2]], Mean@list[[;; , 2]]]

Testing for the given data

data = {{0, 1}, {1, 2}, {2, 4}, {3, 9}};
mass = LinearModelFit[data, x, x];
rsquared[data, mass]
(*0.889474*)

Verifying with the built in RSquared functionality

mass["RSquared"]
(*0.889474*)

Alternatively, with any defined function:

model[r_] := 2.6*r
rsquared[data, model]
(*0.888421*)
$\endgroup$
  • $\begingroup$ Thank you. It works like a charm. So just to confirm, there's no built-in Mathematica operation that will do this? It seems so basic. $\endgroup$ – Donald Airey Dec 8 '16 at 11:33
  • $\begingroup$ A quick look around doesn't seem to indicate that there is a built in function. $\endgroup$ – Marchi Dec 8 '16 at 15:18
  • $\begingroup$ For the denominator, you could instead use ((Length[list] - 1) Variance[list[[;;, 2]]]). $\endgroup$ – J. M. is away Dec 10 '16 at 2:28

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.