diff --git a/function.py b/function.py index b1f8c16..e5f3050 100644 --- a/function.py +++ b/function.py @@ -1,4 +1,3 @@ -# function.py import numpy as np import os @@ -21,12 +20,11 @@ import os - numpy: 2.1.1 """ - """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "20221042303" +name = "赵昊龙" """ @@ -41,7 +39,7 @@ name = "test_name" # 这里写自己的代码实现 -def classify(input_vector, dataSet, labels, k=0): +def classify(input_vector, dataSet, labels, k=3): """ KNN 分类算法。 @@ -54,6 +52,22 @@ def classify(input_vector, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ + # 计算输入向量与数据集中每个向量的欧式距离 + distances = [] + for i in range(dataSet.shape[0]): + dist = np.sqrt(np.sum((input_vector - dataSet[i]) ** 2)) + distances.append((dist, labels[i])) + + # 根据距离进行排序,取前k个最近邻 + distances.sort(key=lambda x: x[0]) + k_nearest_labels = [label for _, label in distances[:k]] + + # 统计前k个最近邻中出现次数最多的标签 + from collections import Counter + label_counts = Counter(k_nearest_labels) + most_common_label = label_counts.most_common(1)[0][0] + + return most_common_label # 这里也写自己的代码实现 @@ -68,6 +82,17 @@ def load_dataset(directory): - np.array: 特征数据。 - np.array: 标签数据。 """ + training_file_list = os.listdir(directory) + training_matrix = [] + training_labels = [] + + for file in training_file_list: + class_num = int(file.split('_')[0]) + vector = img_to_vector(os.path.join(directory, file)) + training_matrix.append(vector) + training_labels.append(class_num) + + return np.array(training_matrix), np.array(training_labels) # 这里还写自己的代码实现 @@ -82,6 +107,7 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ + return np.array([int(pixel) for pixel in open(filename).read().split()]) if __name__ == "__main__":