Python:使用 scipy.optimize.curve_fit 执行 bootstrap 时出错

Python: error while performing bootstrap with scipy.optimize.curve_fit

有两个明显遵循指数趋势的数据集,我通过 scipy.optimize.curve_fit() 为它们拟合了一条曲线。 x 数据集不包含零且有界 0<x<=100,而 y 数据集有界 0<=y<=1。这是拟合方程:

def func(x, a, c, d):
    return a * numpy.exp(-c*x)+d

我这样调用 curve_fit

popt, pcov, infodict, errmsg, ier = curve_fit(func, x1, y1, p0 = (1, 1e-6, 1), full_output=True)

其中 x1y1 是我的两个数据集。现在,based on this answer, I wanted to perform the Bootstrap Method 确保我获得了拟合参数的标准误差,我将使用它来量化拟合优度。

Based on the code provided in this answer,鉴于显然 SciPy 不包含任何此类内容,我已经调用了 Bootstrap 方法,如下所示:

pfit, perr = fit_bootstrap(pstart, xx, yy, func)

其中 pfit 是新的拟合参数(与 curve_fit 给出的参数进行比较), perr 是我所追求的标准误差。 p-start 在我的例子中是 (1, 1e-6,1),xx 是用于绘制函数的 x 值,yy 是拟合方程中的 y 值应用于 xx 值。最后,拟合函数是 func=a*numpy.exp(-c*x)+d.

调用引发错误: TypeError: func() takes exactly 4 arguments (2 given)。我知道在参数方面存在不匹配,但我不明白错误的确切位置。有人可以帮忙吗?

回溯:

TypeError                                 Traceback (most recent call last)
in <module>()
    163     return pfit_bootstrap, perr_bootstrap
    164 
--> 165 pfit, perr = fit_bootstrap(pstart, xx, yy, func)
    166 
    167 print("\nFit parameters and parameter errors from bootstrap method :")

in fit_bootstrap(p0, datax, datay, function, yerr_systematic)
    127 
    128     # Fit first time
--> 129     pfit, perr = optimize.leastsq(errfunc, p0, args=(datax, datay), full_output=0)
    130 
    131 

in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    375     if not isinstance(args, tuple):
    376         args = (args,)
--> 377     shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
    378     m = shape[0]
    379     if n > m:

in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
     24 def _check_func(checker, argname, thefunc, x0, args, numinputs,
     25                 output_shape=None):
---> 26     res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
     27     if (output_shape is not None) and (shape(res) != output_shape):
     28         if (output_shape[0] != 1):

in <lambda>(p, x, y)
    124 def fit_bootstrap(p0, datax, datay, function, yerr_systematic=0.0):
    125 
--> 126     errfunc = lambda p, x, y: function(x,p) - y
    127 
    128     # Fit first time

TypeError: func() takes exactly 4 arguments (2 given) 

在下一行中,您不应将 func 作为参数传递:

pfit, perr = fit_bootstrap(pstart, xx, yy, func)

如果你检查你提到的答案,他们会传递名为 ff 的函数。 ff 定义为:

def ff(x, p):
    return func(x,*p)

添加 "ff" 的定义后,您可以将调用更改为:

pfit, perr = fit_bootstrap(pstart, xx, yy, ff)