fear_matrix
fear_matrix

Reputation: 4960

I am getting ValueError: Expected 2D array, got 1D array instead

I am trying to learn scikit but when I am trying to run this simple example then I am getting the below error. The error also says

Reshape your data either using array.reshape(-1, 1) ValueError: Expected 2D array, got 1D array instead:

but I am not show where do I implement it.

Below is my code

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]

Below is the complete error -

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.

Upvotes: 0

Views: 3317

Answers (1)

Vivek Kumar
Vivek Kumar

Reputation: 36619

Change this

model.predict([12])[0]

to:

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

Notice the second pair of square brackets. For scikit, X should be 2-d.

Upvotes: 2

Related Questions