generated from LufsX/Challenge-kNN
This commit is contained in:
+15
-12
@@ -54,25 +54,28 @@ def classify0(inX, dataSet,labels, k=3):
|
|||||||
inv_S[nonzero_indices] = 1 / S[nonzero_indices]
|
inv_S[nonzero_indices] = 1 / S[nonzero_indices]
|
||||||
inv_cov_matrix = VT.T @ np.diag(inv_S) @ U.T
|
inv_cov_matrix = VT.T @ np.diag(inv_S) @ U.T
|
||||||
|
|
||||||
# 计算马氏距离的平方
|
# 计算马氏距离
|
||||||
diff = normalized_dataSet - normalized_inX
|
diff = normalized_dataSet - normalized_inX
|
||||||
squared_distances = np.einsum('ij,jk->i', diff, inv_cov_matrix @ diff.T)
|
distances = np.sum(diff @ inv_cov_matrix * diff, axis=1)
|
||||||
|
|
||||||
# 获取距离最小的 k 个样本的索引
|
# 获取距离最小的 k 个样本的索引
|
||||||
sorted_indices = np.argsort(distances)[:k]
|
sorted_indices = np.argsort(distances)[:k]
|
||||||
|
|
||||||
# 获取 k 个最近邻的标签
|
# 获取 k 个最近邻的标签和对应的距离
|
||||||
nearest_labels = [labels[i] for i in sorted_indices]
|
nearest_labels = [labels[i] for i in sorted_indices]
|
||||||
|
nearest_distances = distances[sorted_indices]
|
||||||
|
|
||||||
# 统计 k 个最近邻中每个类别的出现次数
|
# 计算每个标签的加权投票
|
||||||
label_count = {}
|
label_weight = {}
|
||||||
for label in nearest_labels:
|
for i, label in enumerate(nearest_labels):
|
||||||
if label in label_count:
|
# 反距离作为权重,避免距离为0的情况
|
||||||
label_count[label] += 1
|
weight = 1 / (nearest_distances[i] + 1e-10) # 加一个小值避免除以零
|
||||||
|
if label in label_weight:
|
||||||
|
label_weight[label] += weight
|
||||||
else:
|
else:
|
||||||
label_count[label] = 1
|
label_weight[label] = weight
|
||||||
|
|
||||||
# 找到出现次数最多的标签
|
# 找到加权投票中出现次数最多的标签
|
||||||
predicted_label = max(label_count, key=label_count.get)
|
predicted_label = max(label_weight, key=label_weight.get)
|
||||||
|
|
||||||
return predicted_label
|
return predicted_label
|
||||||
|
|||||||
Reference in New Issue
Block a user