线性回归预计X
为具有两个维度的阵列,并且在内部需要X.shape[1]
初始化一个np.ones
阵列。因此,将X
转换为nx1阵列可以做到这一点。因此,更换:
regr.fit(x,y)
由:
regr.fit(x[:,np.newaxis],y)
这将解决这个问题。演示:
>>> from sklearn import datasets
>>> from sklearn import linear_model
>>> clf = linear_model.LinearRegression()
>>> iris=datasets.load_iris()
>>> X=iris.data[:,3]
>>> Y=iris.target
>>> clf.fit(X,Y) # This will throw an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/sklearn/linear_model/base.py", line 363, in fit
X, y, self.fit_intercept, self.normalize, self.copy_X)
File "/usr/lib/python2.7/dist-packages/sklearn/linear_model/base.py", line 103, in center_data
X_std = np.ones(X.shape[1])
IndexError: tuple index out of range
>>> clf.fit(X[:,np.newaxis],Y) # This will work properly
LinearRegression(copy_X=True, fit_intercept=True, normalize=False)
要绘制回归线使用下面的代码:
>>> from matplotlib import pyplot as plt
>>> plt.scatter(X, Y, color='red')
<matplotlib.collections.PathCollection object at 0x7f76640e97d0>
>>> plt.plot(X, clf.predict(X[:,np.newaxis]), color='blue')
<matplotlib.lines.Line2D object at 0x7f7663f9eb90>
>>> plt.show()
![enter image description here](https://i.stack.imgur.com/Vfs5z.png)
对不起,我完全误解了你的问题:(我已经删除了答案,如果我能得到一个然后你可以提供更多的信息吗?比如你的完整代码? – Ffisegydd 2014-11-24 14:44:37
这是你需要的代码,没有别的重要。 – JackLametta 2014-11-24 14:46:06
真的吗?什么是'linear_model'?你是怎么做到的?得到它? – Ffisegydd 2014-11-24 14:46:45