diff --git a/function.py b/function.py index a840fee..31e1330 100644 --- a/function.py +++ b/function.py @@ -1,9 +1,7 @@ -#function.py +# function.py import numpy as np import os -from collections import Counter -id="202210423115" -name="李煜锋" + def img_to_vector(filename): """ 将二值图像转换为向量。 @@ -33,7 +31,6 @@ def load_dataset(directory): feature_list = [] label_list = [] - print(f"正在加载目录: {directory}") # 遍历目录,加载数据 for filename in os.listdir(directory): if filename.endswith('.txt'): @@ -52,6 +49,7 @@ def load_dataset(directory): labels = np.array(label_list) return features, labels +from collections import Counter def knn_classify(input_vector, dataSet, labels, k=3): """ @@ -79,29 +77,14 @@ def knn_classify(input_vector, dataSet, labels, k=3): label_count = Counter(top_k_labels) return label_count.most_common(1)[0][0] +# 加载训练数据 +train_data, train_labels = load_dataset('C:\\Users\\Administrator\\Desktop\\trainingDigits') -# 主程序 -if __name__ == '__main__': - # 使用绝对路径替换为你数据集的路径 - train_directory = r'C:\Users\Administrator\Desktop\trainingDigits' - test_directory = r'C:\Users\Administrator\Desktop\testDigits' - - # 加载训练数据 - train_data, train_labels = load_dataset(train_directory) - - # 加载测试数据 - test_data, test_labels = load_dataset(test_directory) - - # 测试 kNN 分类器 - correct_predictions = 0 - - for i in range(len(test_data)): - predicted_label = knn_classify(test_data[i], train_data, train_labels, k=3) - true_label = test_labels[i] - print(f"预测标签: {predicted_label}, 真实标签: {true_label}") - - if predicted_label == true_label: - correct_predictions += 1 - - accuracy = correct_predictions / len(test_data) * 100 - print(f"分类准确率: {accuracy:.2f}%") +# 加载测试数据 +test_data, test_labels = load_dataset('C:\\Users\\Administrator\\Desktop\\testDigits') + +# 选择一个测试样本,进行分类 +for i in range(len(test_data)): + predicted_label = knn_classify(test_data[i], train_data, train_labels, k=3) + true_label = test_labels[i] + print(f"预测标签: {predicted_label}, 真实标签: {true_label}")