generated from LufsX/Challenge-kNN
This commit is contained in:
+17
-32
@@ -43,38 +43,23 @@ name = "陈垣豪"
|
||||
# 这里写自己的代码实现
|
||||
def classify0(inX, dataSet, labels, k=0):
|
||||
def classify0(inX, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,请**自行设置默认值**,评测时仅会使用其默认值,不修改默认值将**无法通过**评测,**成绩为零**。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1))
|
||||
# 获取距离最小的 k 个样本的索引
|
||||
sorted_indices = np.argsort(distances)[:k]
|
||||
|
||||
# 计算输入样本与训练集中每个样本的欧氏距离
|
||||
distances = np.sqrt(np.sum((dataSet - inX) ** 2, axis=1))
|
||||
# 获取 k 个最近邻的标签
|
||||
nearest_labels = [labels[i] for i in sorted_indices]
|
||||
|
||||
# 获取距离最小的 k 个样本的索引
|
||||
sorted_indices = np.argsort(distances)[:k]
|
||||
|
||||
# 获取 k 个最近邻的标签
|
||||
nearest_labels = [labels[i] for i in sorted_indices]
|
||||
|
||||
# 统计 k 个最近邻中每个类别的出现次数
|
||||
label_count = {}
|
||||
for label in nearest_labels:
|
||||
if label in label_count:
|
||||
label_count[label] += 1
|
||||
else:
|
||||
label_count[label] = 1
|
||||
|
||||
# 找到出现次数最多的标签
|
||||
predicted_label = max(label_count, key=label_count.get)
|
||||
|
||||
return predicted_label
|
||||
# 统计 k 个最近邻中每个类别的出现次数
|
||||
label_count = {}
|
||||
for label in nearest_labels:
|
||||
if label in label_count:
|
||||
label_count[label] += 1
|
||||
else:
|
||||
label_count[label] = 1
|
||||
|
||||
# 找到出现次数最多的标签
|
||||
predicted_label = max(label_count, key=label_count.get)
|
||||
|
||||
return predicted_label
|
||||
|
||||
|
||||
Reference in New Issue
Block a user