generated from LufsX/Challenge-kNN
This commit is contained in:
+12
-6
@@ -1,6 +1,6 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
from collections import Counter
|
||||
|
||||
|
||||
"""
|
||||
挑战说明:
|
||||
@@ -43,11 +43,17 @@ name = "邓杰元"
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify0(inX, dataSet, labels, k=20):
|
||||
distances = [np.sqrt(np.sum((x - inX) ** 2)) for x in dataSet]
|
||||
k_indices = np.argsort(distances)[:k]
|
||||
|
||||
most_common = Counter(k_nearest_labels).most_common(1)
|
||||
return most_common[0][0]
|
||||
# 计算输入向量与训练集中每个样本的欧氏距离
|
||||
distances = np.sqrt(np.sum((dataSet - input_vector) ** 2, axis=1))
|
||||
|
||||
# 获取距离最小的k个样本的索引
|
||||
k_indices = np.argsort(distances)[:k]
|
||||
|
||||
# 获取这k个样本的标签
|
||||
k_nearest_labels = labels[k_indices]
|
||||
|
||||
# 找出出现次数最多的标签
|
||||
most_common = Counter(k_nearest_labels).most_common(1)
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user