简体   繁体   English

如何打印高斯曲线拟合结果?

[英]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.我花了一些时间,但我使用下面的代码为我的 x,y 数据集创建了一个高斯拟合。

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?我现在想知道的是如何在我的屏幕上打印出这种拟合的结果,例如拟合最大值点 x 处的最大值、估计误差等?

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 .相关信息包含在变量poptpcov See scipy doc .请参阅scipy 文档 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()].看看这里: https ://lmfit.github.io/lmfit-py/model.html [见函数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 .您还可以将最终参数添加到绘图的标签中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).正如 tagoma 所指出的,您拟合的所有相关信息都包含在 popt(最佳参数)和 pcov(协方差矩阵)中。 In this case, given your set of parameters (a, x0, sigma, offset) you can unpack them as:在这种情况下,给定您的一组参数(a、x0、sigma、offset),您可以将它们解包为:

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).据我所知,curve_fit 不提供卡方或标准差等更多信息,我通常在拟合完成后立即执行所需的计算,只需将所有平方差相加并除以原始值(但更多一个统计的东西)。

Hope it helped.希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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