scipy.optimize.curve_fit, TypeError: unsupported operand type

Deadly 提交于 2019-12-04 05:18:49

The TypeError occurs because the x being passed to func2 is a list.

Here is an example:

import numpy as np
import scipy.optimize as optimize
def func2(x,a,b):
    return a*np.exp(b*(x**2))

x = np.linspace(0,1,6).reshape(2,-1)
y = func2(x,1,1)
x = x.tolist()
y = y.tolist()
print(x)
# [[0.0, 0.2, 0.4], [0.6000000000000001, 0.8, 1.0]]
print(y)
# [[1.0, 1.0408107741923882, 1.1735108709918103], [1.4333294145603404, 1.8964808793049517, 2.718281828459045]]

popt, pcov = optimize.curve_fit(func2, x, y)
# TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

In this case, func2 maps an array x of shape (2,3) to an array y of shape (2,3). The function optimize.curve_fit expects the return value from func2 to be a sequence of numbers -- not an array.

Fortunately for us, in this case, func2 is operating element-wise on each component of x -- there is no interaction between the elements of x. So it really makes no difference if we pass an array x of shape (2,3) or an 1D array of shape (6,).

If we pass an array of shape (6,) then func2 will return an array of shape (6,). Perfect. That's will do just fine:

x = np.asarray(x).ravel()
y = np.asarray(y).ravel()
popt, pcov = optimize.curve_fit(func2, x, y)
print(popt)
# [ 1.  1.]

What x values did you use? Following example works for me.

from scipy.optimize import curve_fit
import numpy as np

def func2(x,a,b):
  return a*np.exp(b*(x**2))

x = np.linspace(0,4,50)
y = func2(x, 2.5, 2.3)
yn = y + 6.*np.random.normal(size=len(x))
popt, pcov = curve_fit(func2,x,yn)
print popt, pcov

It gives the result depending on the random function:

[ 1.64182333  2.00134505] [[  1.77331612e+11  -6.77171181e+09]
 [ -6.77171181e+09   2.58627411e+08]]

Are your x and yn values of type list? Following example gives your error message:

print range(10)**2

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!