【问题标题】:Python: error while performing bootstrap with scipy.optimize.curve_fitPython:使用 scipy.optimize.curve_fit 执行引导时出错
【发布时间】:2016-09-09 13:49:37
【问题描述】:

有两个显然遵循指数趋势的数据集,我通过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,我想执行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 是来自适用于 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) 

【问题讨论】:

    标签: python numpy scipy parameter-passing curve-fitting


    【解决方案1】:

    在以下行中,您不应将 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)
    

    【讨论】:

    • 好的,但这是为什么呢?为什么func 不能直接成为一个论点?
    猜你喜欢
    • 1970-01-01
    • 2012-01-29
    • 2019-04-16
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2020-05-29
    • 2018-04-05
    • 2012-02-25
    相关资源
    最近更新 更多