pyqt_fit.CurveFitting示例抛出错误

时间:2016-03-01 21:31:21

标签: python pyqt

我尝试在代码中使用PyQt-Fit库,但遇到了麻烦。仅仅是为了试验,我从包主页复制了示例代码。

以下是我正在运行的代码:

import pyqt_fit
from pyqt_fit import plot_fit
import numpy as np
from matplotlib import pylab
x = np.arange(0,3,0.01)
y = 2*x + 4*x**2 + np.random.randn(*x.shape)
def fct(params, x):
    (a0, a1, a2) = params
    return a0 + a1*x + a2*x*x
fit = pyqt_fit.CurveFitting(x, y, (0,1,0), fct)
result = plot_fit.fit_evaluation(fit, x, y)
print(fit(x)) # Display the estimated values
plot_fit.plot1d(result)
pylab.show()

这是我得到的错误:

    fit = pyqt_fit.CurveFitting(x, y, (0,1,0), fct)

TypeError: __init__() takes exactly 3 arguments (5 given)

Example code from the docs会出现同样的错误。

我试过谷歌搜索我的问题,但我找不到一个有效的例子。

我需要更改什么来正确传递所有参数?

1 个答案:

答案 0 :(得分:3)

我能够通过查看PyQt-Fit 1.2源代码来解决这个问题,看看签名在版本1.2和1.3之间如何变化。旧CurveFitting.__init__()看起来像这样:

def __init__(self, xdata, ydata, p0, fct, args=(), residuals=None,
             fix_params=(), Dfun=None, Dres = None, col_deriv=1,
             constraints = None, *lsq_args, **lsq_kword):

new one看起来像这样:

def __init__(self, xdata, ydata, **kwords):
    self._fct = None
    self._Dfun = None
    self._residuals = None

   # snip...

    self.xdata = xdata
    self.ydata = ydata

    for n in kwords:
        setattr(self, n, kwords[n])

# getters and setters for all the other properties

可以看出,它现在希望除了xdata和ydata之外的所有内容都是命名参数,而之前的p0fct是未命名的。 [文档中明显遗漏了这一点。]

示例中的函数调用应该如下所示:

fit = pyqt_fit.CurveFitting(x, y, p0=(0,1,0), function=fct)

至少对我来说,它仍然会在下一行引发错误:

 File "untitled0.py", line 18, in <module>
    result = plot_fit.fit_evaluation(fit, x, y)

  File "pyqt_fit/plot_fit.py", line 165, in fit_evaluation
    popt = fit.popt

AttributeError: 'CurveFitting' object has no attribute 'popt'

在尝试绘制图形之前,似乎它希望我调用返回的fit()函数。我只是将print(fit(x))行的顺序改为这一行,这解决了它。

现在的工作代码是:

import pyqt_fit
from pyqt_fit import plot_fit
import numpy as np
from matplotlib import pylab
x = np.arange(0,3,0.01)
y = 2*x + 4*x**2 + np.random.randn(*x.shape)
def fct(params, x):
    (a0, a1, a2) = params
    return a0 + a1*x + a2*x*x
fit = pyqt_fit.CurveFitting(x, y, p0=(0,1,0), function=fct)
print(fit(x)) # Display the estimated values1
result = plot_fit.fit_evaluation(fit, x, y)
plot_fit.plot1d(result)
pylab.show()
相关问题