From 19665a8133e12258e7a5d96562cf7523a872a242 Mon Sep 17 00:00:00 2001 From: lzh <202210423221@qq.com> Date: Wed, 16 Oct 2024 23:44:59 +0800 Subject: [PATCH] 11 --- function.py | 186 +++++++++++++++++----------------------------------- 1 file changed, 61 insertions(+), 125 deletions(-) diff --git a/function.py b/function.py index 96a55be..7757bb6 100644 --- a/function.py +++ b/function.py @@ -42,35 +42,10 @@ name = "廖子豪" # 这里写自己的代码实现 -def classify(input_vector, dataSet, labels, k=3): - """ - KNN 分类算法。 +import numpy as np +import os +from collections import Counter - Args: - - input_vector (numpy array): 输入待分类的样本。 - - dataSet (numpy array): 训练数据集。 - - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数,默认值为 3。 - - Returns: - - int: 预测的分类标签。 - """ - # 计算输入向量与数据集中每个向量之间的欧几里得距离 - distances = np.sqrt(np.sum((input_vector - dataSet) ** 2, axis=1)) - - # 获取距离最小的k个样本的索引 - k_indices = np.argsort(distances)[:k] - - # 获取这些样本对应的标签 - k_nearest_labels = labels[k_indices] - - # 使用Counter统计这些标签中出现次数最多的标签 - label_count = Counter(k_nearest_labels) - - # 返回出现次数最多的标签 - return label_count.most_common(1)[0][0] - -# 这里也写自己的代码实现 def img_to_vector(filename): """ 将二值图像转换为向量。 @@ -81,7 +56,10 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ - return np.array([int(char) for line in open(filename) for char in line.strip()]) + with open(filename, 'r') as file: + lines = file.readlines() + vector = [int(pixel) for line in lines for pixel in line.strip()] + return np.array(vector) def load_dataset(directory): """ @@ -96,30 +74,35 @@ def load_dataset(directory): """ images = [] labels = [] - - # 遍历目录中的所有子目录 for label_dir in os.listdir(directory): - # 构建完整的子目录路径 label_dir_path = os.path.join(directory, label_dir) - - # 确保是目录而不是文件 if os.path.isdir(label_dir_path): - # 遍历目录中的所有文件 for filename in os.listdir(label_dir_path): - # 构建完整的文件路径 file_path = os.path.join(label_dir_path, filename) - - # 读取文件内容并转换为向量 image_vector = img_to_vector(file_path) - - # 添加向量和标签到列表中 images.append(image_vector) labels.append(int(label_dir)) - - # 将列表转换为 NumPy 数组 return np.array(images), np.array(labels) -# 示例用法 +def classify(input_vector, dataSet, labels, k=3): + """ + KNN 分类算法。 + + Args: + - input_vector (numpy array): 输入待分类的样本。 + - dataSet (numpy array): 训练数据集。 + - labels (list or numpy array): 训练集对应的标签。 + - k (int): kNN 算法参数,默认值为 3。 + + Returns: + - int: 预测的分类标签。 + """ + distances = np.sqrt(np.sum((input_vector - dataSet) ** 2, axis=1)) + k_indices = np.argsort(distances)[:k] + k_nearest_labels = labels[k_indices] + label_count = Counter(k_nearest_labels) + return label_count.most_common(1)[0][0] + if __name__ == "__main__": train_dir = "trainingDigits" # 训练集目录 test_dir = "testDigits" # 测试集目录 @@ -131,86 +114,39 @@ if __name__ == "__main__": print("训练集标签形状:", train_labels.shape) print("测试集特征形状:", test_images.shape) print("测试集标签形状:", test_labels.shape) - - -# 这里还写自己的代码实现 -def img_to_vector(filename): - """ - 将二值图像转换为向量。 - Args: - - filename (str): 图像文件路径。 - - Returns: - - np.array: 二值图像向量。 - """ - with open(filename, 'r') as file: - # 读取文件的每一行 - lines = file.readlines() - - # 初始化一个空列表来存储向量 - vector = [] - - # 遍历每一行,将每个字符转换为整数并添加到列表中 - for line in lines: - vector.extend([int(pixel) for pixel in line.strip()]) - - # 将列表转换为 NumPy 数组并返回 - return np.array(vector) - -# 示例用法 -if __name__ == "__main__": - # 假设有一个图像文件路径 - filename = "path_to_your_image_file.txt" - - # 调用函数并打印结果 - image_vector = img_to_vector(filename) - print("图像向量:", image_vector) - print("向量形状:", image_vector.shape) - - -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}") + # 测试 classify 函数 + test_data = np.array([int(char) for char in "00000000000000110000000000000000000" # 示例数据 + "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"] * 4).reshape(1, 1024) + predicted_label = classify(test_data, train_images, train_labels) + print(f"预测的标签: {predicted_label}") \ No newline at end of file