knn实现
"""
识别手写数字 数据集 mnist 直接从keras库中读取
"""
# 导入 keras 库
import tensorflow.keras as tk
import numpy as np
import matplotlib.pyplot as plt
# 加载数据
(train_dataset, train_labels), (test_dataset, test_labels) = tk.datasets.mnist.load_data()
train_labels = np.array(train_labels, dtype=np.int32)
# # 打印数据集形状
# print(train_dataset.shape, test_dataset.shape)
# # 图像预览
# for i in range(40):
# plt.subplot(4, 10, i+1)
# plt.imshow(train_dataset[i], cmap='gray')
# plt.title(train_labels[i], fontsize=10)
# plt.axis('off')
# plt.show()
# 将原始图像作为描述符
def raw_pixels(img):
return img.flatten()
# 数据打散
shuffle = np.random.permutation(len(train_dataset))
train_dataset, train_labels = train_dataset[shuffle], train_labels[shuffle]
# 计算每个图像的描述符,这里特征描述符是原始像素
raw_descriptors = []
for img in train_dataset:
raw_descriptors.append(np.float32(raw_pixels(img)))
r