3

当我尝试使用 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) 
4

1 回答 1

6

更改x并更改y为 numpy 数组

x = np.array([40,45,50,55,60])
y = np.array([0.99358851674641158, 0.79779904306220106, 0.60200956937799055, 0.49521531100478472, 0.38842105263157894])

那么我认为你很好,因为该函数需要矢量化计算,而列表是不够的。

于 2012-11-13T22:44:17.700 回答