diff --git a/function.py b/function.py index d103869..6b18f60 100644 --- a/function.py +++ b/function.py @@ -45,32 +45,18 @@ import numpy as np import os from collections import Counter -def classify_mahalanobis(input_vector, dataSet, labels, k=1): - """使用 KNN 算法并基于马氏距离对输入样本进行分类。""" - # 计算数据集的协方差矩阵及其逆矩阵 - cov_matrix = np.cov(dataSet, rowvar=False) - - # 对协方差矩阵添加正则化 - cov_matrix += np.eye(cov_matrix.shape[0]) * 1e-5 - - # 计算协方差矩阵的逆矩阵 - inv_cov_matrix = np.linalg.inv(cov_matrix) - - # 计算马氏距离 - diffMat = dataSet - input_vector - distances = np.sqrt(np.sum(np.dot(diffMat, inv_cov_matrix) * diffMat, axis=1)) - +def classify(input_vector, dataSet, labels, k=1): # 设置默认值 k=1 + """使用 KNN 算法对输入样本进行分类。""" + # 计算输入向量与训练集之间的欧氏距离 + distances = np.linalg.norm(dataSet - input_vector, axis=1) # 根据距离排序并获取索引 sorted_indices = distances.argsort() - # 选择距离最近的k个点 k_nearest_labels = labels[sorted_indices[:k]] - # 统计k个点中各类别的数量 count = Counter(k_nearest_labels) - # 返回数量最多的类别标签 - return count.most_common(1)[0][0] +return count.most_common(1)[0][0] # 为评测系统创建别名 classify = classify_mahalanobis