我如何绘制线性回归 [英] How I plot the linear regression

查看:87
本文介绍了我如何绘制线性回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用计算的线性回归绘制图,但出现错误"ValueError:x和y必须具有相同的第一维". 这是一个包含3个样本(x1,x2,x3)的多变量(2个变量)线性回归.

I am trying to plot a graph with the calculated linear regression, but I get the error "ValueError: x and y must have same first dimension". This is a multivariate (2 variables) linear regression with 3 samples (x1,x2,x3).

1-首先,我正在正确计算线性回归吗?

1 - First, I am calculating the linear regression correctly?

2-我知道错误来自绘图线.我只是不明白为什么会出现此错误.放置在图中正确的尺寸是什么?

2 - I know that the error comes from the plot lines. I just don't understand why I get this error. What is the right dimensions to put in the plot?

    import numpy as np
    import matplotlib.pyplot as plt

    x1 = np.array([3,2])
    x2 = np.array([1,1.5])
    x3 = np.array([6,5])
    y = np.random.random(3)
    A = [x1,x2,x3]

    m,c = np.linalg.lstsq(A,y)[0]

    plt.plot(A, y, 'o', label='Original data', markersize=10)
    plt.plot(A, m*A + c, 'r', label='Fitted line')
    plt.legend()
    plt.show()


    $ python  testNumpy.py
    Traceback (most recent call last):
      File "testNumpy.py", line 22, in <module>
        plt.plot(A, m*A + c, 'r', label='Fitted line')
      File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2987, in plot
        ret = ax.plot(*args, **kwargs)
      File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 4137, in plot
        for line in self._get_lines(*args, **kwargs):
      File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 317, in     _grab_next_args
        for seg in self._plot_args(remaining, kwargs):
      File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 295, in _plot_args
        x, y = self._xy_from_xy(x, y)
      File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 237, in _xy_from_xy
        raise ValueError("x and y must have same first dimension")
    ValueError: x and y must have same first dimension

推荐答案

这里的问题是,您正在创建列表A,而不是数组. m*A没有按照您的期望做.

The problem here is that you're creating a list A where you want an array instead. m*A is not doing what you expect.

此:

A = np.array([x1, x2, x3])

将消除错误.

NB:将列表 A 整数 m 相乘会为您提供一个包含原始内容的新列表重复 m 次.例如

NB: multiplying a list A and an integer m gives you a new list with the original content repeated m times. Eg.

>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]

现在,作为浮点数的 m 应该加一个TypeError(因为您只能将列表乘以整数)...但是m却是一个numpy.float64 ,并且当您将它乘以某个意外的东西(或知道的列表)时,NumPy会将其强制为整数.

Now, m being a floating point number should have raised a TypeError (because you can only multiply lists by integers)... but m turns out to be a numpy.float64, and it seems like when you multiply it to some unexpected thing (or a list, who knows), NumPy coerces it to an integer.

这篇关于我如何绘制线性回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆