From 3bfb4fa2de7ebc783eb6963822528af04f29995e Mon Sep 17 00:00:00 2001 From: Dengddd <3149942468@qq.com> Date: Tue, 15 Oct 2024 16:16:17 +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 | 131 ++++++++++++++++------------------------------------ 1 file changed, 41 insertions(+), 90 deletions(-) diff --git a/function.py b/function.py index fcfdcf1..fd14443 100644 --- a/function.py +++ b/function.py @@ -41,91 +41,48 @@ name = "邓龙树" # 这里写自己的代码实现 -import numpy as np -import os -from collections import Counter - -def classify(input_vector, dataSet, labels, k=1): - """ - 使用 KNN 算法对输入样本进行分类。 - - 参数: - input_vector (ndarray): 输入的特征向量,形状为 (1, n_features)。 - dataSet (ndarray): 训练集特征矩阵,形状为 (m_samples, n_features)。 - labels (ndarray): 训练集标签数组,形状为 (m_samples,)。 - k (int): 选择最近邻的个数,默认为 1。 - - 返回: - int: 预测的类别标签。 - """ - # 计算输入向量与训练集之间的欧氏距离 - distances = np.linalg.norm(dataSet - input_vector, axis=1) - # 根据距离排序并获取索引 - sorted_indices = np.argsort(distances) - # 选择距离最近的k个点 - k_nearest_labels = labels[sorted_indices[:k]] - # 统计k个点中各类别的数量 - count = Counter(k_nearest_labels) - # 返回数量最多的类别标签 - return count.most_common(1)[0][0] - -def load_dataset(directory): - """ - 加载数据集中的图像,并将其转换为特征向量和标签。 - - 参数: - directory (str): 包含图像文件的目录路径。 - - 返回: - tuple: 包含特征矩阵 (ndarray) 和标签数组 (ndarray) 的元组。 - """ - feature_list = [] - label_list = [] - try: - for file in os.listdir(directory): - file_path = os.path.join(directory, file) - feature_vector = img_to_vector(file_path) - label = int(file.split('_')[0]) - feature_list.append(feature_vector) - label_list.append(label) - feature_matrix = np.array(feature_list) - label_array = np.array(label_list) - except Exception as e: - print(f"Error loading dataset: {e}") - return None, None - return feature_matrix, label_array - -def img_to_vector(filename): - """ - 将二值图像转换为向量。 - - 参数: - filename (str): 图像文件的路径。 - - 返回: - ndarray: 转换后的特征向量,形状为 (1024,)。 - """ - try: - with open(filename, 'r') as file: - lines = file.readlines() - vector = np.array([int(char) for line in lines for char in line.strip()]).reshape(1024,) - except Exception as e: - print(f"Error converting image to vector: {e}") - return None - return vector - -if __name__ == "__main__": - # 加载训练数据集 - train_data, train_labels = load_dataset("trainingDigits") - if train_data is None or train_labels is None: - print("Failed to load training data.") - exit(1) +import numpy as np +import os +from collections import Counter -if __name__ == "__main__": - # 以下代码可用于测试,可自行随意修改 +def classify(input_vector, dataSet, labels, k=3): # 设置默认值 k=3 + """使用 KNN 算法对输入样本进行分类。""" + # 计算输入向量与训练集之间的欧氏距离 + distances = np.linalg.norm(dataSet - input_vector, axis=1) + # 根据距离排序并获取索引 + sorted_indices = distances.argsort() + # 选择距离最近的k个点 + k_nearest_labels = labels[sorted_indices[:k]] + # 统计k个点中各类别的数量 + count = Counter(k_nearest_labels) + # 返回数量最多的类别标签 + return count.most_common(1)[0][0] + +def load_dataset(directory): + """加载数据集中的图像,并将其转换为特征向量和标签。""" + feature_list = [] + label_list = [] + for file in os.listdir(directory): + file_path = os.path.join(directory, file) + feature_vector = img_to_vector(file_path) + feature_list.append(feature_vector) + label_list.append(int(file.split('_')[0])) + feature_matrix = np.array(feature_list) + label_array = np.array(label_list) + return feature_matrix, label_array + +def img_to_vector(filename): + """将二值图像转换为向量。""" + with open(filename, 'r') as file: + lines = file.read().strip() + vector = np.array(list(map(int, lines))).reshape(1024,) + return vector + +if __name__ == "__main__": + # 测试代码 train_data, train_labels = load_dataset("trainingDigits") - test_data = ( + test_data_str = ( "00000000000000110000000000000000" "00000000000011111000000000000000" "00000000000011111100000000000000" @@ -159,12 +116,6 @@ if __name__ == "__main__": "00000000000001111111110000000000" "00000000000000000111100000000000" ) - - predicted_label = classify( - np.array([int(char) for char in test_data]).reshape(1, 1024), - train_data, - train_labels, - ) - + test_data = np.array(list(map(int, test_data_str))).reshape(1, 1024) + predicted_label = classify(test_data, train_data, train_labels) print(f"预测的标签: {predicted_label}") -