python - 用curve_fit拟合函数,但拟合的曲线错误

标签 python curve-fitting gaussian

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()

enter image description here

我的高斯拟合无法正常工作,但看起来像一条柔和的曲线,而不是拟合尖锐的峰值,我认为我的脚本中有一些 super 愚蠢的错误,但不确定是什么。有谁能看到吗?

最佳答案

您的数据的恒定偏移量约为 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]

resulting plot

关于python - 用curve_fit拟合函数,但拟合的曲线错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60029805/

相关文章:

python - 在 Python 3 和 PyQt 中使用 QProcess.finished()

python - 如何正确地包含与 python 拟合的不确定性

python - 在 Python 中处理超时异常

r - 如何使用非线性函数拟合数据并绘制数据并使用 ggplot() 拟合

python - 为什么调和后的mcmc fit 转换不好?

python - 如何在直方图上绘制高斯分布

java - 三点高斯积分程序

c++ - 如何让高斯模糊正常工作?

Python;如何用各自的 'real' utf-8 替换转义的非 unicode 字符

python - seaborn distplot y 轴密度值在几个 bin 上高于 1.0