简体   繁体   中英

How to print Gaussian curve fitting results?

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.

图片

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?

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.

Take a look here: https://lmfit.github.io/lmfit-py/model.html [see the function result.fit_report()]. You can also add the final parameters to the label of your plot How to return the fit error in Python curve_fit .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM