尝试使用curve_fit来拟合3D高斯和获取广播问题(Python)
我今天花了至少两个小时试图让这个3D高斯拟合工作,但我一直没有成功!我的数据在一个名为“data”的NumPy数组中,data[x,y,z]给出函数在位置(x,y,z)上的值(所有位置都是非负值和整数值)。我正在尝试使用以下形式的3D高斯曲线进行拟合:尝试使用curve_fit来拟合3D高斯和获取广播问题(Python),python,scipy,curve-fitting,gaussian,data-fitting,Python,Scipy,Curve Fitting,Gaussian,Data Fitting,我今天花了至少两个小时试图让这个3D高斯拟合工作,但我一直没有成功!我的数据在一个名为“data”的NumPy数组中,data[x,y,z]给出函数在位置(x,y,z)上的值(所有位置都是非负值和整数值)。我正在尝试使用以下形式的3D高斯曲线进行拟合: # Our function gauss_3d is a function w = f(x,y,z) # Returns the value "w" of the 3D Gaussian at point (x,y,z) de
# Our function gauss_3d is a function w = f(x,y,z)
# Returns the value "w" of the 3D Gaussian at point (x,y,z)
def gauss_3d(x, y, z, amplit, x0, y0, z0, sig_x, sig_y, sig_z, offset):
sum = offset + amplit*np.exp(-(((x-x0)**2/(2*sig_x**2)) + \
((y-y0)**2/(2*sig_y**2) + ((z-z0)**2/(2*sig_z**2)))))
return sum
我的曲线拟合代码如下:
dim = data.shape
# Create meshgrid
XX, YY, ZZ = np.meshgrid(np.arange(dim[2]), np.arange(dim[1]), np.arange(dim[0]))
# Create data_in, which consists of (x, y, z) points. data_in has shape (392,3)
# i.e. 392 points of the form (x, y, z), where x,y,z are non-negative integers
data_in = np.vstack((XX.ravel(),YY.ravel(),ZZ.ravel())).T
# Create data_out, which is the ravelled data. data_out has shape (392,)
data_out = data.ravel()
print(data_in)
p_param, p_cov = opt.curve_fit(gauss_3d, data_in, data_out)
print("Fitted params:")
print(p_param)
但是,目前我收到错误“ValueError:操作数无法与形状(392,3)(392,)”一起广播。我检查了文档,它说Y和X必须有相同的维度M,在我的例子中,它们都有392作为第一个维度M=392。那么这为什么不起作用呢?数据必须有维度(392,3),否则,我不能把(x,y,z)值放在那里。看一看,因为它的实际工作原理与直觉所暗示的略有不同。@mikuszefski我现在明白我的错误了。非常感谢。欢迎干杯