柚子快报邀请码778899分享:k邻近算法:-机器学习之K近邻 - Ball Tree:适用于高维数据

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网 👁️ 521 次阅读

柚子快报邀请码778899分享:k邻近算法:-机器学习之K近邻

机器学习之K近邻

目录

算法简介算法原理数学表述距离度量K值的选择算法优缺点应用场景算法优化代码实现总结

算法简介

K近邻算法(K-Nearest Neighbors,简称KNN)是一种基于实例的学习算法,也是机器学习中最简单、最直观的算法之一。该算法由Cover和Hart于1968年提出,最初用于模式识别领域。

KNN的核心思想是:“近朱者赤,近墨者黑”。给定一个测试样本,基于某种距离度量找出训练集中与其最靠近的K个样本,然后基于这K个"邻居"的信息来进行预测。

KNN是一种 懒惰学习(Lazy Learning) 算法,它没有显式的训练过程,而是将训练数据存储起来,直到收到测试样本时才进行计算。

算法特点

非参数化:不需要对数据分布做任何假设基于实例:直接使用训练样本进行预测多用途:可用于分类和回归任务简单直观:易于理解和实现

算法原理

分类任务

对于分类问题,KNN的预测规则是多数投票:

y

^

=

arg

⁡

max

⁡

c

∑

i

=

1

K

I

(

y

i

=

c

)

\hat{y} = \arg\max_{c} \sum_{i=1}^{K} I(y_i = c)

y^​=argcmax​i=1∑K​I(yi​=c)

其中:

y

^

\hat{y}

y^​ 是预测的类别

c

c

c 是可能的类别

y

i

y_i

yi​ 是第i个最近邻的类别标签

I

(

⋅

)

I(\cdot)

I(⋅) 是指示函数

回归任务

对于回归问题,KNN的预测规则是平均值:

y

^

=

1

K

∑

i

=

1

K

y

i

\hat{y} = \frac{1}{K} \sum_{i=1}^{K} y_i

y^​=K1​i=1∑K​yi​

其中:

y

^

\hat{y}

y^​ 是预测值

y

i

y_i

yi​ 是第i个最近邻的目标值

加权KNN

为了考虑距离的影响,可以引入权重,通常使用距离的倒数作为权重:

w

i

=

1

d

(

x

,

x

i

)

α

w_i = \frac{1}{d(x, x_i)^\alpha}

wi​=d(x,xi​)α1​

其中:

w

i

w_i

wi​ 是第i个邻居的权重

d

(

x

,

x

i

)

d(x, x_i)

d(x,xi​) 是测试样本与第i个邻居的距离

α

\alpha

α 是幂参数,通常取1或2

加权分类:

y

^

=

arg

⁡

max

⁡

c

∑

i

=

1

K

w

i

⋅

I

(

y

i

=

c

)

\hat{y} = \arg\max_{c} \sum_{i=1}^{K} w_i \cdot I(y_i = c)

y^​=argcmax​i=1∑K​wi​⋅I(yi​=c)

加权回归:

y

^

=

∑

i

=

1

K

w

i

⋅

y

i

∑

i

=

1

K

w

i

\hat{y} = \frac{\sum_{i=1}^{K} w_i \cdot y_i}{\sum_{i=1}^{K} w_i}

y^​=∑i=1K​wi​∑i=1K​wi​⋅yi​​

数学表述

算法流程

给定训练数据集

D

=

{

(

x

1

,

y

1

)

,

(

x

2

,

y

2

)

,

.

.

.

,

(

x

n

,

y

n

)

}

D = \{(x_1, y_1), (x_2, y_2), ..., (x_n, y_n)\}

D={(x1​,y1​),(x2​,y2​),...,(xn​,yn​)},其中

x

i

∈

R

d

x_i \in \mathbb{R}^d

xi​∈Rd 是特征向量,

y

i

y_i

yi​ 是标签。

对于测试样本

x

x

x,KNN算法的步骤如下:

计算距离:计算

x

x

x 与训练集中每个样本

x

i

x_i

xi​ 的距离

d

(

x

,

x

i

)

d(x, x_i)

d(x,xi​) 排序:根据距离从小到大排序,选择前K个最近邻 预测:

分类:统计K个最近邻的类别,选择出现次数最多的类别回归:计算K个最近邻目标值的平均值

时间复杂度

训练阶段:

O

(

1

)

O(1)

O(1) - 不需要训练,只需存储数据预测阶段:

O

(

n

⋅

d

)

O(n \cdot d)

O(n⋅d) - 需要计算与所有n个训练样本的距离,每个距离计算涉及d维特征

空间复杂度为

O

(

n

⋅

d

)

O(n \cdot d)

O(n⋅d),需要存储所有训练样本。

距离度量

选择合适的距离度量对KNN的性能至关重要。常用的距离度量包括:

1. 欧氏距离 (Euclidean Distance)

最常用的距离度量,适用于连续特征:

d

(

x

,

x

i

) 拼多多帮助力入口

=

∑

j

=

1

d

(

x

j

−

x

i

,

j

)

2

=

∥

x

−

x

i

∥

2

d(x, x_i) = \sqrt{\sum_{j=1}^{d} (x_j - x_{i,j})^2} = \|x - x_i\|_2

d(x,xi​)=j=1∑d​(xj​−xi,j​)2

​=∥x−xi​∥2​

2. 曼哈顿距离 (Manhattan Distance)

也称为城市街区距离:

d

(

x

,

x

i

)

=

∑

j

=

1

d

∣

x

j

−

x

i

,

j

∣

=

∥

x

−

x

i

∥

1

d(x, x_i) = \sum_{j=1}^{d} |x_j - x_{i,j}| = \|x - x_i\|_1

d(x,xi​)=j=1∑d​∣xj​−xi,j​∣=∥x−xi​∥1​

3. 切比雪夫距离 (Chebyshev Distance)

适用于棋盘式移动的场景:

d

(

x

,

x

i

)

=

max

⁡

j

∣

x

j

−

x

i

,

j

∣

=

∥

x

−

x

i

∥

∞

d(x, x_i) = \max_{j} |x_j - x_{i,j}| = \|x - x_i\|_\infty

d(x,xi​)=jmax​∣xj​−xi,j​∣=∥x−xi​∥∞​

4. 闵可夫斯基距离 (Minkowski Distance)

上述距离的推广形式:

d

(

x

,

x

i

)

=

(

∑

j

=

1

d

∣

x

j

−

x

i

,

j

∣

p

)

1

/

p

=

∥

x

−

x

i

∥

p

d(x, x_i) = \left(\sum_{j=1}^{d} |x_j - x_{i,j}|^p\right)^{1/p} = \|x - x_i\|_p

d(x,xi​)=(j=1∑d​∣xj​−xi,j​∣p)1/p=∥x−xi​∥p​

当

p

=

1

p=1

p=1 时,为曼哈顿距离当

p

=

2

p=2

p=2 时,为欧氏距离当

p

→

∞

p \to \infty

p→∞ 时,为切比雪夫距离

5. 余弦相似度 (Cosine Similarity)

适用于文本数据和高维稀疏向量:

similarity

(

x

,

x

i

)

=

x

⋅

x

i

∥

x

∥

⋅

∥

x

i

∥

=

∑

j

=

1

d

x

j

⋅

x

i

,

j

∑

j

=

1

d

x

j

2

⋅

∑

j

=

1

d

x

i

,

j

2

\text{similarity}(x, x_i) = \frac{x \cdot x_i}{\|x\| \cdot \|x_i\|} = \frac{\sum_{j=1}^{d} x_j \cdot x_{i,j}}{\sqrt{\sum_{j=1}^{d} x_j^2} \cdot \sqrt{\sum_{j=1}^{d} x_{i,j}^2}}

similarity(x,xi​)=∥x∥⋅∥xi​∥x⋅xi​​=∑j=1d​xj2​

​⋅∑j=1d​xi,j2​

​∑j=1d​xj​⋅xi,j​​

距离可以表示为:

d

(

x

,

x

i

)

=

1

−

similarity

(

x

,

x

i

)

d(x, x_i) = 1 - \text{similarity}(x, x_i)

d(x,xi​)=1−similarity(x,xi​)

6. 马氏距离 (Mahalanobis Distance)

考虑特征之间的相关性:

d

(

x

,

x

i

)

=

(

x

−

x

i

)

T

Σ

−

1

(

x

−

x

i

)

d(x, x_i) = \sqrt{(x - x_i)^T \Sigma^{-1} (x - x_i)}

d(x,xi​)=(x−xi​)TΣ−1(x−xi​)

​

其中

Σ

\Sigma

Σ 是协方差矩阵。

距离度量选择建议

场景推荐距离度量一般连续特征欧氏距离高维稀疏数据余弦相似度特征相关性较强马氏距离离散/分类特征汉明距离

K值的选择

K值的选择对KNN算法的性能有重要影响,需要在偏差和方差之间进行权衡。

K值过小

特点:模型复杂,容易过拟合原因:只考虑极少数邻居,对噪声敏感表现:决策边界不规则,训练误差低但测试误差高

K值过大

特点:模型简单,容易欠拟合原因:考虑过多邻居,可能包含不相关的样本表现:决策边界平滑,可能忽略局部模式

K值选择经验法则

经验公式:

K

=

n

K = \sqrt{n}

K=n

​,其中n是训练样本数量 交叉验证:使用交叉验证选择最优K值 奇数选择:对于二分类问题,选择奇数K避免平票 一般范围:通常在3到20之间选择

偏差-方差权衡

总误差

=

偏差

2

+

方差

+

噪声

\text{总误差} = \text{偏差}^2 + \text{方差} + \text{噪声}

总误差=偏差2+方差+噪声

小K:低偏差,高方差大K:高偏差,低方差

最优K值应使总误差最小。

算法优缺点

优点

简单直观:算法原理简单,易于理解和实现无需训练:没有显式的训练过程,适合动态数据集多用途:同时适用于分类和回归问题非参数化:不需要对数据分布做假设理论保证:在足够数据下,KNN的误差率不超过贝叶斯误差率的2倍

缺点

计算复杂度高:预测时需要计算与所有训练样本的距离存储需求大:需要存储所有训练样本对维度敏感:高维数据下距离度量失效(维度灾难)对不平衡数据敏感:多数类可能主导预测结果对特征尺度敏感:需要特征标准化

维度灾难

在高维空间中,KNN面临严重的维度灾难问题:

d

max

−

d

min

d

min

→

1

当

d

→

∞

\frac{d_{\text{max}} - d_{\text{min}}}{d_{\text{min}}} \to 1 \quad \text{当} \quad d \to \infty

dmin​dmax​−dmin​​→1当d→∞

这意味着在高维空间中,最近邻和最远邻的距离差异变得很小,距离度量失去意义。

应用场景

1. 分类问题

手写数字识别:MNIST数据集分类图像分类:简单图像识别任务文本分类:文档分类、垃圾邮件检测推荐系统:基于用户的协同过滤

2. 回归问题

房价预测:基于相似房屋的价格预测缺失值填充:使用相似样本填充缺失数据异常检测:基于距离的异常值识别

3. 特定领域应用

医学诊断:基于相似病例的疾病诊断金融风控:信用评分、欺诈检测生物信息学:基因序列分类、蛋白质结构预测

算法优化

1. 特征缩放

由于KNN对特征尺度敏感,必须进行特征标准化:

Z-score标准化:

x

j

′

=

x

j

−

μ

j

σ

j

x'_j = \frac{x_j - \mu_j}{\sigma_j}

xj′​=σj​xj​−μj​​

其中

μ

j

\mu_j

μj​ 是第j个特征的均值,

σ

j

\sigma_j

σj​ 是标准差。

Min-Max归一化:

x

j

′

=

x

j

−

min

⁡

j

max

⁡

j

−

min

⁡

j

x'_j = \frac{x_j - \min_j}{\max_j - \min_j}

xj′​=maxj​−minj​xj​−minj​​

2. 降维技术

使用降维方法缓解维度灾难:

PCA (主成分分析):线性降维t-SNE:非线性降维,适合可视化UMAP:保持局部结构的降维

3. 加速算法

KD-Tree:适用于低维数据(d < 20)

O

(

n

log

⁡

n

)

O(n \log n)

O

(

log

⁡

n

)

O(\log n)

O(logn) 平均情况

Ball Tree:适用于高维数据

O

(

n

log

⁡

n

)

O(n \log n)

O

(

log

⁡

n

)

O(\log n)

O(logn) 平均情况

近似最近邻 (ANN):牺牲精度换取速度

LSH (局部敏感哈希)HNSW (分层可导航小世界图)Annoy (近似最近邻)FAISS (Facebook AI相似性搜索)

4. 数据采样

随机采样:减少训练样本数量聚类采样:从每个聚类中选择代表点边界采样:优先保留决策边界附近的样本

5. 并行化

距离计算可以并行化:

# 伪代码

parallel for each training sample xi:

compute distance d(x, xi)

sort distances

select top K

代码实现

Python实现(使用scikit-learn)

import numpy as np

from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor

from sklearn.model_selection import train_test_split, cross_val_score

from sklearn.preprocessing import StandardScaler

from sklearn.datasets import load_iris, make_regression

import matplotlib.pyplot as plt

# ==================== 分类任务 ====================

# 加载数据

iris = load_iris()

X, y = iris.data, iris.target

# 数据分割

X_train, X_test, y_train, y_test = train_test_split(

X, y, test_size=0.2, random_state=42

)

# 特征标准化

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)

X_test_scaled = scaler.transform(X_test)

# 选择最优K值

k_range = range(1, 31)

k_scores = []

for k in k_range:

knn = KNeighborsClassifier(n_neighbors=k)

scores = cross_val_score(knn, X_train_scaled, y_train, cv=5, scoring='accuracy')

k_scores.append(scores.mean())

# 绘制K值与准确率的关系

plt.figure(figsize=(10, 6))

plt.plot(k_range, k_scores, marker='o')

plt.xlabel('K Value')

plt.ylabel('Cross-Validation Accuracy')

plt.title('KNN: K Value vs Accuracy')

plt.grid(True)

plt.show()

# 选择最优K值

optimal_k = k_range[np.argmax(k_scores)]

print(f"Optimal K: {optimal_k}")

# 训练最终模型

knn_classifier = KNeighborsClassifier(

n_neighbors=optimal_k,

weights='distance', # 使用距离加权

metric='euclidean' # 欧氏距离

)

knn_classifier.fit(X_train_scaled, y_train)

# 预测

y_pred = knn_classifier.predict(X_test_scaled)

accuracy = knn_classifier.score(X_test_scaled, y_test)

print(f"Test Accuracy: {accuracy:.4f}")

# ==================== 回归任务 ====================

# 生成回归数据

X_reg, y_reg = make_regression(

n_samples=1000, n_features=10, noise=0.1, random_state=42

)

# 数据分割

X_train_reg, X_test_reg, y_train_reg, y_test_reg = train_test_split(

X_reg, y_reg, test_size=0.2, random_state=42

)

# 特征标准化

scaler_reg = StandardScaler()

X_train_reg_scaled = scaler_reg.fit_transform(X_train_reg)

X_test_reg_scaled = scaler_reg.transform(X_test_reg)

# 训练KNN回归模型

knn_regressor = KNeighborsRegressor(

n_neighbors=5,

weights='distance',

metric='manhattan'

)

knn_regressor.fit(X_train_reg_scaled, y_train_reg)

# 预测和评估

y_pred_reg = knn_regressor.predict(X_test_reg_scaled)

mse = np.mean((y_pred_reg - y_test_reg) ** 2)

r2 = knn_regressor.score(X_test_reg_scaled, y_test_reg)

print(f"Mean Squared Error: {mse:.4f}")

print(f"R² Score: {r2:.4f}")

从零实现KNN

import numpy as np

from collections import Counter

from sklearn.base import BaseEstimator, ClassifierMixin

from sklearn.metrics.pairwise import euclidean_distances

class KNNClassifier(BaseEstimator, ClassifierMixin):

"""K近邻分类器的自定义实现"""

def __init__(self, n_neighbors=5, weights='uniform', metric='euclidean'):

"""

参数:

- n_neighbors: 邻居数量K

- weights: 权重方式 ('uniform' 或 'distance')

- metric: 距离度量

"""

self.n_neighbors = n_neighbors

self.weights = weights

self.metric = metric

def fit(self, X, y):

"""存储训练数据"""

self.X_train = np.array(X)

self.y_train = np.array(y)

self.classes_ = np.unique(y)

return self

def _compute_distances(self, X):

"""计算距离矩阵"""

if self.metric == 'euclidean':

return euclidean_distances(X, self.X_train)

elif self.metric == 'manhattan':

# 曼哈顿距离

n_test = X.shape[0]

n_train = self.X_train.shape[0]

distances = np.zeros((n_test, n_train))

for i in range(n_test):

for j in range(n_train):

distances[i, j] = np.sum(np.abs(X[i] - self.X_train[j]))

return distances

else:

raise ValueError(f"Unknown metric: {self.metric}")

def predict(self, X):

"""预测类别"""

distances = self._compute_distances(X)

predictions = []

for i in range(len(X)):

# 获取K个最近邻的索引

neighbor_indices = np.argsort(distances[i])[:self.n_neighbors]

neighbor_labels = self.y_train[neighbor_indices]

if self.weights == 'uniform':

# 均匀权重:多数投票

label_counts = Counter(neighbor_labels)

prediction = label_counts.most_common(1)[0][0]

else:

# 距离加权

neighbor_distances = distances[i][neighbor_indices]

# 避免除以零

weights = 1.0 / (neighbor_distances + 1e-10)

# 计算每个类别的加权票数

class_weights = {}

for label, weight in zip(neighbor_labels, weights):

class_weights[label] = class_weights.get(label, 0) + weight

# 选择权重最大的类别

prediction = max(class_weights.items(), key=lambda x: x[1])[0]

predictions.append(prediction)

return np.array(predictions)

def predict_proba(self, X):

"""预测类别概率"""

distances = self._compute_distances(X)

probas = []

for i in range(len(X)):

neighbor_indices = np.argsort(distances[i])[:self.n_neighbors]

neighbor_labels = self.y_train[neighbor_indices]

if self.weights == 'uniform':

label_counts = Counter(neighbor_labels)

total = sum(label_counts.values())

class_probas = {

cls: label_counts.get(cls, 0) / total

for cls in self.classes_

}

else:

neighbor_distances = distances[i][neighbor_indices]

weights = 1.0 / (neighbor_distances + 1e-10)

class_weights = {}

for label, weight in zip(neighbor_labels, weights):

class_weights[label] = class_weights.get(label, 0) + weight

total_weight = sum(class_weights.values())

class_probas = {

cls: class_weights.get(cls, 0) / total_weight

for cls in self.classes_

}

probas.append([class_probas[cls] for cls in self.classes_])

return np.array(probas)

class KNNRegressor(BaseEstimator):

"""K近邻回归器的自定义实现"""

def __init__(self, n_neighbors=5, weights='uniform', metric='euclidean'):

self.n_neighbors = n_neighbors

self.weights = weights

self.metric = metric

def fit(self, X, y):

self.X_train = np.array(X)

self.y_train = np.array(y)

return self

def predict(self, X):

distances = euclidean_distances(X, self.X_train)

predictions = []

for i in range(len(X)):

neighbor_indices = np.argsort(distances[i])[:self.n_neighbors]

neighbor_values = self.y_train[neighbor_indices]

if self.weights == 'uniform':

prediction = np.mean(neighbor_values)

else:

neighbor_distances = distances[i][neighbor_indices]

weights = 1.0 / (neighbor_distances + 1e-10)

prediction = np.sum(weights * neighbor_values) / np.sum(weights)

predictions.append(prediction)

return np.array(predictions)

# 使用示例

if __name__ == "__main__":

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

# 分类示例

iris = load_iris()

X, y = iris.data, iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

knn = KNNClassifier(n_neighbors=5, weights='distance')

knn.fit(X_train, y_train)

predictions = knn.predict(X_test)

accuracy = np.mean(predictions == y_test)

print(f"Custom KNN Accuracy: {accuracy:.4f}")

总结

K近邻算法是机器学习中最基础且重要的算法之一。以下是对KNN的全面总结:

核心要点

算法本质:基于实例的懒惰学习算法,通过最近邻进行预测关键参数:K值的选择需要在偏差和方差之间权衡距离度量:选择合适的距离度量对算法性能至关重要特征处理:必须进行特征标准化以消除尺度影响

适用场景

场景适用性说明小样本数据⭐⭐⭐⭐⭐计算开销小,效果良好低维数据⭐⭐⭐⭐⭐距离度量有效多类别分类⭐⭐⭐⭐天然支持多分类实时预测⭐⭐预测时间较长高维数据⭐⭐需要降维处理大规模数据⭐需要加速优化

最佳实践

数据预处理:始终进行特征标准化K值选择:使用交叉验证选择最优K值距离度量:根据数据特点选择合适的距离度量加速优化:对于大数据集使用KD-Tree或近似算法加权策略:考虑使用距离加权提高性能

与其他算法对比

算法训练时间预测时间解释性适用场景KNNO(1)O(n)高小样本、低维决策树O(n log n)O(log n)高可解释性要求高SVMO(n²) ~ O(n³)O(n_sv)中中小样本神经网络O(epochs × n)O(1)低大规模复杂数据

柚子快报邀请码778899分享:k邻近算法:-机器学习之K近邻

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧