[英]How I plot the linear regression
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". 我正在尝试使用计算的线性回归绘制图,但出现错误“ ValueError:x和y必须具有相同的第一维”。 This is a multivariate (2 variables) linear regression with 3 samples (x1,x2,x3).
这是具有3个样本(x1,x2,x3)的多元(2个变量)线性回归。
1 - First, I am calculating the linear regression correctly? 1-首先,我是否正确计算了线性回归?
2 - I know that the error comes from the plot lines. 2-我知道错误来自绘图线。 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
The problem here is that you're creating a list A
where you want an array instead. 这里的问题是,您正在创建列表
A
,而不是要使用数组。 m*A
is not doing what you expect. m*A
没有达到您的期望。
This: 这个:
A = np.array([x1, x2, x3])
will get rid of the error. 将摆脱错误。
NB: multiplying a list A and an integer m gives you a new list with the original content repeated m times. 注意:将列表 A与整数 m相乘会得到一个新列表,原始内容重复m次。 Eg.
例如。
>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]
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. 现在, m作为浮点数应该引发
TypeError
(因为您只能将列表乘以整数)...但是m
原来是numpy.float64
,并且看起来像将其乘以某种意外的东西(或列表(知道),NumPy将其强制为整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.