当我尝试使用curve_fit进行指数拟合时,scipy会返回错误。难道我做错了什么?从np.exp(-b * t)中删除负号可以使curve_fit工作,但它返回的值是关闭的。
#!/usr/bin/python
import numpy as np
import scipy as sp
from scipy.optimize import curve_fit
import scipy.optimize as opt
import matplotlib.pyplot as plt
x = [40,45,50,55,60]
y = [0.99358851674641158, 0.79779904306220106, 0.60200956937799055, 0.49521531100478472, 0.38842105263157894]
def model_func(t, a, b, c):
return a * np.exp(-b * t) + c
opt_parms, parm_cov = sp.optimize.curve_fit(model_func, x, y, maxfev=1000)
a,b,c = opt_parms
print a,b,c
print x
print y
print model_func(x, a,b,c)
失败并显示错误:
Traceback (most recent call last):
File "asdf.py", line 18, in <module>
opt_parms, parm_cov = sp.optimize.curve_fit(model_func, x, y, maxfev=1000)
File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 426, in curve_fit
res = leastsq(func, p0, args=args, full_output=1, **kw)
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 "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 346, in _general_function
return function(xdata, *params) - ydata
ValueError: operands could not be broadcast together with shapes (0) (5)
答案 0 :(得分:5)
将x
和y
更改为numpy数组
x = np.array([40,45,50,55,60])
y = np.array([0.99358851674641158, 0.79779904306220106, 0.60200956937799055, 0.49521531100478472, 0.38842105263157894])
然后我认为你很好,因为这个函数需要矢量化计算,而列表是不够的。