【发布时间】: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
【问题讨论】: