From 620afde54283ed70de400cf30f427ba1d28ef881 Mon Sep 17 00:00:00 2001 From: wzy <675163717@qq.com> Date: Tue, 22 Oct 2024 19:50:10 +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 | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/function.py b/function.py index 6a453bb..8cdca64 100644 --- a/function.py +++ b/function.py @@ -41,8 +41,10 @@ name = "万子玉" """ # 这里写自己的代码实现 -def euclidean_distance(a, b): - return np.sqrt(np.sum((a - b) ** 2)) +def mahalanobis_distance(x, mean, inv_covmat): + delta = x - mean + m_dist = np.sqrt(np.dot(np.dot(delta, inv_covmat), delta.T)) + return m_dist def classify(input_vector, dataSet, labels, k=2): """ @@ -57,7 +59,15 @@ def classify(input_vector, dataSet, labels, k=2): Returns: - int: 预测的分类标签。 """ - dists = [euclidean_distance(input_vector, data) for data in dataSet] + mean = np.mean(dataSet, axis=0) + covmat = np.cov(dataSet, rowvar=0) + inv_covmat = np.linalg.inv(covmat) + + dists = [mahalanobis_distance(input_vector, mean, inv_covmat)] + + for data in dataSet: + dists.append(mahalanobis_distance(data, mean, inv_covmat)) + k_indices = np.argsort(dists)[:k] k_nearest_labels = [labels[i] for i in k_indices] @@ -69,7 +79,7 @@ def classify(input_vector, dataSet, labels, k=2): if most_common: return most_common[0][0] else: - return None # 或者 raise ValueError("No common labels found") + return None # 这里也写自己的代码实现 @@ -156,4 +166,4 @@ if __name__ == "__main__": train_labels, ) - print(f"预测的标签: {predicted_label}") + print(f"预测的标签: {predicted_label}") \ No newline at end of file