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

This commit is contained in:
2024-10-11 20:01:37 +08:00
parent 94edbcb0ce
commit 0c71a39b4f
+26 -2
View File
@@ -25,8 +25,8 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423230"
name = "尹家立"
"""
@@ -53,6 +53,30 @@ def classify0(inX, dataSet, labels, k=0):
Returns:
- int: 预测的分类标签。
"""
# Step 1: 计算协方差矩阵的逆矩阵
covMat = np.cov(dataSet, rowvar=False) # 计算协方差矩阵
invCovMat = np.linalg.inv(covMat) # 计算协方差矩阵的逆
# Step 2: 计算马氏距离
diffMat = dataSet - inX # 计算差值矩阵
left = np.dot(diffMat, invCovMat) # 左乘协方差矩阵的逆
mahalanobisDist = np.sqrt(np.sum(left * diffMat, axis=1)) # 计算马氏距离
# Step 3: 按距离排序,得到索引
sortedDistIndices = mahalanobisDist.argsort()
# Step 4: 选择距离最近的 k 个点的标签,并采用权重投票
classCount = {}
for i in range(k):
voteLabel = labels[sortedDistIndices[i]]
distance = mahalanobisDist[sortedDistIndices[i]]
weight = 1 / (distance + 1e-5) # 距离越小权重越大,防止除零
classCount[voteLabel] = classCount.get(voteLabel, 0) + weight
# Step 5: 按照加权后的类别得票数排序并返回得票最多的类别
sortedClassCount = sorted(classCount.items(), key=lambda item: item[1], reverse=True)
return sortedClassCount[0][0]
def load_data(file_path):