首页 > 解决方案 > 用curve_fit拟合函数,但拟合曲线错误

问题描述

def gaus(x,a,x0,sigma):
     return a*np.exp(-(x-x0)**2/(2*sigma**2))

times, amplitudes = openFile("../datafiles/number_of_counts.txt")

mean = sum(np.array(times)*np.array(amplitudes))/sum(amplitudes)            
sigma = np.sqrt(sum(np.array(amplitudes)*(np.array(times)-mean)**2)/sum(amplitudes))        

params,pcov = curve_fit(gaus,times, amplitudes,p0=[max(amplitudes),mean,sigma])


plt.plot(times, amplitudes)
plt.plot(times ,gaus(np.array(times),params[0],params[1],params[2]),'r',  label="fitted curve")

plt.ylabel("Coincidents")
plt.title("Coincident plot")
plt.legend()
plt.show()

在此处输入图像描述

我的高斯拟合不能正常工作,但看起来像一条柔软的曲线,而不是为了拟合尖峰,我认为我的脚本中有一些超级愚蠢的错误,但不确定是什么。有谁能看出来?

标签: pythoncurve-fittinggaussian

解决方案


您的数据具有大约 3750 的恒定偏移量,但您的gaus模型函数无法解释这一点,因此您正在拟合偏移量为 0 的正态分布。

它还需要一个参数:

def gaus(x, a, x0, sigma, c):
    return a * np.exp(-(x - x0)**2 / (2 * sigma**2)) + c

然后:

offset_guess = 3750  # maybe calculate it from the data as well
params, pcov = curve_fit(
    gaus, times, amplitudes,
    p0=[max(amplitudes), mean, sigma, offset_guess])

plt.plot(times, gaus(np.array(times), params[0], params[1], params[2], params[3]), ...)

结果:

>>> print(params)
[1545.00193331  -20.45639132  -43.28484495 3792.41050636]

结果图


推荐阅读