实现如下的线性回归:
from sklearn.linear_model import LinearRegression
x = [1,2,3,4,5,6,7]
y = [1,2,1,3,2.5,2,5]
# Create linear regression object
regr = LinearRegression()
# Train the model using the training sets
regr.fit([x], [y])
# print(x)
regr.predict([[1, 2000, 3, 4, 5, 26, 7]])
产生:
array([[1. , 2. , 1. , 3. , 2.5, 2. , 5. ]])
在利用预测函数时,为什么不能利用单个x值进行预测?
试试 regr.predict([[2000]])
回报:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-3a8b477f5103> in <module>()
11
12 # print(x)
---> 13 regr.predict([[2000]])
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/base.py in predict(self, X)
254 Returns predicted values.
255 """
--> 256 return self._decision_function(X)
257
258 _preprocess_data = staticmethod(_preprocess_data)
/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/base.py in _decision_function(self, X)
239 X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
240 return safe_sparse_dot(X, self.coef_.T,
--> 241 dense_output=True) + self.intercept_
242
243 def predict(self, X):
/usr/local/lib/python3.6/dist-packages/sklearn/utils/extmath.py in safe_sparse_dot(a, b, dense_output)
138 return ret
139 else:
--> 140 return np.dot(a, b)
141
142
ValueError: shapes (1,1) and (7,7) not aligned: 1 (dim 1) != 7 (dim 0)
1 回答
当你这样做:
你基本上输入这个:
X
的形状为(1,7)
,y
的形状为(1,7)
.现在看documentation of fit():
参数:
y:numpy数组形状[n_samples,n_targets]
目标值 . 如有必要,将被转换为X的dtype
所以在这里,模型假定您拥有数据的数据具有7个功能,并且您有7个目标 . 请参阅this for more information on multi-output regression .
因此,在预测时,模型将需要具有7个特征的数据,形状为
(n_samples_to_predict, 7)
,并将输出形状为(n_samples_to_predict, 7)
的数据 .相反,如果你想要这样的东西:
那么你需要
(7,1)
的形状为输入x
和(7,)
或(7,1)
为目标y
.所以@WStokvis在评论中说,你需要这样做:
然后在预测时间再次:
然后执行以下操作不会引发错误:
因为存在所需的形状 .
Update for the comment:-
当你执行
[[2000]]
时,它将在内部转换为np.array([[2000]])
,因此它的形状为(1,1)
. 这类似于(n_samples, n_features)
,其中n_features = 1
. 这对于模型是正确的,因为在训练时,数据具有形状(n_samples, 1)
. 这样可行 .现在让我们说,你有:
同样,它将在内部转换为:
所以现在X_new的形状为
(7,)
. 看它只是一维数组 . 它是行向量还是列向量无关紧要 . 它只是(n,)
的一维数组 .所以scikit可能无法推断它的
n_samples=n
和n_features=1
或其他方式(n_samples=1
和n_features=n
) . 请参阅my other answer which explains about this .所以我们需要通过
reshape(-1,1)
将一维数组显式转换为2-d . 希望现在清楚 .