【问题标题】:SciPy LeastSq - Array to Scalar IssueSciPy LeastSq - 数组到标量问题
【发布时间】:2012-04-10 08:09:55
【问题描述】:

我正在尝试使用 scipy.leastsq() 作为找到一组数据的最佳拟合点的方法。不熟悉 scipy 库,我得到的印象是,leastsq 函数一次对整个数据集进行数学运算,但同时我遇到了问题,因为它似乎将一些数据点作为标量。

我的目标是将结果作为一组两个值 - 也就是与一系列圆的最小距离的点 (x,y),这些圆也以 (x, y,半径)。 leastsq 函数前半部分的数学运算在每个圆上找到最接近猜测的点,然后得到猜测到该点的距离。

调用 minimumsq 函数(xi, yi, radii 已经将值加载到数组中)

#Now that we have the center, we can do least squares
#generate point guess starting at avg of circles
ptGuess = np.array([avgX,avgY])         
point, cov,info,mesg, ier = optimize.leastsq(calcResiduals, ptGuess, args = (xi,yi,radii))

还有 calcResiduals():

def calcResiduals(ptGuess, xi, yi, radii):
#extract x and y from guess point
xg = ptGuess[0]
yg = ptGuess[1]
#slope of the line from (xi,yi) to guess (xg,yg)
m = (yg - yi) / (xg - xi)
#Go along the line for the distance of c to get coordinates
deltax = radii / math.sqrt(1+m**2)
if (xi > xg):
    xii = xi + deltax
else:
    xii = xi - deltax
yii = m*(xii-xi) + yi
#residuals is distance from (xii,yii) to (xg, yg)
return (xii-xg)**2 + (yii-yg)**2    

我得到的错误似乎暗示了将数组转换为标量值以进行乘法运算的问题,但我不知道为什么该行不起作用,而前一个行会起作用。

错误:

File "listener.py", line 62, in calcAPLocation
point, cov,info,mesg, ier = optimize.leastsq(calcResiduals, ptGuess, args = (xi,yi,radii))
File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 276, in leastsq
m = _check_func('leastsq', 'func', func, x0, args, n)[0]
File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 13, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "listener.py", line 76, in calcResiduals
deltax = radii / math.sqrt(1+m**2)
TypeError: only length-1 arrays can be converted to Python scalars

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    如果代码中的 xi 和 yi 是点数组,则 m 应该是长度相等的数组 到 len(xi)。函数 math.sqrt 需要长度为 1 的数组或标量才能工作。

    上一行:

    m = (yg - yi) / (xg - xi)
    

    之所以有效,是因为您要划分为相同长度的数组。

    此行失败:

    deltax = radii / math.sqrt(1+m**2)
    

    因为 m 是一个包含许多条目的数组,而 python 数学库不知道如何处理它。您可以尝试将 math.sqrt 更改为 numpy.sqrt 以取每个的平方根 在 m 中输入。我想这就是你所追求的。将上面的行改为

    deltaX = radii/np.sqrt(1 + m**2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 2011-11-27
      • 1970-01-01
      • 2017-07-22
      • 2015-10-04
      相关资源
      最近更新 更多