From 3fb10047c2940fa6e513ec4f830f989a83d5c840 Mon Sep 17 00:00:00 2001 From: zhe <2904040094@qq.com> Date: Wed, 23 Oct 2024 19:47:32 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20function.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 225 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 143 insertions(+), 82 deletions(-) diff --git a/function.py b/function.py index 2c4159d..6913a9f 100644 --- a/function.py +++ b/function.py @@ -1,105 +1,166 @@ +# function.py import numpy as np import os from scipy.spatial.distance import mahalanobis -from collections import Counter -# 学号和姓名(这部分在实际代码中可能不需要,但为了完整性保留) -id = "202210423111" -name = "" +""" +实验说明: +- 自行编写实现数据加载与 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 = "202210423111" +name = "李劲" + + +""" +参数说明: +- input_vector (numpy array): 输入待分类的样本。 +- dataSet (numpy array): 训练数据集。 +- labels (list or numpy array): 训练集对应的标签。 +- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 +返回值: +- int: 预测的分类标签。 +""" + -def classify(input_vector, dataSet, labels, mean_vector, inv_cov_matrix, k=1): +def classify(input_vector, dataSet, labels, k=3): # 设置 k 的默认值为 3 """ KNN 分类算法,使用马氏距离。 + + Args: + - input_vector (numpy array): 输入待分类的样本。 + - dataSet (numpy array): 训练数据集。 + - labels (list or numpy array): 训练集对应的标签。 + - k (int): kNN 算法参数,选择距离最小的 k 个样本进行投票。 + + Returns: + - int: 预测的分类标签。 """ - # 确保输入向量与训练数据集的维度一致 - input_vector = input_vector.reshape(1, -1) + # 计算训练数据集的均值向量 + mean_vec = np.mean(dataSet, axis=0) - # 计算每个数据点到输入向量的马氏距离 - mahalanobis_distances = [] - for data_point in dataSet: - dist = mahalanobis(data_point.reshape(1, -1), input_vector, inv_cov_matrix) - mahalanobis_distances.append(dist) + # 计算训练数据集的协方差矩阵 + cov_mat = np.cov(dataSet, rowvar=False) - # 将距离列表转换为 NumPy 数组,方便后续操作 - mahalanobis_distances = np.array(mahalanobis_distances) + # 计算输入样本到所有训练样本的马氏距离 + # 注意:mahalanobis 函数要求输入二维数组,因此需要对 input_vector 进行 reshape + # 同时,dataSet 也需要是二维数组,如果它是三维的(例如有多个特征图),则需要先展平 + inv_covmat = np.linalg.inv(cov_mat) # 计算协方差矩阵的逆 + distances = [] + for row in dataSet: + dist = mahalanobis(input_vector.reshape(1, -1), row.reshape(1, -1), inv_covmat) + distances.append(dist) - # 获取距离最近的 k 个样本的索引 - k_indices = np.argsort(mahalanobis_distances)[:k] + # 选择距离最小的 k 个样本的索引 + k_indices = np.argsort(distances)[:k] - # 获取最近邻样本的标签 + # 选择这些样本对应的标签 k_nearest_labels = [labels[i] for i in k_indices] - # 找出出现次数最多的标签 - most_common = Counter(k_nearest_labels).most_common(1)[0][0] - - return most_common + # 返回出现次数最多的标签 + from collections import Counter + most_common = Counter(k_nearest_labels).most_common(1) + return most_common[0][0] def load_dataset(directory): """ - 从文件夹中加载数据,并计算均值向量和协方差矩阵。 - """ - features = [] - labels = [] - - # 遍历文件夹中的所有文件 - for filename in os.listdir(directory): - if filename.endswith(".txt"): # 假设文件是 .txt 格式 - filepath = os.path.join(directory, filename) - - try: - label = int(filename.split('_')[0]) - image_vector = img_to_vector(filepath) - features.append(image_vector) - labels.append(label) - except Exception as e: - print(f"Error processing file {filepath}: {e}") - - features = np.array(features) - labels = np.array(labels) + 从文件夹中加载数据,并返回特征数据和标签数据。 + 这里假设文件夹中的每个文件都是一个二值图像,文件名包含了标签信息。 - # 假设cov_matrix是原始协方差矩阵 - - regularization_term = 1e-5 * np.eye(cov_matrix.shape[0]) - - cov_matrix_regularized = cov_matrix + regularization_term - - inv_cov_matrix = np.linalg.inv(cov_matrix_regularized) - # 计算均值向量和协方差矩阵 - - - return features, labels, mean_vector, inv_cov_matrix + Args: + - directory (str): 数据文件夹路径。 + + Returns: + - np.array: 特征数据。 + - np.array: 标签数据。 + """ + data = [] + labels = [] + for filename in os.listdir(directory): + if filename.endswith(".txt"): # 假设图像数据以文本形式存储,且文件名包含标签 + label = int(filename.split('_')[0]) # 从文件名中提取标签,这里假设文件名格式为 "label_xxx.txt" + img_vector = img_to_vector(os.path.join(directory, filename)) + data.append(img_vector) + labels.append(label) + return np.array(data), np.array(labels) def img_to_vector(filename): """ - 将二值图像转换为向量。 + 将二值图像(以文本形式存储)转换为向量。 + 这里假设图像数据是以空格分隔的 0 和 1 组成的字符串。 + + Args: + - filename (str): 图像文件路径。 + + Returns: + - np.array: 二值图像向量。 """ - try: - with open(filename) as file: - lines = file.readlines() - image_vector = np.array([int(char) for line in lines for char in line.strip()]) - return image_vector - except Exception as e: - print(f"Error reading file {filename}: {e}") - return np.zeros(1024) # 假设图像向量长度为1024 - -if __name__ == "__main__": - # 测试 - train_data, train_labels, mean_vector, inv_cov_matrix = load_dataset("trainingDigits") - - # 注意:这里的测试数据应该是一个二维数组,形状为 (1, 1024) - # 假设 test_data 是一个已经格式化为字符串的1024位二值图像 - test_data_str = ( - "00000000000000110000000000000000" - # ... (省略的测试数据,确保总长度为1024) - ) - test_data = np.array([int(char) for char in test_data_str]).reshape(1, 1024) - - predicted_label = classify( - test_data, - train_data, - train_labels, - mean_vector, - inv_cov_matrix, - ) - + with open(filename, 'r') as f: + img_str = f.read().strip() + img_vector = np.array([int(char) for char in img_str]).reshape(1, -1) + return img_vector.flatten() # 展平为一维向量 + + +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" + ) + predicted_label = classify( + np.array([int(char) for char in test_data]).reshape(1, 1024), + train_data, + train_labels, + ) + print(f"预测的标签: {predicted_label}") \ No newline at end of file