Getting the r-squared value using curve_fit

There seems to be some background about R2 not being implemented directly in scipy.

You can use sklearn.metrics.r2_score.

From your example:

from sklearn.metrics import r2_score
popt, pcov = curve_fit(func, xFit, yFit)
y_pred = func(xFit, *popt)
r2_score(yFit, y_pred)

Computing r_squared:

The r_squared value can be found using the mean (mean), the total sum of squares (ss_tot), and the residual sum of squares (ss_res). Each is defined as:

mean

SStot

SSres

rsquared

where f_i is the function value at point x_i. Taken from Wikipedia.

From scipy.optimize.curve_fit():

  • You can get the parameters (popt) from curve_fit() with

    popt, pcov = curve_fit(f, xdata, ydata)

  • You can get the residual sum of squares (ss_tot) with

    • residuals = ydata- f(xdata, *popt)
    • ss_res = numpy.sum(residuals**2)
  • You can get the total sum of squares (ss_tot) with

    ss_tot = numpy.sum((ydata-numpy.mean(ydata))**2)

  • And finally, the r_squared-value with,

    r_squared = 1 - (ss_res / ss_tot)