我得到了ValueError:预期的2D数组,得到了1D数组

时间:2018-03-16 07:08:14

标签: python python-2.7 scikit-learn

我正在尝试学习scikit但是当我试图运行这个简单的例子时,我得到以下错误。错误也说

  

使用array.reshape(-1,1)重塑数据   ValueError:预期的2D数组,改为获得1D数组:

但我不知道我在哪里实现它。

以下是我的代码

from sklearn.linear_model import LinearRegression
# Training data
X = [[6], [8], [10], [14],[18]]
y = [[7], [9], [13], [17.5], [18]]
# Create and fit the model
model = LinearRegression()
model.fit(X, y)
print 'A 12" pizza should cost: $%.2f' % model.predict([12])[0]

以下是完整的错误 -

ValueErrorTraceback (most recent call last)
<ipython-input-4-20775a37bc05> in <module>()
      6 model = LinearRegression()
      7 model.fit(X, y)
----> 8 print 'A 12" pizza should cost: $%.2f' % model.predict([12])[0]

/home/atif/anaconda2/lib/python2.7/site-packages/sklearn/linear_model/base.pyc in predict(self, X)
    254             Returns predicted values.
    255         """
--> 256         return self._decision_function(X)
    257 
    258     _preprocess_data = staticmethod(_preprocess_data)

/home/atif/anaconda2/lib/python2.7/site-packages/sklearn/linear_model/base.pyc in _decision_function(self, X)
    237         check_is_fitted(self, "coef_")
    238 
--> 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_

/home/atif/anaconda2/lib/python2.7/site-packages/sklearn/utils/validation.pyc in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    439                     "Reshape your data either using array.reshape(-1, 1) if "
    440                     "your data has a single feature or array.reshape(1, -1) "
--> 441                     "if it contains a single sample.".format(array))
    442             array = np.atleast_2d(array)
    443             # To ensure that array flags are maintained

ValueError: Expected 2D array, got 1D array instead:
array=[12].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

1 个答案:

答案 0 :(得分:2)

更改此

model.predict([12])[0]

为:

model.predict([[12]])[0]

注意第二对方括号。对于scikit,X应为2-d。