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

This commit is contained in:
2024-10-17 16:38:08 +08:00
parent 015b0ad1b1
commit ee382cb91b
+5 -6
View File
@@ -1,4 +1,3 @@
import numpy as np import numpy as np
""" """
@@ -7,9 +6,9 @@ qin
id = "202210423206" id = "202210423206"
name = "詹宇豪" name = "詹宇豪"
def classify0(inX, dataSet, labels, k=3): def classify0(inX, dataSet, labels, k=1):
""" """
KNN 分类算法。 KNN 分类算法(使用曼哈顿距离)。
Args: Args:
- inX (numpy array): 输入待分类的样本。 - inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。 - dataSet (numpy array): 训练数据集。
@@ -18,8 +17,8 @@ def classify0(inX, dataSet, labels, k=3):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
# 使用广播机制计算欧氏距离,提高效率 # 曼哈顿距离计算
distances = np.linalg.norm(dataSet - inX, axis=1) distances = np.sum(np.abs(dataSet - inX), axis=1)
# 按距离从小到大排序并获取对应的索引 # 按距离从小到大排序并获取对应的索引
sorted_indices = np.argsort(distances) sorted_indices = np.argsort(distances)
@@ -67,5 +66,5 @@ if __name__ == "__main__":
# 测试 classify0 函数 # 测试 classify0 函数
test_sample = np.array([65915, 3.868359, 0.128078]) test_sample = np.array([65915, 3.868359, 0.128078])
result = classify0(test_sample, train_data, train_labels, k=3) result = classify0(test_sample, train_data, train_labels, k=1)
print("Predicted label:", result) print("Predicted label:", result)