更新 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
+18 -10
View File
@@ -55,17 +55,25 @@ def classify0(inX, dataSet, labels, k=1):
Returns:
- int: 预测的分类标签。
"""
dataSetSize=dataSet.shape[0]
diffMat=inX - dataSet
sqDiffMat=diffMat**2
sqDistances=sqDiffMat.sum(axis=1)
distances=sqDistances**0.5
sortedDistIndicies=distances.argsort()
classCount={}
dataSetSize = dataSet.shape[0]
# 计算协方差矩阵及其逆矩阵
cov_matrix = np.cov(dataSet, rowvar=False)
inv_cov_matrix = np.linalg.inv(cov_matrix)
# 计算马氏距离
diffMat = inX - dataSet
left_term = np.dot(diffMat, inv_cov_matrix)
mahalanobis_distances = np.sqrt(np.sum(left_term * diffMat, axis=1))
# 排序距离并选择前 k 个最近邻
sortedDistIndicies = mahalanobis_distances.argsort()
classCount = {}
for i in range(k):
votellabel=labels[sortedDistIndicies[i]]
classCount[votellabel]=classCount.get(votellabel,0)+1
sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
vote_label = labels[sortedDistIndicies[i]]
classCount[vote_label] = classCount.get(vote_label, 0) + 1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]