如何修复Python错误,在描述中是代码和错误

时间:2018-09-04 17:49:57

标签: python arrays python-3.x scikit-learn libsvm

如何修复代码中的错误,我使用的是python 3.7,macOS high sierra 已安装的库为:sklearn matplotlib numpy

代码:

import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
import numpy


digits=datasets.load_digits()
'''
print(digits.data)
print(digits.target)
print(digits.images[0])
 '''

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

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()

错误:

  Traceback (most recent call last):
   File "/Users/harmanthind/Documents/Python/scikit learn 
  liberary/pehla.py", line 21, in <module>
  print('prediction:',clf.predict(digits.data[-1]))

  File"/Library/Frameworks/ 
   Python.framework/Versions/3.7/lib/python3.7/site- 
    packages/sklearn/svm/base.py", line 548, in predict
  y = super(BaseSVC, self).predict(X)
    File 
 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- 
  packages/sklearn/svm/base.py", line 308, in predict
   X = self._validate_for_predict(X)
   File 
"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/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 
 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/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.  6.  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.

1 个答案:

答案 0 :(得分:0)

正确缩进 了吗?

我已经使用正确的缩进在我的计算机( Windows 8.1 )上运行了您的代码,并且该代码运行了 fine

缩进代码:

import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
import numpy


digits=datasets.load_digits()
'''
 print(digits.data)
 print(digits.target)
 print(digits.images[0])
 '''

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

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()

此外,如果它不起作用,请尝试更改内核/解释器。尝试 Python 3.6.x 内核/解释器。

p.s:我已经在Thonny IDE上使用Python 3.6.0来运行测试该代码,并且在我的机器上工作正常。