chore: opt running time
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 10s

This commit is contained in:
2024-10-09 00:29:15 +08:00
parent 20935c69e6
commit 224f8e1965
+11 -4
View File
@@ -1,6 +1,7 @@
# function.py
import numpy as np
import time
"""
挑战说明:
- 自行编写实现 KNN 分类算法。
@@ -38,7 +39,7 @@ name = "向兴宇"
# 这里写自己的代码实现
def classify0(inX, dataSet, labels, k=8):
def classify0(inX, dataSet, labels, k=8, _cache={"VI": None, "dataSet": None}):
"""
KNN 分类算法。
@@ -46,12 +47,18 @@ def classify0(inX, dataSet, labels, k=8):
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): 选择最近的 k 个样本,默认为 8。
Returns:
- int: 预测的分类标签。
"""
# 计算数据集的协方差矩阵的逆
VI = np.linalg.inv(np.cov(dataSet.T))
# 检查数据集是否发生变化
if _cache["dataSet"] is None or not np.array_equal(dataSet, _cache["dataSet"]):
# 计算并缓存数据集的协方差矩阵的逆
_cache["VI"] = np.linalg.inv(np.cov(dataSet.T))
_cache["dataSet"] = dataSet
VI = _cache["VI"]
# 计算 inX 与数据集的差值
diff = dataSet - inX
@@ -63,7 +70,7 @@ def classify0(inX, dataSet, labels, k=8):
sortedDistIndices = np.argsort(distances)
# 统计前 k 个样本的标签
classCount = np.bincount(labels[sortedDistIndices[:8]])
classCount = np.bincount(labels[sortedDistIndices[:k]])
# 返回出现次数最多的标签
return np.argmax(classCount)