From 14f011c9d5f6e81d01c1e9ffeb68ff4b641c4b26 Mon Sep 17 00:00:00 2001 From: fox <3147253307@qq.com> Date: Wed, 23 Oct 2024 10:42:06 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- function.py | 59 ++++++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/function.py b/function.py index e04c803..60936bb 100644 --- a/function.py +++ b/function.py @@ -57,19 +57,19 @@ def classify(input_vector, dataSet, labels, k=3): """ 使用欧式距离的 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 + + # 按距离升序排列,选出距离最小的k个点的索引 + nearest_neighbors = distances.argsort()[:k] + + # 获取这k个邻居的标签 + neighbor_labels = [labels[i] for i in nearest_neighbors] + + # 返回出现次数最多的标签 + predicted_label = max(set(neighbor_labels), key=neighbor_labels.count) + + return predicted_label # 这里也写自己的代码实现 @@ -89,20 +89,17 @@ def load_dataset(directory): labels = [] # 遍历文件夹中的所有文件 + data = [] + 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) + if filename.endswith(".txt"): + file_path = os.path.join(directory, filename) + data.append(img_to_vector(file_path)) + labels.append(int(filename.split('_')[0])) # 假设文件名格式为 'label_index.txt' + + return np.array(data), np.array(labels) # 这里还写自己的代码实现 @@ -117,11 +114,13 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ - 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 + with open(filename) as f: + lines = f.readlines() + vector = np.zeros((1, 1024)) + for i in range(32): # 图像是32x32的 + for j in range(32): + vector[0, 32 * i + j] = int(lines[i][j]) + return vector if __name__ == "__main__":