From 2b14b9631afecf8ed1e5af8f7147dd713cf3400f Mon Sep 17 00:00:00 2001 From: wzy <675163717@qq.com> Date: Thu, 10 Oct 2024 18:48: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 | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/function.py b/function.py index b1f8c16..ec5c940 100644 --- a/function.py +++ b/function.py @@ -25,8 +25,8 @@ import os """ 请在这里填写学号和姓名,不填写即成绩无效。 """ -id = "202210423xxx" -name = "test_name" +id = "202210423209" +name = "万子玉" """ @@ -41,7 +41,7 @@ name = "test_name" # 这里写自己的代码实现 -def classify(input_vector, dataSet, labels, k=0): +def classify(input_vector, dataSet, labels, k=3): """ KNN 分类算法。 @@ -54,6 +54,22 @@ def classify(input_vector, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ + dists = [distance.euclidean(input_vector, data) for data in dataSet] + k_indices = np.argsort(dists)[:k] + k_nearest_labels = [labels[i] for i in k_indices] + + # 确保至少有一个近邻 + if not k_nearest_labels: + raise ValueError("No neighbors found; possible causes: k is too small or all distances are the same.") + + most_common = Counter(k_nearest_labels).most_common(1) + + # 检查most_common是否为空 + if most_common: + return most_common[0][0] + else: + # 如果为空,返回一个默认值或者抛出异常 + return None # 或者 raise ValueError("No common labels found") # 这里也写自己的代码实现 @@ -68,6 +84,15 @@ def load_dataset(directory): - np.array: 特征数据。 - np.array: 标签数据。 """ + data_list = [] + label_list = [] + for root, dirs, files in os.walk(directory): + for file in files: + file_path = os.path.join(root, file) + vector = img_to_vector(file_path) + data_list.append(vector) + label_list.append(int(file.split('_')[0])) + return np.array(data_list), np.array(label_list) # 这里还写自己的代码实现 @@ -82,6 +107,8 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ + with open(filename, 'r') as f: + return np.array([int(char) for char in f.read().strip()]).reshape(1, -1) if __name__ == "__main__":