generated from LufsX/Challenge-kNN
This commit is contained in:
+5
-6
@@ -1,4 +1,3 @@
|
||||
|
||||
import numpy as np
|
||||
|
||||
"""
|
||||
@@ -7,9 +6,9 @@ qin
|
||||
id = "202210423206"
|
||||
name = "詹宇豪"
|
||||
|
||||
def classify0(inX, dataSet, labels, k=3):
|
||||
def classify0(inX, dataSet, labels, k=1):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
KNN 分类算法(使用曼哈顿距离)。
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
@@ -18,8 +17,8 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 使用广播机制计算欧氏距离,提高效率
|
||||
distances = np.linalg.norm(dataSet - inX, axis=1)
|
||||
# 曼哈顿距离计算
|
||||
distances = np.sum(np.abs(dataSet - inX), axis=1)
|
||||
|
||||
# 按距离从小到大排序并获取对应的索引
|
||||
sorted_indices = np.argsort(distances)
|
||||
@@ -67,5 +66,5 @@ if __name__ == "__main__":
|
||||
|
||||
# 测试 classify0 函数
|
||||
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)
|
||||
Reference in New Issue
Block a user