2017-12-13 7 views
0

나는이 내 코드입니다Scikit 알아 숫자 데이터 세트

에 무슨 일이 일어나고 있는지 이해하지

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

# Load digits dataset 
digits = datasets.load_digits() 

# Create support vector machine classifier 
clf = svm.SVC(gamma=0.001, C=100.) 
# fit the classifier 
X, y = digits.data[:-1], digits.target[:-1] 
clf.fit(X, y) 
pred = clf.predict(digits.data[-1]) # error goes at this line 
plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest') 
plt.show() 

이 코드는 예측 sklearn 숫자 이미지를 보여주고 보여되고 난 실행

이 코드는 나에게이 오류를 표시합니다.

Traceback (most recent call last): 
    File "detect.py", line 15, in <module> 
    pred = clf.predict(digits.data[-1]) 
    File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py", line 548, in predict 
    y = super(BaseSVC, self).predict(X) 
    File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py", line 308, in predict 
    X = self._validate_for_predict(X) 
    File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/base.py", line 439, in _validate_for_predict 
    X = check_array(X, accept_sparse='csr', dtype=np.float64, order="C") 
    File "/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py", line 410, 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

오류 메시지에 무엇이 잘못 되었나요? 분류기의 예측 방법에 단일 열을 제공하고 피팅 할 때 사용 된만큼의 열을 예상합니다. 코드를 변경하면 코드가

pred = clf.predict(digits.data[:-1]) 

으로 변경됩니다. 물론 당신이 맞춘 동일한 데이터를 예측할 것이기 때문에 (그리고 당신은 그 피처들로부터 하나의 컬럼을 생략하고 있기 때문에) 이해가되지 않습니다. 더 합리적인 일은 split the dataset으로 기차로 데이터 세트 및 적합성을 테스트하고 테스트하고 테스트를 예측하는 것입니다. 좋아요 :

from sklearn import datasets 
from sklearn import svm 
import matplotlib.pyplot as plt 
from sklearn.model_selection import train_test_split 

# Load digits dataset 
digits = datasets.load_digits() 

# Create support vector machine classifier 
clf = svm.SVC(gamma=0.001, C=100.) 
# split the data to train and test sets 
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=2017) 
# fit the classifier with train data 
clf.fit(X_train, y_train) 
pred = clf.predict(X_test)