KNN
整体思路
- 加载数据集CIFAR10并随机展示部分数据
- 构建KNearestNeighbor分类器,计算测试集每张图片的每个像素点与训练集每张图片的每个像素点的距离。
- 将图片转化为数组。在测试集使用compute_distances_one_loop,compute_distances_no_loops,compute_distances_two_loops三种方法计算距离矩阵和欧氏距离
- 交叉验证选择最优K值在验证集计算准确率
加载CIFAR10数据集
#下载并加载数据集
from cs231n.data_utils import load_CIFAR10
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
#初始化
try:
del X_train, y_train
del X_test, y_test
print('Clear previously loaded data.')
# 加载数据集
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# 打印数据集大小和维度
print('Training data shape: ', X_train.shape)
print('Training labels shape: ', y_train.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
展示图片
# 图片类别
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
num_classes = len(classes)
# 每个类别展示七张照片
samples_per_class = 7
for y, cls in enumerate(classes):
idxs = np.flatnonzero(y_train == y)
idxs = np.random.choice(idxs, samples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt_idx = i * num_classes + y + 1
plt.subplot(samples_per_class, num_classes, plt_idx)
plt.imshow(X_train[idx].astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls)
plt.show()
构建模型
欧式距离也称欧几里得距离,衡量的是多维空间中两个点之间的 绝对距离 。

compute_distances_two_loops
#距离计算如下:
import numpy as np
X= np.arange(20)
print(X) #输出[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
X=np.reshape(X,(5,4))
print(X)
'''
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
'''
X_train = np.arange(16)
print(X_train) #输出[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
X_train=np.reshape(X_train,(4,4))
print(X_train)
'''
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
'''
num_test = X

本文介绍了如何使用KNN算法在CIFAR10数据集上进行图像分类,包括加载数据、计算欧氏距离的不同实现方法(两层循环、一层循环和无循环),以及通过k折交叉验证选择最佳K值以提高模型精度。
最低0.47元/天 解锁文章
552

被折叠的 条评论
为什么被折叠?



