From 4d8869506407be8cf65a840877f6d67db53c3207 Mon Sep 17 00:00:00 2001 From: cool Date: Thu, 17 Oct 2024 00:15:52 +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 | 143 +++++++++++++++++++++++----------------------------- 1 file changed, 63 insertions(+), 80 deletions(-) diff --git a/function.py b/function.py index b1f8c16..d9656bd 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import os """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423210" +name = "陈宇杰" """ @@ -40,92 +40,75 @@ name = "test_name" """ -# 这里写自己的代码实现 -def classify(input_vector, dataSet, labels, k=0): - """ - 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 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。 +# 加载数据的函数 +def load_data(directory): + file_list = os.listdir(directory) + data_matrix = [] + labels = [] + + for file_name in file_list: + file_path = os.path.join(directory, file_name) + # 读取txt文件并将其转化为向量 + vector = img_to_vector(file_path) + data_matrix.append(vector) + # 假设文件名格式为:{数字}_某些字符.txt,提取数字作为标签 + label = int(file_name.split('_')[0]) + labels.append(label) + + return np.array(data_matrix), np.array(labels) - Returns: - - int: 预测的分类标签。 - """ +# 将32x32的二值图像转换为1x1024的向量 +def img_to_vector(file_path): + vector = np.zeros((1, 1024)) + with open(file_path, 'r') as f: + lines = f.readlines() + for i in range(32): + for j in range(32): + vector[0, 32 * i + j] = int(lines[i][j]) + return vector +# kNN 分类函数 +def classify(input_vector, dataSet, labels, k=3): + # 计算欧氏距离 + distances = np.linalg.norm(dataSet - input_vector, axis=1) + # 获取距离最近的k个样本的标签 + nearest_neighbors = np.argsort(distances)[:k] + nearest_labels = labels[nearest_neighbors] + + # 确保 nearest_labels 是一维的,转换为 Python 列表 + nearest_labels = nearest_labels.flatten().tolist() + + # 投票,返回出现次数最多的标签 + most_common = Counter(nearest_labels).most_common(1) + return most_common[0][0] -# 这里也写自己的代码实现 -def load_dataset(directory): - """ - 从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。 +# 实验主程序 +def main(): + # 加载训练集和测试集 + training_data, training_labels = load_data('trainingdigits') + test_data, test_labels = load_data('testdigits') - Args: - - directory (str): 数据文件夹路径。 + # 测试 kNN 算法 + total_tests = len(test_data) + correct_predictions = 0 - Returns: - - np.array: 特征数据。 - - np.array: 标签数据。 - """ + for i in range(total_tests): + test_sample = test_data[i] + prediction = classify(test_sample, training_data, training_labels, k=3) + actual_label = test_labels[i] + print(f"测试样本 {i+1}: 预测值 = {prediction}, 实际值 = {actual_label}") -# 这里还写自己的代码实现 -def img_to_vector(filename): - """ - 将二值图像转换为向量。 - 该部分应为 load_dataset 函数的辅助子函数,可单独在这里实现,也可直接集成至 load_dataset 函数中。 + if prediction == actual_label: + correct_predictions += 1 - Args: - - filename (str): 图像文件路径。 + accuracy = correct_predictions / total_tests * 100 + print(f"\n分类精度: {accuracy:.2f}%") - Returns: - - np.array: 二值图像向量。 - """ +if __name__ == '__main__': + main() - -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}")