From 7c8839246ce1a8e0d639c5f55bf0dc667f64a212 Mon Sep 17 00:00:00 2001 From: 202210423116 <2477589483@qq.com> Date: Wed, 16 Oct 2024 21:04:40 +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 | 46 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/function.py b/function.py index b1f8c16..2959a20 100644 --- a/function.py +++ b/function.py @@ -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,7 +54,22 @@ def classify(input_vector, dataSet, labels, k=0): Returns: - int: 预测的分类标签。 """ - + """ + 使用欧式距离的 kNN 分类算法。 + """ + # 计算欧式距离 + distances = np.linalg.norm(dataSet - input_vector, axis=1) + + # 获取距离最近的 k 个样本的索引 + k_indices = np.argsort(distances)[:k] + + # 获取最近邻样本的标签 + k_nearest_labels = [labels[i] for i in k_indices] + + # 找出出现次数最多的标签 + most_common = max(set(k_nearest_labels), key=k_nearest_labels.count) + + return most_common # 这里也写自己的代码实现 def load_dataset(directory): @@ -68,7 +83,24 @@ def load_dataset(directory): - np.array: 特征数据。 - np.array: 标签数据。 """ - + features = [] + labels = [] + + # 遍历文件夹中的所有文件 + for filename in os.listdir(directory): + if filename.endswith(".txt"): # 假设文件是 .txt 格式 + filepath = os.path.join(directory, filename) + + # 假设文件名格式为 "数字_编号.txt" + label = int(filename.split('_')[0]) + + # 加载文件中的二进制数据并转换为 1D 向量 + image_vector = img_to_vector(filepath) + + features.append(image_vector) + labels.append(label) + + return np.array(features), np.array(labels # 这里还写自己的代码实现 def img_to_vector(filename): @@ -82,9 +114,11 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ - - -if __name__ == "__main__": + with open(filename) as file: + lines = file.readlines() + image_vector = np.array([int(char) for line in lines for char in line.strip()]) + + return image_vector # 以下代码可用于测试,可自行随意修改 train_data, train_labels = load_dataset("trainingDigits")