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

This commit is contained in:
2024-10-16 18:24:43 +08:00
parent 1fdadecf1b
commit 067b852fdc
+14 -6
View File
@@ -56,15 +56,23 @@ def classify0(inX, dataSet, labels, k=1):
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
dataSetSize = dataSet.shape[0] dataSetSize = dataSet.shape[0]
# 计算协方差矩阵及其逆矩阵
cov_matrix = np.cov(dataSet, rowvar=False)
inv_cov_matrix = np.linalg.inv(cov_matrix)
# 计算马氏距离
diffMat = inX - dataSet diffMat = inX - dataSet
sqDiffMat=diffMat**2 left_term = np.dot(diffMat, inv_cov_matrix)
sqDistances=sqDiffMat.sum(axis=1) mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1))
distances=sqDistances**0.5
sortedDistIndicies=distances.argsort() # 排序距离并选择前 k 个最近邻
sortedDistIndicies = mahalanobis_distances.argsort()
classCount = {} classCount = {}
for i in range(k): for i in range(k):
votellabel=labels[sortedDistIndicies[i]] vote_label = labels[sortedDistIndicies[i]]
classCount[votellabel]=classCount.get(votellabel,0)+1 classCount[vote_label] = classCount.get(vote_label, 0) + 1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0] return sortedClassCount[0][0]