繁体   English   中英

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

[英]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是我的两个数据集。 现在, 基于此答案 ,我想执行Bootstrap方法 ,以确保获得拟合参数的标准误差,并将其用于量化拟合优度。

基于此答案中提供的代码 ,鉴于SciPy显然不包括任何种类的东西,因此我对Bootstrap方法进行了如下调用:

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

其中pfit是新的拟合参数(将与curve_fit给出的参数进行比较),而perr是我要curve_fit的标准误差。 在我的情况下, p-start是(1,1e-6,1), xx是用于绘制函数的x值, yy是从应用于xx值的拟合方程式中得出的y值。 最后,拟合函数为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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM