我正在阅读 curve_fit
的文档。作为第一个参数,curve_fit
接受要拟合的函数。为了让它以部分函数作为第一个参数,我稍微修改了示例代码:
In:
import numpy as np
from scipy.optimize import curve_fit
def func( t, x , a, b, c): # I added a dummy variable t so that I can apply partials later
return a*np.exp(-b*x) + c + t
func = partial( func, 0 ) # use of partial to remove the dummy variable
x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, yn) # curve_fit gets a partial instead of a Python function
Out:
TypeError: <functools.partial object at 0x104551c58> is not a Python function
啊,那很令人失望。我想下次我会使用一个
lambda
。
不管怎样,这里的问题是什么?函数能做什么而部分函数不能做什么?
isinstance(func, types.FunctionType)
是否成立。type(pfunc)
是functools.partial
。 - hpauljcurvefit
只是使用getargspec
来确定len(args)
。在这种情况下,func
的长度为 5,pfunc
的长度为 5-1,即len(getargspec(pfunc.func)[0])-len(pfunc.args)
。使用此计算的自定义curvefit
可能会起作用。 - hpaulj