KNN (K-Nearest Neighbors,K 最近邻算法)算法详解

一、 KNN 算法简介

KNN 是一种简单、直观的监督学习算法,其核心思想是 “物以类聚”。它通过找出训练集中与测试样本最相似的 K 个邻居,并根据它们的标签进行预测。既可以用于分类任务,也可以用于回归任务。

二、KNN 算法详解

在明确 KNN 算法的核心思想和应用流程后,我们通过数学公式和具体案例进一步拆解其实现逻辑。

2.1 核心决策公式:

分类任务(多数投票法)

假设测试样本的 K 个邻居标签集合为 { y 1 , y 2 , … , y K } \{y_1, y_2, \dots, y_K\} { y1,y2,,yK},预测类别 y ^ \hat{y} y^ 为出现频率最高的类别:

y ^ = arg ⁡ max ⁡ c ∈ Y ∑ i = 1 K I ( y i = c ) \hat{y} = \arg\max_{c \in \mathcal{Y}} \sum_{i=1}^{K} \mathbb{I}(y_i = c) y^=argmaxcYi=1KI(yi=c)

其中 I ( ⋅ ) \mathbb{I}(\cdot) I() 为指示函数,条件成立时返回 1,否则返回 0。

回归任务(均值预测法)

假设 K 个邻居的目标值为 { t 1 , t 2 , … , t K } \{t_1, t_2, \dots, t_K\} { t1,t2,,tK},预测值 t ^ \hat{t} t^ 为目标值的算术平均:

t ^ = 1 K ∑ i = 1 K t i \hat{t} = \frac{1}{K} \sum_{i=1}^{K} t_i t^=K1i=1K

以下是KNN(K-Nearest Neighbors)分类算法的伪代码: ```plaintext function KNN_Classification(training_data, training_labels, test_data, k): predictions = [] for each test_sample in test_data: distances = [] for each training_sample in training_data: # 计算测试样本与训练样本之间的距离 distance = calculate_distance(test_sample, training_sample) distances.append(distance) # 获取距离最近的k个训练样本的索引 k_nearest_indices = get_k_nearest_indices(distances, k) # 获取这k个最近邻的标签 k_nearest_labels = [training_labels[i] for i in k_nearest_indices] # 统计各个标签的出现次数 label_counts = count_labels(k_nearest_labels) # 找出出现次数最多的标签作为预测结果 predicted_label = get_most_common_label(label_counts) # 将预测结果添加到预测列表中 predictions.append(predicted_label) return predictions function calculate_distance(sample1, sample2): # 这里可以使用欧氏距离、曼哈顿距离等 # 以欧氏距离为例 squared_sum = 0 for i in range(len(sample1)): squared_sum += (sample1[i] - sample2[i]) ** 2 return sqrt(squared_sum) function get_k_nearest_indices(distances, k): # 对距离进行排序并获取前k个最小距离的索引 sorted_indices = argsort(distances) return sorted_indices[:k] function count_labels(labels): label_counts = {} for label in labels: if label in label_counts: label_counts[label] += 1 else: label_counts[label] = 1 return label_counts function get_most_common_label(label_counts): most_common_label = None max_count = 0 for label, count in label_counts.items(): if count > max_count: max_count = count most_common_label = label return most_common_label ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值