diff --git a/function.py b/function.py index 6829644..9e9362d 100644 --- a/function.py +++ b/function.py @@ -42,10 +42,15 @@ def classify(input_vector, dataSet, labels, k=2): - int: 预测的分类标签。 """ dataSet_size = dataSet.shape[0] - # 计算曼哈顿距离 + # 计算马氏距离 + cov_matrix = np.cov(dataSet.T) + inv_cov_matrix = np.linalg.inv(cov_matrix) diff_mat = np.tile(input_vector, (dataSet_size, 1)) - dataSet - abs_diff_mat = np.abs(diff_mat) - distances = abs_diff_mat.sum(axis=1) + 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 = {}