scipy.optimize.curve_fit不支持的操作数类型错误

时间:2014-05-01 01:41:58

标签: python scipy

我正在尝试使用scipy.optimize.curve_fit来适应模型函数,但以下代码给出了以下错误:

from scipy.optimize import curve_fit
from math import log10

def my_func(x, alpha):
return [10*log10(alpha*y*y) for y in x]

known_x = [1039.885254, 2256.833008, 6428.667969, 30602.62891] #known x-values
known_y = [31.87999916, 33.63000107, 35, 36.74000168]

popt, pcov = curve_fit(my_func, known_x, known_y)

我得到的错误是:

TypeError: unsupported operand type(s) for -: 'list' and 'list'

我知道相关问题已被问及herehere,但我无法从这些答案中解决问题。

我仔细检查了curve_fit发送到我的函数的参数的类型,我看到alpha作为numpy.float64x作为{{1}进来}}

感谢您的帮助。

以下是回溯错误:

list

以下是Traceback (most recent call last): File "test.py", line 10, in <module> popt, pcov = curve_fit(my_func, known_x, known_y) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 506, in curve_fit res = leastsq(func, p0, args=args, full_output=1, **kw) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 348, in leastsq m = _check_func('leastsq', 'func', func, x0, args, n)[0] File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 14, in _check_func res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/minpack.py", line 418, in _general_function return function(xdata, *params) - ydata TypeError: unsupported operand type(s) for -: 'list' and 'list'

_general_function

1 个答案:

答案 0 :(得分:4)

您需要将list转换为np.array

def my_func(x, alpha):
    return np.array([10*np.log10(alpha*y*y) for y in x])

known_x = np.array([1039.885254, 2256.833008, 6428.667969, 30602.62891]) #known x-values
known_y = np.array([31.87999916, 33.63000107, 35, 36.74000168])

结果:

(array([ 0.00012562]), array([[  2.38452809e-08]]))

原因很明显,如此消息所示:

TypeError: unsupported operand type(s) for -: 'list' and 'list'

当然,list无法减去list。为此,我们需要它们位于numpy.array