使用 linalg.lstsq (numpy) 时的数学域错误



所以我在输入一组数据点时尝试使用线性回归来显示趋势线。我正在使用 Tkinter 获取数据的输入,然后将它们转换为浮点以将它们放入列表中。不过,当我运行程序时,我收到此错误代码。

    Exception in Tkinter callback
    Traceback (most recent call last):
      File "C:Python27liblib-tkTkinter.py", line 1486, in __call__
        return self.func(*args)
      File     "C:/Users/NIBO9901/PycharmProjects/Matteuppgift/Trendlinje/Input.py", line 78,  in plot
        m, c = np.linalg.lstsq(a, y)[0]
      File "C:Python27libsite-packagesnumpylinalglinalg.py", line 1889, in lstsq
        nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 )
    ValueError: math domain error

它引用的代码在这里:

    xList = []
    yList = []
    x = np.array(xList)
    y = np.array(yList)
    if 0 < len(inpX0.get()):
        xList.append(float(inpX0.get()))
    if 0 < len(inpX1.get()):
        xList.append(float(inpX1.get()))
    if 0 < len(inpY0.get()):
        yList.append(float(inpY0.get()))
    if 0 < len(inpY1.get()):
        yList.append(float(inpY1.get()))
    a = np.vstack([x, np.ones(len(x))]).T
    m, c = np.linalg.lstsq(a, y)[0]
    plt.plot(x, y, 'o', label='Data', markersize=10)
    plt.plot(x, m*x + c, 'r', label='Trendlinje')
    plt.legend()
    plt.show()

inpX/Y 是 Tkinter 条目。

numpy 数组是静态结构。您首先必须填充列表,然后将其转换为 numpy 数组。之后,对列表的修改将不再对 numpy 数组产生影响。

所以你想做的可能是:

xList = []
yList = []
if 0 < len(inpX0.get()):
    xList.append(float(inpX0.get()))
if 0 < len(inpX1.get()):
    xList.append(float(inpX1.get()))
if 0 < len(inpY0.get()):
    yList.append(float(inpY0.get()))
if 0 < len(inpY1.get()):
    yList.append(float(inpY1.get()))
a = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(a, y)[0]
# the lists are complete, now convert them to numpy arrays
x = np.array(xList)
y = np.array(yList)
plt.plot(x, y, 'o', label='Data', markersize=10)
plt.plot(x, m*x + c, 'r', label='Trendlinje')
plt.legend()
plt.show()

最新更新