Last active
November 3, 2015 17:00
-
-
Save fabiosato/2a2014cd386d475fd037 to your computer and use it in GitHub Desktop.
kNN Classification of digits using scikit-learn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sklearn.metrics import confusion_matrix, accuracy_score | |
from sklearn import cross_validation | |
# load sample dataset of digits | |
digits = datasets.load_digits() | |
# prepare datasets from training and for validation | |
X_train, X_test, y_train, y_test = cross_validation.train_test_split(digits.data, digits.target, test_size=0.4, random_state=0) | |
# runs the kNN classifier for even number of neighbors from 1 to 10 | |
for n in range(1, 10, 2): | |
clf = neighbors.KNeighborsClassifier(n) | |
# instance based learning | |
clf.fit(X_train, y_train) | |
# our 'ground truth' | |
y_true = y_test | |
# predict | |
y_pred = clf.predict(X_test) | |
# learning metrics | |
cm = confusion_matrix(y_true, y_pred) | |
acc = accuracy_score(y_true, y_pred) | |
print "Neighbors: %d" % n | |
print "Confusion Matrix" | |
print cm | |
print "Accuracy score: %f" % accuracy_score(y_true, y_pred) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment