更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 10s

This commit is contained in:
zhe
2024-10-23 11:40:33 +08:00
parent f89c9a36c1
commit 16b9377f35
+9 -5
View File
@@ -1,7 +1,8 @@
# function.py # function.py
import numpy as np import numpy as np
import os import os
from scipy.spatial.distance import mahalanobis
from collections import Counter
""" """
实验说明: 实验说明:
- 自行编写实现数据加载与 kNN 的手写数字分类算法。 - 自行编写实现数据加载与 kNN 的手写数字分类算法。
@@ -43,10 +44,14 @@ name = "李劲"
# 这里写自己的代码实现 # 这里写自己的代码实现
def classify(input_vector, dataSet, labels, k=1): def classify(input_vector, dataSet, labels, k=1):
""" """
KNN 分类算法。 KNN 分类算法,使用马氏距离。
""" """
# 计算欧式距离 # 计算协方差矩阵及其逆
distances = np.linalg.norm(dataSet - input_vector, axis=1) cov_matrix = np.cov(dataSet.T)
inv_cov_matrix = np.linalg.inv(cov_matrix)
# 计算马氏距离
distances = [mahalanobis(input_vector, point, inv_cov_matrix) for point in dataSet]
# 获取距离最近的 k 个样本的索引 # 获取距离最近的 k 个样本的索引
k_indices = np.argsort(distances)[:k] k_indices = np.argsort(distances)[:k]
@@ -55,7 +60,6 @@ def classify(input_vector, dataSet, labels, k=1):
k_nearest_labels = [labels[i] for i in k_indices] k_nearest_labels = [labels[i] for i in k_indices]
# 找出出现次数最多的标签 # 找出出现次数最多的标签
from collections import Counter
most_common = Counter(k_nearest_labels).most_common(1)[0][0] most_common = Counter(k_nearest_labels).most_common(1)[0][0]
return most_common return most_common