Getting the r-squared value using curve_fit

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)

Leave a Comment

tech