【问题标题】:Single prediction with linear regression线性回归的单一预测
【发布时间】:2018-10-09 23:22:00
【问题描述】:

如下实现线性回归:

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)

【问题讨论】:

  • 所以看起来该函数进行了 7D 预测!。所以模型认为你输入一个 7D 的样本 X 并产生一个 y 和 7D 的输出。因此,您的新输入不适合。也许你应该把你拉进去并输出到 (7,1) 暗向量。
  • 添加到@Quickbeam2k1 的评论。使用reshape。例如,X = np.reshape(x, (7,1)) 然后适合您的模型,它应该可以按预期工作。
  • @Quickbeam2k1 它的 2D(不是 7D)。只是第二个维度有 7 个元素。
  • 所以你传递的每个向量都是 7D。您下面的答案也使用 7d 向量表示 x 和 y
  • @Quickbeam2k1 7 个元素并不意味着 7d。

标签: python scikit-learn regression linear-regression


【解决方案1】:

当你这样做时:

regr.fit([x], [y])

你实际上是在输入这个:

regr.fit([[1,2,3,4,5,6,7]], [[1,2,1,3,2.5,2,5]])

对于X,形状为(1,7),对于y,形状为(1,7)

现在看documentation of fit()

参数:

X : numpy array or sparse matrix of shape [n_samples,n_features]
    Training data

y : numpy array of shape [n_samples, n_targets]
    Target values. Will be cast to X’s dtype if necessary

所以在这里,模型假设你有数据,这些数据有 7 个特征,你有 7 个目标。请看this for more information on multi-output regression

所以在预测时,模型将需要具有 7 个特征的数据,形状为 (n_samples_to_predict, 7) 的数据,并将输出形状为 (n_samples_to_predict, 7) 的数据。

如果你想要这样的东西:

  x   y
  1  1.0
  2  2.0
  3  1.0
  4  3.0
  5  2.5
  6  2.0
  7  5.0

那么你需要有一个(7,1) 的形状用于输入x(7,)(7,1) 用于目标y

正如@WStokvis 在 cmets 中所说,您需要这样做:

import numpy as np
X = np.array(x).reshape(-1, 1)
y = np.array(y)          # You may omit this step if you want

regr.fit(X, y)           # Dont wrap it in []

然后在预测时间再次:

X_new = np.array([1, 2000, 3, 4, 5, 26, 7]).reshape(-1, 1)
regr.predict(X_new)

然后执行以下操作不会引发错误:

regr.predict([[2000]])

因为存在所需的形状。

评论更新:-

当您执行[[2000]] 时,它将在内部转换为np.array([[2000]]),因此它具有(1,1) 的形状。这类似于(n_samples, n_features),其中n_features = 1。这对于模型是正确的,因为在训练时,数据的形状为 (n_samples, 1)。所以这行得通。

现在让我们说,你有:

X_new = [1, 2000, 3, 4, 5, 26, 7] #(You havent wrapped it in numpy array and reshape(-1,1) yet

再次,它将在内部转换为:

X_new = np.array([1, 2000, 3, 4, 5, 26, 7])

所以现在 X_new 的形状为 (7,)。看到它只有一个一维数组。它是行向量还是列向量都没有关系。它只是(n,) 的一维数组。

因此 scikit 可能无法推断其是 n_samples=nn_features=1 还是其他方式(n_samples=1n_features=n)。请参阅my other answer which explains about this

所以我们需要通过reshape(-1,1) 将一维数组显式转换为二维数组。希望现在清楚。

【讨论】:

  • 感谢为什么需要代码 'X_new = np.array([1, 2000, 3, 4, 5, 26, 7]).reshape(-1, 1) regr.predict(X_new) ' 因为 'regr.predict([[2000]])' 似乎没有它也能工作?
  • @blue-sky 我已经更新了您评论的答案。请看一下,如果还不清楚,请询问。
  • @VivekKumar 感谢 Vivek 如此精美和详细地解释它。我一直在努力寻找一种方法来解决我所面临的同一类型的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 2018-04-02
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多