How to print Gaussian curve fitting results?

Viewed 626

It took me some time but I have used the code below to create myself a Gaussian fit for my x,y data set.

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def Gauss(x, a, x0, sigma, offset):
    return a * np.exp(-(x - x0)**2 / (2 * sigma**2)) + offset
x, y = np.random.random(100), np.random.random(100)
popt, pcov = curve_fit(Gauss, x, y, p0=[np.max(y), np.median(x), np.std(x), np.min(y)])
plt.plot(x, y, 'b+:', label='data')
x_fit = np.linspace(np.min(x), np.max(x), 1000)
plt.plot(x_fit, Gauss(x_fit, *popt), 'r-', label='fit')
plt.legend()
plt.title('Something')
plt.xlabel('Anotherthing')
plt.ylabel('Athing')
plt.show()

I can see my fit is well done and see the graph and everything.

Image

What I would like to know now is how can I print out the results of this fit on my screen such as the max value at x on fit's max point, the estimated error and etc?

Is these information accessible? If so, is there a way to print out this information? If not, can someone point me to the right direction about finding the error of the fit please?

3 Answers

The relevant information is contained in your variables popt and pcov. See scipy doc. You will be returned an array for each of these variables.

as tagoma pointed out, all the relevant information of your fit is self-contained in popt (optimal parameters) and pcov (covariance matrix). In this case, given your set of parameters (a, x0, sigma, offset) you can unpack them as:

a, x0, sigma, offset = popt;

To unpack their uncertainties, similarly:

ua, ux0, usigma, uoffset = np.sqrt(np.diag(pcov));

(as they are given by their own covariances).

As far as I know, further information like chi square or standard deviations are not provided by curve_fit, and I usually implement the needed calculation just after the fit is done, simply adding up all the square deviations and dividing by original value (but that's more a statistics thing).

Hope it helped.

Related