It is not possible to obtain the value of chi^2 from scipy.optimize.curve_fit
directly without manual calculations. It is possible to get additional output from curve_fit
besides popt
and pcov
by providing the argument full_output=True
, but the additional output does not contain the value of chi^2. (The additional output is documented e.g. at leastsq
here).
In the case where sigma
is a MxM array, the definition of the chi^2 function minimized by curve_fit is slightly different.
In this case, curve_fit
minimizes the function r.T @ inv(sigma) @ r
, where r = ydata - f(xdata, *popt)
, instead of chisq = sum((r / sigma) ** 2)
in the case of one dimensional sigma
, see the documentation of the parameter sigma
.
So you should also be able to calculate chi^2 in your case by using r.T @ inv(sigma) @ r
with your optimized parameters.
An alternative would be to use another package, for example lmfit, where the value of chi square can be directly obtained from the fit result:
from lmfit.models import GaussianModel
model = GaussianModel()
# create parameters with initial guesses:
params = model.make_params(center=9, amplitude=40, sigma=1)
result = model.fit(n, params, x=centers)
print(result.chisqr)