【发布时间】:2017-08-07 12:38:30
【问题描述】:
我现在多次偶然发现使用scipy.curve_fit 在 python 中进行拟合比使用其他工具(例如根(https://root.cern.ch/)
对应代码:
def fit_gauss(y, x = None):
n = len(y) # the number of data
if x is None:
x = np.arange(0,n,1)
mean = y.mean()
sigma = y.std()
def gauss(x, a, x0, sigma):
return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2))
popt, pcov = curve_fit(gauss, x, y, p0=[max(y), mean, sigma])
plt.plot(x, y, 'b+:', label='data')
plt.plot(x, gauss(x, *popt), 'ro:', label='fit')
plt.legend()
plt.title('Gauss fit for spot')
plt.xlabel('Pixel (px)')
plt.ylabel('Intensity (a.u.)')
plt.show()
同样,对应的代码:
import ROOT
import numpy as np
y = np.array([2., 2., 11., 0., 5., 7., 18., 12., 19., 20., 36., 11., 21., 8., 13., 14., 8., 3., 21., 0., 24., 0., 12., 0., 8., 11., 18., 0., 9., 21., 17., 21., 28., 36., 51., 36., 47., 69., 78., 73., 52., 81., 96., 71., 92., 70., 84.,72., 88., 82., 106., 101., 88., 74., 94., 80., 83., 70., 78., 85., 85., 56., 59., 56., 73., 33., 49., 50., 40., 22., 37., 26., 6., 11., 7., 26., 0., 3., 0., 0., 0., 0., 0., 3., 9., 0., 31., 0., 11., 0., 8., 0., 9., 18.,9., 14., 0., 0., 6., 0.])
x = np.arange(0,len(y),1)
#yerr= np.array([0.1,0.2,0.1,0.2,0.2])
graph = ROOT.TGraphErrors()
for i in range(len(y)):
graph.SetPoint(i, x[i], y[i])
#graph.SetPointError(i, yerr[i], yerr[i])
func = ROOT.TF1("Name", "gaus")
graph.Fit(func)
canvas = ROOT.TCanvas("name", "title", 1024, 768)
graph.GetXaxis().SetTitle("x") # set x-axis title
graph.GetYaxis().SetTitle("y") # set y-axis title
graph.Draw("AP")
有人可以向我解释一下,为什么结果差异如此之大? scipy 中的实现是否糟糕/依赖于良好的启动参数? 有什么办法吗?我需要自动处理很多拟合,但在目标计算机上无权访问 ROOT,因此它只能与 python 一起使用。
当从 ROOT 拟合中获取结果并将它们作为起始参数提供给 scipy 时,拟合也适用于 scipy...
【问题讨论】:
-
您在第二个代码示例中提供的数据得到了很好的输出(请参阅下面的答案)。
标签: python scipy curve-fitting gaussian