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 :
The value can be found using the mean (), the total sum of squares (), and the residual sum of squares (). Each is defined as:
where is the function value at point . Taken from Wikipedia.
From scipy.optimize.curve_fit()
:
You can get the parameters (
popt
) fromcurve_fit()
withpopt, pcov = curve_fit(f, xdata, ydata)
You can get the residual sum of squares () with
residuals = ydata- f(xdata, *popt)
ss_res = numpy.sum(residuals**2)
You can get the total sum of squares () with
ss_tot = numpy.sum((ydata-numpy.mean(ydata))**2)
And finally, the -value with,
r_squared = 1 - (ss_res / ss_tot)