chore: only use numpy
Gitea Actions Test / Exp-Actions (push) Successful in 9s

This commit is contained in:
2024-09-27 21:01:18 +08:00
parent 07d82589f6
commit 8d060a9a27
2 changed files with 8 additions and 17 deletions
+8 -16
View File
@@ -52,31 +52,23 @@ def classify0(inX, dataSet, labels):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
# 获取数据集的大小
dataSetSize = dataSet.shape[0]
# 计算数据集的协方差矩阵的逆 # 计算数据集的协方差矩阵的逆
VI = np.linalg.inv(np.cov(dataSet.T)) VI = np.linalg.inv(np.cov(dataSet.T))
# 计算 Mahalanobis 距离 # 计算 inX 与数据集的差值
distances = np.zeros(dataSetSize) diff = dataSet - inX
for i in range(dataSetSize):
distances[i] = mahalanobis(inX, dataSet[i], VI) # 使用矩阵运算计算马氏距离
distances = np.sqrt(np.sum(diff @ VI * diff, axis=1))
# 对距离排序,获取前 k 个最近的样本索引 # 对距离排序,获取前 k 个最近的样本索引
sortedDistIndices = distances.argsort() sortedDistIndices = np.argsort(distances)
# 统计前 k 个样本的标签 # 统计前 k 个样本的标签
classCount = {} classCount = np.bincount(labels[sortedDistIndices[:8]])
for i in range(9):
voteLabel = labels[sortedDistIndices[i]]
classCount[voteLabel] = classCount.get(voteLabel, 0) + 1
# 返回出现次数最多的标签 # 返回出现次数最多的标签
sortedClassCount = sorted( return np.argmax(classCount)
classCount.items(), key=operator.itemgetter(1), reverse=True
)
return sortedClassCount[0][0]
def load_data(file_path): def load_data(file_path):
-1
View File
@@ -1,3 +1,2 @@
numpy==2.1.1 numpy==2.1.1
requests==2.32.3 requests==2.32.3
scipy