0

My code is this:

import matplotlib.pyplot as plt

from sklearn import datasets, svm

digits = datasets.load_digits()

clf = svm.SVC(gamma=0.001, C=100)

print(len(digits.data))

X,y = digits.data[:-1] , digits.target[:-1]

clf.fit(X,y)

print('Prediction:',clf.predict(digits.data[-1]))

plt.imshow(digits.images[-1],  cmap=plt.cm.gray_r, interpolation="nearest")

plt.show()

And I am getting this error:

Traceback (most recent call last):
File "E:\python programs\sklearn\sklearn 2.py", line 14, in <module>
print('Prediction:',clf.predict(digits.data[-1]))
File "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\svm\base.py", line 548, in predict
y = super(BaseSVC, self).predict(X)
File   "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\svm\base.py", line 308, in predict
X = self._validate_for_predict(X)
File "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\lib\site-packages\sklearn\svm\base.py", line 439, in _validate_for_predict
X = check_array(X, accept_sparse='csr', dtype=np.float64, order="C")
File "C:\Users\Rohan\AppData\Local\Programs\Python\Python36\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=[ 0.  0. 10. 14.  8.  1.  0.  0.  0.  2. 16. 14.   m6.  1.  0.  0.  0.  0.
 15. 15.  8. 15.  0.  0.  0.  0.  5. 16. 16. 10.  0.  0.  0.  0. 12. 15.
 15. 12.  0.  0.  0.  4. 16.  6.  4. 16.  6.  0.  0.  8. 16. 10.  8. 16.
 8.  0.  0.  1.  8. 12. 14. 12.  1.  0.].
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.

"What should I do?"

2
  • try print('Prediction:',clf.predict(digits.data[:-1])) Commented Jul 13, 2018 at 5:01
  • Always print and provide shape of arrays in such issues. They are helpful to get the problem right. Commented Jul 13, 2018 at 5:11

1 Answer 1

1

In your prediction step, you are passing a 1D array of shape (1,64) as I am able to see from the sklearn digit dataset docs. Reshape input data before predicting. Use Below:

print('Prediction:',clf.predict(np.reshape(digits.data[-1], (1,-1))) 
Sign up to request clarification or add additional context in comments.

2 Comments

File "E:\python programs\sklearn\sklearn 2.py", line 15, in <module> print('Prediction:',clf.predict(np.reshape(digits.data[-1]) ,(-1,1))) TypeError: reshape() missing 1 required positional argument: 'newshape' Now its giving the above error
there is no closing bracket after digits.data[-1] please copy the code in the answer, then share if you are getting the error.

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.