From d19abb296c7ddfe4a0b3d0efd027b3194e8ad673 Mon Sep 17 00:00:00 2001 From: zhe <2904040094@qq.com> Date: Wed, 23 Oct 2024 11:52:36 +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 | 71 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 44 insertions(+), 27 deletions(-) diff --git a/function.py b/function.py index 103fa23..e63d439 100644 --- a/function.py +++ b/function.py @@ -1,39 +1,42 @@ import numpy as np import os from scipy.spatial.distance import mahalanobis -from collections import Counter - -# 学号和姓名 +from collections import Counter + +# 学号和姓名(这部分在实际代码中可能不需要,但为了完整性保留) id = "202210423111" -name = "" - -def classify(input_vector, dataSet, labels, k=1): +name = "李劲" + +def classify(input_vector, dataSet, labels, mean_vector, inv_cov_matrix, k=1): """ KNN 分类算法,使用马氏距离。 """ - # 计算协方差矩阵及其逆 - cov_matrix = np.cov(dataSet.T) - if np.linalg.det(cov_matrix) == 0: # 检查奇异矩阵 - cov_matrix += np.eye(cov_matrix.shape[0]) * 1e-8 # 添加正则化 - inv_cov_matrix = np.linalg.inv(cov_matrix) - - # 计算马氏距离 - distances = [mahalanobis(input_vector, point, inv_cov_matrix) for point in dataSet] - + # 确保输入向量与训练数据集的维度一致 + input_vector = input_vector.reshape(1, -1) + + # 计算每个数据点到输入向量的马氏距离 + mahalanobis_distances = [] + for data_point in dataSet: + dist = mahalanobis(data_point.reshape(1, -1), input_vector, inv_cov_matrix) + mahalanobis_distances.append(dist) + + # 将距离列表转换为 NumPy 数组,方便后续操作 + mahalanobis_distances = np.array(mahalanobis_distances) + # 获取距离最近的 k 个样本的索引 - k_indices = np.argsort(distances)[:k] + k_indices = np.argsort(mahalanobis_distances)[:k] # 获取最近邻样本的标签 k_nearest_labels = [labels[i] for i in k_indices] # 找出出现次数最多的标签 most_common = Counter(k_nearest_labels).most_common(1)[0][0] - + return most_common def load_dataset(directory): """ - 从文件夹中加载数据。 + 从文件夹中加载数据,并计算均值向量和协方差矩阵。 """ features = [] labels = [] @@ -51,7 +54,15 @@ def load_dataset(directory): except Exception as e: print(f"Error processing file {filepath}: {e}") - return np.array(features), np.array(labels) + features = np.array(features) + labels = np.array(labels) + + # 计算均值向量和协方差矩阵 + mean_vector = np.mean(features, axis=0) + cov_matrix = np.cov(features, rowvar=False) + inv_cov_matrix = np.linalg.inv(cov_matrix) # 计算协方差矩阵的逆 + + return features, labels, mean_vector, inv_cov_matrix def img_to_vector(filename): """ @@ -64,20 +75,26 @@ def img_to_vector(filename): return image_vector except Exception as e: print(f"Error reading file {filename}: {e}") - return np.zeros(1024) # 假设有一个预期的向量长度,此处设为1024 - + return np.zeros(1024) # 假设图像向量长度为1024 + if __name__ == "__main__": # 测试 - train_data, train_labels = load_dataset("trainingDigits") - - test_data = ( + train_data, train_labels, mean_vector, inv_cov_matrix = load_dataset("trainingDigits") + + # 注意:这里的测试数据应该是一个二维数组,形状为 (1, 1024) + # 假设 test_data 是一个已经格式化为字符串的1024位二值图像 + test_data_str = ( "00000000000000110000000000000000" - # ... (省略的测试数据) + # ... (省略的测试数据,确保总长度为1024) ) + test_data = np.array([int(char) for char in test_data_str]).reshape(1, 1024) + predicted_label = classify( - np.array([int(char) for char in test_data]).reshape(1, 1024), + test_data, train_data, train_labels, + mean_vector, + inv_cov_matrix, ) - + print(f"预测的标签: {predicted_label}") \ No newline at end of file