diff --git a/function.py b/function.py index 7ebb0c9..61879b6 100644 --- a/function.py +++ b/function.py @@ -29,25 +29,17 @@ name = "程悦" -def classify(input_vector, dataSet, labels, k=9): - """ - KNN 分类算法,添加了数据归一化处理。 - - Args: - - input_vector (numpy array): 输入待分类的样本。 - - dataSet (numpy array): 训练数据集。 - - labels (list or numpy array): 训练集对应的标签。 - - k (int): kNN 算法参数。 - - Returns: - - int: 预测的分类标签。 - """ +def classify(input_vector, dataSet, labels, k=2): dataSet_size = dataSet.shape[0] - # 计算欧氏距离 + # 计算马氏距离 + cov_matrix = np.cov(dataSet.T) + inv_cov_matrix = np.linalg.pinv(cov_matrix) diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet - sq_diff_mat = diff_mat ** 2 - sq_distances = sq_diff_mat.sum(axis=1) - distances = np.sqrt(sq_distances) + distances = [] + for i in range(dataSet_size): + distance = np.sqrt(np.dot(np.dot(diff_mat[i], inv_cov_matrix), diff_mat[i].T)) + distances.append(distance) + distances = np.array(distances) # 对距离进行排序 sorted_indices = distances.argsort() class_count = {}