Reputation: 3657
I am trying to use scipy.optimize.curve_fit
to fit a model function, but the following code gives me the following error:
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)
The error I get is:
TypeError: unsupported operand type(s) for -: 'list' and 'list'
I know related questions have been asked here and here but I wasn't able to solve my problem from those answers.
I did double check the type of of the arguments that curve_fit
sends to my function and I saw that alpha
comes in as numpy.float64
and x
as list
Thanks for your help.
Here is the traceback error:
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'
Here is _general_function
:
def _general_function(params, xdata, ydata, function):
return function(xdata, *params) - ydata
Upvotes: 3
Views: 2196
Reputation: 54380
You need to convert you list
s to 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])
Result:
(array([ 0.00012562]), array([[ 2.38452809e-08]]))
The reason is quite evident as indicated by this message:
TypeError: unsupported operand type(s) for -: 'list' and 'list'
Sure, list
can not be subtracted by a list
. In order to do so, we need them to be in numpy.array
Upvotes: 5