1

I am trying the further below linear regression python code but I am getting the error: "expecting a 2D array got 1D array instead: Array=[16]". What could be wrong?

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

==================================================================== Traceback (most recent call last):

 File "<ipython-input-27-8b7f351334d7>", line 1, in <module>
 runfile('C:/ML/train.py', wdir='C:/ML')

 File "C:\Users\admin\Anaconda3\lib\site- 
 packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
 execfile(filename, namespace)

 File "C:\Users\admin\Anaconda3\lib\site- 
 packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

 File "C:/ML/train.py", line 16, in <module>
 model.predict([12])[0]

 File "C:\Users\admin\Anaconda3\lib\site- 
 packages\sklearn\linear_model\base.py", line 256, in predict
return self._decision_function(X)

   File "C:\Users\admin\Anaconda3\lib\site- 
   packages\sklearn\linear_model\base.py", line 239, in _decision_function
   X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])

File "C:\Users\admin\Anaconda3\lib\site- 
 packages\sklearn\utils\validation.py", line 441, in check_array
"if it contains a single sample.".format(array))

ValueError: Expected 2D array, got 1D array instead:
 array=[16].
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.
3
  • Please include the full error traceback. Commented Aug 4, 2018 at 12:32
  • traceback included Commented Aug 4, 2018 at 18:38
  • @IPPOKRATISKARAKOTSOGLOU, if my answer helped you please upvote it as well as accepting it. many thanks Commented Aug 5, 2018 at 8:43

1 Answer 1

1

You're only providing a 1D array. Try

>>> print 'A 16" pitta bread should cost: $%.2f' % model.predict([16][0])
>>> A 16" pitta bread should cost: $18.14
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.