From 42a492551b554819127dcbad67c2e42df55500b9 Mon Sep 17 00:00:00 2001 From: zhangchenghong <1598349064@qq.com> Date: Sun, 20 Oct 2024 13:37:56 +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 | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/function.py b/function.py index d2ed52e..aeea5fa 100644 --- a/function.py +++ b/function.py @@ -61,15 +61,22 @@ def classify(input_vector, dataSet, labels, k=2): - int: 预测的分类标签。 """ # 计算输入向量与训练集之间的欧氏距离 - distances = np.sum((input_vector - dataSet) ** 2, axis=1) ** 0.5 - # 根据距离排序并获取索引 + distances = np.sum((input_vector - dataSet) ** 2, axis=1) sorted_indices = distances.argsort() - # 选择距离最近的k个点 - k_nearest_labels = labels[sorted_indices[:k]].tolist() # 将 NumPy 数组转换为列表 - # 统计k个点中各类别的数量 - count = Counter(k_nearest_labels) - # 返回数量最多的类别标签 - return count.most_common(1)[0][0] + k_nearest_distances = distances[sorted_indices[:k]] + k_nearest_labels = labels[sorted_indices[:k]] + + # 计算权重(距离的倒数) + weights = 1 / k_nearest_distances + # 归一化权重 + weights /= weights.sum() + + # 计算加权投票 + weighted_votes = np.zeros((10,)) + for label, weight in zip(k_nearest_labels, weights): + weighted_votes[label] += weight + + return np.argmax(weighted_votes) # 这里也写自己的代码实现 def load_dataset(directory): @@ -83,22 +90,21 @@ def load_dataset(directory): - np.array: 特征数据(Mx1024)。 - np.array: 标签数据(Mx1)。 """ - # 初始化特征数据列表和标签列表 feature_list = [] label_list = [] - # 遍历目录中的所有文件 for file in os.listdir(directory): - # 获取文件的完整路径 file_path = os.path.join(directory, file) - # 将图像文件转换为向量 feature_vector = img_to_vector(file_path) - # 将特征向量添加到列表中 feature_list.append(feature_vector) - # 获取文件名中的标签并添加到标签列表中 label_list.append(int(file.split('_')[0])) - # 将特征列表和标签列表转换为numpy数组 feature_matrix = np.array(feature_list) label_array = np.array(label_list) + + # 特征缩放(归一化) + min_value = np.min(feature_matrix) + max_value = np.max(feature_matrix) + feature_matrix = (feature_matrix - min_value) / (max_value - min_value) + return feature_matrix, label_array # 这里还写自己的代码实现 def img_to_vector(filename):