【发布时间】:2019-04-16 12:18:22
【问题描述】:
我有一个 2400 x 2400 的数据数组,看起来像这样:
data = [[-2.302670298082603040e-01 -2.304885241061924717e-01 -2.305029774024092148e-01 -2.304807100897505734e-01 -2.303702531336284665e-01 -2.307144352067780346e-01...
[-2.302670298082603040e-01 -2.304885241061924717e-01 -2.305029774024092148e-01 -2.304807100897505734e-01 -2.303702531336284665e-01 -2.307144352067780346e-01...
...
我正在尝试拟合以下二维高斯函数:
def Gauss2D(x, mux, muy, sigmax, sigmay, amplitude, offset, rotation):
assert len(x) == 2
X = x[0]
Y = x[1]
A = (np.cos(rotation)**2)/(2*sigmax**2) + (np.sin(rotation)**2)/(2*sigmay**2)
B = (np.sin(rotation*2))/(4*sigmay**2) - (np.sin(2*rotation))/(4*sigmax**2)
C = (np.sin(rotation)**2)/(2*sigmax**2) + (np.cos(rotation)**2)/(2*sigmay**2)
G = amplitude*np.exp(-((A * (X - mux) ** 2) + (2 * B * (X - mux) * (Y - muy)) + (C * (Y - muy) ** 2))) + offset
return G
这个数据,使用 scipy curve_fit。因此,我将自变量(坐标)的域定义如下:
vert = np.arange(2400, dtype=float)
horiz = np.arange(2400, dtype=float)
HORIZ, VERT = np.meshgrid(horiz, vert)
作为参数的初始估计:
po = np.asarray([1200., 1200., 300., 300., 0.14, 0.22, 0.], dtype=float)
这样我就可以执行以下拟合:
popt, pcov = curve_fit(Gauss2D, (HORIZ, VERT), data, p0=po)
这将返回以下错误消息,我不知道为什么:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
ValueError: object too deep for desired array
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-11-ebba75332bfa> in <module>()
----> 1 curve_fit(Gauss2D, (HORIZ, VERT), data, p0=po)
/home/harrythegenius/anaconda3/lib/python3.6/site-packages/scipy/optimize/minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
734 # Remove full_output from kwargs, otherwise we're passing it in twice.
735 return_full = kwargs.pop('full_output', False)
--> 736 res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
737 popt, pcov, infodict, errmsg, ier = res
738 cost = np.sum(infodict['fvec'] ** 2)
/home/harrythegenius/anaconda3/lib/python3.6/site-packages/scipy/optimize/minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
385 maxfev = 200*(n + 1)
386 retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
--> 387 gtol, maxfev, epsfcn, factor, diag)
388 else:
389 if col_deriv:
error: Result from function call is not a proper array of floats.
我不理解“对象对于所需数组而言太深”的消息。我还看到了针对此错误消息的多个在线解决方案,其中一个可以通过确保传递给 curve_fit 的所有数据类型都是浮点数或检查数组的维度是否正确来修复它。我已经一次又一次地尝试了这两种方法,但没有任何区别。那么这个有什么问题呢?
【问题讨论】:
-
澄清一下,
data.shape和data.dtype是什么?您需要显示一些数据检查。 -
形状为 (2400, 2400)。
-
dtype 是 float64
-
HORIZ是一个二维数组,(2400,2400)。您是否尝试过使用(horiz, vert)来调用它? -
如果您给我们minimal reproducible example,我们可以复制粘贴并运行,我们也许可以提供更多帮助。
标签: python optimization scipy curve-fitting gaussian