# function.py import numpy as np import os from scipy.spatial import distance from sklearn.neighbors import KDTree """ 实验说明: - 自行编写实现数据加载与 kNN 的手写数字分类算法。 - 函数输入: 待分类的样本 input_vector, 训练数据集 dataSet, 训练集对应的标签 labels。 - 函数返回: 预测的分类标签。 注意事项: - 在 function.py 中实现 kNN 分类算法。 - 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。 - 自动评测脚本仅会加载 classify 和 load_data 函数,请勿修改函数名。 - 训练集和测试集需手动下载解压,并放入当前目录下。 测评环境: - CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz - OS: Ubuntu 22.04.4 LTS - Python: 3.10.12 - numpy: 2.1.1 """ """ 请在这里填写学号和姓名,不填写即成绩无效。 """ id = "202210423213" name = "熊浩燃" """ 参数说明: - input_vector (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 - k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 返回值: - int: 预测的分类标签。 """ # 这里写自己的代码实现 def classify(input_vector, dataSet, labels, k=7, metric='euclidean', decision_rule='uniform', use_kdtree=False): """ 优化后的 KNN 分类算法,包括 k 值调优、距离度量、决策规则和加速方法。 Args: - input_vector (numpy array): 输入待分类的样本。 - dataSet (numpy array): 训练数据集。 - labels (list or numpy array): 训练集对应的标签。 - k (int): kNN 算法中的 k 值。 - metric (str): 距离度量方式,默认是 'euclidean',可以选择 'manhattan', 'cosine', 'mahalanobis' 等。 - decision_rule (str): 决策规则,'uniform' 为普通投票,'weighted' 为加权投票。 - use_kdtree (bool): 是否使用 KDTree 加速。 Returns: - int: 预测的分类标签。 """ # 如果使用 KDTree 加速 if use_kdtree: tree = KDTree(dataSet) distances, indices = tree.query(input_vector.reshape(1, -1), k=k) nearest_labels = np.array(labels)[indices[0]] predicted_label = np.bincount(nearest_labels).argmax() return predicted_label # 如果不使用 KDTree, 选择距离度量 if metric == 'euclidean': distances = np.linalg.norm(dataSet - input_vector, axis=1) elif metric == 'manhattan': distances = np.sum(np.abs(dataSet - input_vector), axis=1) elif metric == 'cosine': distances = distance.cdist([input_vector], dataSet, 'cosine')[0] elif metric == 'mahalanobis': VI = np.linalg.inv(np.cov(dataSet.T)) distances = distance.cdist([input_vector], dataSet, 'mahalanobis', VI=VI)[0] # 获取最近的 k 个样本 nearest_neighbors_indices = distances.argsort()[:k] nearest_labels = np.array(labels)[nearest_neighbors_indices] # 决策规则 if decision_rule == 'uniform': predicted_label = np.bincount(nearest_labels).argmax() elif decision_rule == 'weighted': weights = 1 / (distances[nearest_neighbors_indices] + 1e-5) # 避免距离为0时除零 predicted_label = np.bincount(nearest_labels, weights=weights).argmax() return predicted_label # 这里也写自己的代码实现 def load_dataset(directory): """ 从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 Args: - directory (str): 数据文件夹路径。 Returns: - np.array: 特征数据。 - np.array: 标签数据。 """ labels = [] data_list = [] for filename in os.listdir(directory): if filename.endswith(".txt"): # 确保读取的是 txt 文件 label = int(filename.split('_')[0]) labels.append(label) vector = img_to_vector(os.path.join(directory, filename)) data_list.append(vector) return np.array(data_list), np.array(labels) # 这里还写自己的代码实现 def img_to_vector(filename): """ 将二值图像转换为向量。 该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。 Args: - filename (str): 图像文件路径。 Returns: - np.array: 二值图像向量。 """ with open(filename, 'r') as f: # 确保使用文本模式读取 lines = f.readlines() vector = np.zeros((1024,), dtype=int) # 将其改为 (1024,) 的一维数组 for i in range(32): for j in range(32): vector[32 * i + j] = int(lines[i][j]) return vector if __name__ == "__main__": # 测试代码 train_data, train_labels = load_dataset("trainingDigits") test_data = ( "00000000000000110000000000000000" "00000000000011111000000000000000" "00000000000011111100000000000000" "00000000001111111110000000000000" "00000000001111111110000000000000" "00000000001111111100000000000000" "00000000011111111000000000000000" "00000000111111111000000000000000" "00000000111111110000000000000000" "00000000111111110000000000000000" "00000000111111110000000000000000" "00000000111111110000000000000000" "00000000111111100000000000000000" "00000001111111100000000000000000" "00000001111111100000000000000000" "00000001111111100000000000000000" "00000001111111111111000000000000" "00000001111111111111111000000000" "00000001111111111111111100000000" "00000011111111111111111110000000" "00000011111111111111111110000000" "00000001111111111111111110000000" "00000001111111111111111110000000" "00000000111111111100111111100000" "00000000111111111000111111100000" "00000000011111111001111111100000" "00000000011111111111111111000000" "00000000001111111111111111000000" "00000000000111111111111111000000" "00000000000011111111111100000000" "00000000000001111111110000000000" "00000000000000000111100000000000" ) test_vector = np.array([int(char) for char in test_data]).reshape(1, 1024) # 使用优化后的 KNN 进行预测 predicted_label_optimized = classify(test_vector, train_data, train_labels, k=5, metric='cosine', decision_rule='weighted', use_kdtree=False) print(f"优化后的预测标签: {predicted_label_optimized}") # 使用 KDTree 加速的 KNN 进行预测 predicted_label_kdtree = classify(test_vector, train_data, train_labels, k=5, use_kdtree=True) print(f"KDTree 加速后的预测标签: {predicted_label_kdtree}")