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

This commit is contained in:
2024-10-06 18:12:39 +08:00
parent 55750be82d
commit 65a57d4383
+16 -11
View File
@@ -39,7 +39,7 @@ name = "吴俊煯"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels,k=8):
def classify0(inX, dataSet, labels):
"""
KNN 分类算法。
@@ -51,19 +51,24 @@ def classify0(inX, dataSet, labels,k=8):
Returns:
- int: 预测的分类标签。
"""
# 确保 k 不大于数据集的大小
# 计算数据集的协方差矩阵的逆
VI = np.linalg.inv(np.cov(dataset.T))
# 计算 inX 与数据集的差值
diff = dataSet -inX
# 使用矩阵运算计算马氏距离
distances =np.sqrt(np,sum(diff @ VI * diff,axis=1))
# 获取数据集的大小
dataSetSize =dataSet.shape[0]
# 计算数据集的协方差矩阵的逆
VI = np.linalg.inv(np.cov(dataSet.T))
# 计算 Mahalanobis 距离
distances =npzeros(dataSetSize)
for i in range(dataSetSize):
distances[i]=mahalanobis(inX,dataSeti],VI)
# 对距离排序,获取前 k 个最近的样本索引
sortedDistIndices=np.argsort(distances)
sortedDistIndices=distances.argsort)
# 统计前 k 个样本的标签
classCount =np.bincount(labels[sortedDistIndices[:k]])
classCount ={}
for i in range(9):
voteLabel=labels[sortedDistIndices[i]]
classCount[voteLabel]=classCount.get(voteLabel,0)+1
# 返回出现次数最多的标签
return np.argmax(classCount)
sortedClasscount=sorted(classCount.items(),key=operator,itemgetter(1),reverse=True
return sortedclassCount[0][0]
def load_data(file_path):