微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python中的二维直方图二维高斯函数拟合

如何解决Python中的二维直方图二维高斯函数拟合

在 Python 中,我使用 np.hist2d() 函数绘制二维直方图。现在,我想为此拟合一个 2D 高斯函数。我尝试了其他方法,但它不起作用。

# Defining the 2D Gaussian function
def twoD_Gaussian(xdata_tuple,amplitude,xo,yo,sigma_x,sigma_y,theta,offset):
    (x,y) = xdata_tuple
    xo = float(xo)
    yo = float(yo)    
    a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
    b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
    c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
    g = offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) 
                            + c*((y-yo)**2)))
    return g.ravel() 

定义二维高斯函数后,我现在使用 np.histogram2d() 函数并尝试拟合数据。

plt.figure(figsize=(9,6))

xedges = np.linspace(2,13,20)
yedges = np.linspace(2,20)
xe,ye = np.meshgrid(xedges,yedges)

#plt.hist2d(x,y,bins=[xedges,yedges])

hist2d,xedges,yedges = np.histogram2d(x,bins=(xedges,yedges))
plt.imshow(hist2d,cmap=plt.cm.jet,origin='lower',extent=[xedges[0],xedges[-1],yedges[0],yedges[-1]])
plt.colorbar()

popt2d,pcov2d = curve_fit(gauss2d,(xe,ye),hist2d.ravel())

plt.xlabel('x [$ \mathrm{\mu m}$]',fontsize=12)
plt.ylabel('y [$ \mathrm{\mu m}$]',fontsize=12)
plt.title('2D position histogram',fontsize=16)
plt.savefig("2D_histogram.pdf",dpi=300,format="pdf",bBox_inches="tight",pad_inches=0.025)
plt.savefig("2D_histogram.jpeg")
plt.show() 

我之所以定义 xe 和 ye 是因为需要用到 np.meshgrid() 函数。但是我无法将它们包含在 np.histogram2d() 函数的 bin 中,因为您只能将 1D 用于 bin。

ValueError: operands Could not be broadcast together with shapes (800,) (361,) 

以上是我得到的错误。显然,(xe,ye) 和 hist2d.ravel() 的形状是不同的。但我找不到让它们保持相同形状的方法。我不知道这是唯一的问题,还是还有其他问题。提前致谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。