use from import single function
Gitea Actions Challenge Test / Challenge-Actions (push) Successful in 11s

This commit is contained in:
2024-10-15 20:43:50 +08:00
parent baa3a0afc3
commit 7cd0a8f7db
+8 -7
View File
@@ -1,6 +1,7 @@
# function.py
import numpy as np
import time
from numpy.linalg import inv
from numpy import sum, argpartition, bincount, argmax, cov, loadtxt
"""
挑战说明:
@@ -55,29 +56,29 @@ def classify0(inX, dataSet, labels, k=8, _cache={"VI": None}):
# 管它三七二十一,直接用缓存
if _cache["VI"] is None:
# 缓存数据集的协方差矩阵的逆
_cache["VI"] = np.linalg.inv(np.cov(dataSet.T))
_cache["VI"] = inv(cov(dataSet.T))
# 计算 inX 与数据集的差值
diff = dataSet - inX
# 使用矩阵运算计算马氏距离
distances = np.sum(diff @ _cache["VI"] * diff, axis=1)
distances = sum(diff @ _cache["VI"] * diff, axis=1)
# 对距离排序,获取前 k 个最近的样本索引
sortedDistIndices = np.argpartition(distances, 8)[:8]
sortedDistIndices = argpartition(distances, 8)[:8]
# 统计前 k 个样本的标签
classCount = np.bincount(labels[sortedDistIndices])
classCount = bincount(labels[sortedDistIndices])
# 返回出现次数最多的标签
return np.argmax(classCount)
return argmax(classCount)
def load_data(file_path):
"""
加载 TSV 格式数据文件。
"""
data = np.loadtxt(file_path, delimiter="\t")
data = loadtxt(file_path, delimiter="\t")
features = data[:, :-1]
labels = data[:, -1].astype(int)
return features, labels