数据集使用了Keras的datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from keras.datasets import mnist
(x_train_tmp, y_train_tmp), (x_test_tmp, y_test_tmp) = mnist.load_data()
x_test_new = x_test_tmp.reshape(x_test_tmp.shape[0], -1)
total_num = x_test_new.shape[0]
test_num = int(total_num / 10)
x_test = x_test_new[:test_num]
y_test = y_test_tmp[:test_num]
x_train = x_test_new[test_num:]
y_train = y_test_tmp[test_num:]
classifier = KNeighborsClassifier(n_neighbors=5)
classifier.fit(x_train, y_train)
y_pred = classifier.predict(x_test)
print(classification_report(y_test, y_pred))
打印结果如下:
precision recall f1-score support
0 0.94 0.99 0.97 85
1 0.91 1.00 0.95 126
2 0.97 0.91 0.94 116
3 0.93 0.93 0.93 107
4 0.91 0.91 0.91 110
5 0.95 0.92 0.94 87
6 0.97 0.97 0.97 87
7 0.89 0.91 0.90 99
8 0.95 0.83 0.89 89
9 0.86 0.87 0.87 94
accuracy 0.93 1000
macro avg 0.93 0.92 0.93 1000
weighted avg 0.93 0.93 0.93 1000