scipy.optimize.curve_fit 尝试对数据进行高斯拟合时出现奇怪的行为

scipy.optimize.curve_fit weird behaviour when trying to fit gaussian to data

我必须对某些数据拟合高斯曲线。这是我的高斯

的定义
def gaussian(x,sigma,mu):
  return np.array((1/(sigma*np.sqrt(2*np.pi)))*np.exp((-1/2)*np.power(((x-mu)/sigma),2)),dtype='float64')

这是我对高斯函数定义的测试

x = np.linspace(-5,5,100)
y = gaussian(x,1,0)
plt.plot(x,y)

它产生了一个行为正确的情节, here is the image of the plot

现在我必须将这个高斯分布拟合到一些数据。

x = np.array([ 8., 10., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.,
       23., 24., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35.,
       36.],dtype='float64')
y = np.array([0.00220264, 0.00220264, 0.00220264, 0.00220264, 0.0154185 ,
       0.01321586, 0.02863436, 0.03303965, 0.06387665, 0.05506608,
       0.1123348 , 0.08590308, 0.0814978 , 0.0814978 , 0.04625551,
       0.06387665, 0.05726872, 0.05947137, 0.05726872, 0.02863436,
       0.03744493, 0.02863436, 0.01101322, 0.00881057, 0.01101322,
       0.00220264, 0.00881057],dtype='float64')
y_error = np.array([0.00220264, 0.00220264, 0.00220264, 0.00220264, 0.00582765,
       0.00539535, 0.00794174, 0.0085308 , 0.0118616 , 0.01101322,
       0.01573002, 0.0137555 , 0.01339816, 0.01339816, 0.01009378,
       0.0118616 , 0.01123132, 0.01144527, 0.01123132, 0.00794174,
       0.00908173, 0.00794174, 0.00492526, 0.00440529, 0.00492526,
       0.00220264, 0.00440529],dtype='float64')

使用

绘制此数据
plt.errorbar(x,y,yerr=y_error,fmt='.')

产生以下内容plot

现在,当我尝试使用 scipy.optimize.curve_fit 拟合一些数据时 我得到

popt, pcov = scipy.optimize.curve_fit(gaussian,x,y,sigma=y_error,absolute_sigma=True)
plt.plot(x,gaussian(x,*popt)) # plotting the gaussian

这会产生这个 plot,叠加在我的原始数据的先前图上。这根本不是钟形曲线。为什么会这样?我检查了我的数据有问题的东西,但没有发现任何奇怪的东西。所有传入曲线拟合的数组都是 float64,我的高斯函数可以接受 np.array 的 'float64' 并输出相同类型的数组。我很困惑会出什么问题。

经过一些修改,解决方案只是通过将 p0=[sigma_guess,mean_guess] 作为参数传递给 curve_fit() 来提供对均值的良好初始猜测. this plot 是结果。对于上下文(我试图在存在放射源的情况下拟合盖革计数器测量的每个采样间隔的发生次数与计数,因此计算平均值的估计值很容易)。