From d22de460917c9f90102d9120656648a54331053f Mon Sep 17 00:00:00 2001 From: wujunjie <297081150@qq.com> Date: Wed, 16 Oct 2024 00:28:45 +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 | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/function.py b/function.py index 6d3e96c..f95c84d 100644 --- a/function.py +++ b/function.py @@ -54,17 +54,13 @@ def classify(input_vector, dataSet, labels, k=3): Returns: - int: 预测的分类标签。 """ - if k > len(labels): - raise ValueError("k 不能大于训练集样本数") - min_vals = dataSet.min(axis=0) - max_vals = dataSet.max(axis=0) - norm_dataSet = (dataSet - min_vals) / (max_vals - min_vals) - norm_input_vector = (input_vector - min_vals) / (max_vals - min_vals) - - distances = np.linalg.norm(norm_dataSet - norm_input_vector, axis=1) - sorted_indices = distances.argsort() - nearest_labels = np.array(labels)[sorted_indices[:k]] - predicted_label = np.bincount(nearest_labels).argmax() + if k > len(labels): + raise ValueError("k 不能大于训练集样本数") + + distances = np.linalg.norm(dataSet - input_vector, axis=1) + sorted_indices = distances.argsort() + nearest_labels = np.array(labels)[sorted_indices[:k]] + predicted_label = np.bincount(nearest_labels).argmax() return predicted_label # 这里也写自己的代码实现 @@ -79,14 +75,16 @@ def load_dataset(directory): - np.array: 特征数据。 - np.array: 标签数据。 """ - data = [] - labels = [] - for filename in os.listdir(directory): - if filename.endswith(".txt"): - label = int(filename.split('_')[0]) - labels.append(label) - vector = img_to_vector(os.path.join(directory, filename)) - data.append(vector) + data = [] + labels = [] + for filename in os.listdir(directory): + if filename.endswith(".txt"): + # 提取文件名中的标签信息 + label = int(filename.split('_')[0]) + labels.append(label) + # 将图像文件转换为向量 + vector = img_to_vector(os.path.join(directory, filename)) + data.append(vector) return np.array(data), np.array(labels) # 这里还写自己的代码实现 @@ -101,9 +99,10 @@ def img_to_vector(filename): Returns: - np.array: 二值图像向量。 """ - with open(filename, 'r') as f: - lines = f.readlines() - vector = np.array([int(char) for line in lines for char in line.strip()]) + with open(filename, 'r') as f: + lines = f.readlines() + # 将32x32的字符矩阵转换为长度为1024的一维数组 + vector = np.array([int(char) for line in lines for char in line.strip()]) return vector if __name__ == "__main__":