sklearn中的nearest neighbor

本文深入讲解KNN算法的基础原理及应用实例,包括分类与回归两种情况,并提供了详细的sklearn库使用指南。

KNN介绍

基础原理没什么介绍的,可以参考我的KNN原理和实现,里面介绍了KNN的原理同时使用KNN来进行mnist分类

KNN in sklearn

sklearn是这么说KNN的:

The principle behind nearest neighbor methods is to find a predefined number of training samples closest in distance to the new point, and predict the label from these. The number of samples can be a user-defined constant (k-nearest neighbor learning), or vary based on the local density of points (radius-based neighbor learning). The distance can, in general, be any metric measure: standard Euclidean distance is the most common choice. Neighbors-based methods are known as non-generalizing machine learning methods, since they simply “remember” all of its training data (possibly transformed into a fast indexing structure such as a Ball Tree or KD Tree.).

接口介绍

sklearn.neighbors

主要有两个:

  • KNeighborsClassifier(RadiusNeighborsClassifier)
  • kNeighborsRegressor (RadiusNeighborsRefressor)

其它的还有一些,不多说,上图:
knn

classifier

接口定义

KNeighborsClassifier(n_neighbors=5, weights=’uniform’, algorithm=’auto’, leaf_size=30, p=2, metric=’minkowski’, metric_params=None, n_jobs=1, **kwargs)

参数介绍

需要注意的点就是:

  1. weights(各个neighbor的权重分配)
  2. metric(距离的度量)

例子

这次就不写mnist分类了,其实也很简单,官网的教程就可以说明问题了

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets

n_neighbors = 15

# 导入iris数据集
iris = datasets.load_iris()  
# iris特征有四个,这里只使用前两个特征来做分类
X = iris.data[:, :2] 
# iris的label 
y = iris.target  

h = .02  # step size in the mesh

# colormap
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

for weights in ['uniform', 'distance']:
    # KNN分类器
    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    # fit
    clf.fit(X, y)

    # Plot the decision boundary.     
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    # predict
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"
              % (n_neighbors, weights))

plt.show()

其实非常简单,如果去除画图的代码其实就三行:

  1. clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
  2. clf.fit(X, y)
  3. clf.predict(Z)

如果你的数据不是uniformaly sampled的,你会需要用到RadiusNeighrborsClassifier,使用方法保持一致

regressor

大部分说KNN其实是说的是分类器,其实KNN还可以做回归,官网教程是这么说的:

Neighbors-based regression can be used in cases where the data labels are continuous rather than discrete variables. The label assigned to a query point is computed based the mean of the labels of its nearest neighbors.
例子

同样是官网的例子

import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors

np.random.seed(0)
X = np.sort(5 * np.random.rand(40, 1), axis=0)
T = np.linspace(0, 5, 500)[:, np.newaxis]
y = np.sin(X).ravel()

# Add noise to targets
y[::5] += 1 * (0.5 - np.random.rand(8))

n_neighbors = 5

for i, weights in enumerate(['uniform', 'distance']):
    knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)
    y_ = knn.fit(X, y).predict(T)

    plt.subplot(2, 1, i + 1)
    plt.scatter(X, y, c='k', label='data')
    plt.plot(T, y_, c='g', label='prediction')
    plt.axis('tight')
    plt.legend()
    plt.title("KNeighborsRegressor (k = %i, weights = '%s')" % (n_neighbors, weights)  

    plt.show()

简单易懂,就不解释了

与classifier一样,如果你的数据不是uniformly sampled的,使用RadiusNeighborsRegressor更加合适


最近邻算法(Nearest Neighbor Algorithm)是一种广泛应用于模式识别、分类以及回归任务中的方法。然而,在实际应用过程中,可能会遇到“False Nearest Neighbor”(假近邻)问题。这一现象通常出现在高维数据空间中,尤其是当使用距离度量来寻找最近邻时。 ### False Nearest Neighbor 的定义与成因 在某些情况下,两个点可能因为维度灾难(Curse of Dimensionality)而在某些不相关的维度上表现出较小的距离差异,从而被错误地认为是彼此的邻居。这种现象导致了所谓的 **False Nearest Neighbor** 问题,即一个样本被错误地归类为另一个样本的最近邻,而实际上它们并不属于同一类别或相似特征。 这个问题的主要原因包括: - 数据维度较高,导致欧几里得距离等传统度量方式失效。 - 数据集中存在噪声或无关特征,这些特征会干扰最近邻的计算。 - 距离度量的选择不合适,无法准确反映样本之间的相似性 [^2]。 ### 解决方案 #### 1. 特征选择与降维 通过减少不必要的特征或进行降维处理,可以有效缓解维度灾难的问题。常用的方法包括: - **主成分分析(PCA)**:将数据投影到低维子空间中,保留最大方差方向。 - **线性判别分析(LDA)**:在降维的同时最大化类别间的可分性。 - **t-SNE 或 UMAP**:用于可视化和非线性降维,尤其适用于复杂的数据分布。 #### 2. 使用合适的距离度量 根据具体应用场景选择合适距离度量函数,例如: - **马氏距离(Mahalanobis Distance)**:考虑了各维度之间的相关性,适用于多变量正态分布数据。 - **余弦相似度(Cosine Similarity)**:适用于文本分类等场景,关注向量的方向而非大小。 - **动态时间规整(DTW)**:适用于时间序列数据,能够对齐不同长度的序列。 #### 3. 噪声过滤与异常值检测 - 在训练集预处理阶段去除噪声点,可以通过KNN自身或其他异常值检测技术(如Isolation Forest)实现。 - 使用基于密度的聚类算法(如DBSCAN)来识别并剔除稀疏区域的噪声点 。 #### 4. 多尺度邻域搜索 在多个尺度下进行邻域搜索,并结合结果以提高鲁棒性。例如,可以使用不同的K值运行KNN算法,并通过投票机制决定最终分类结果。 #### 5. 集成学习方法 采用集成策略,如Bagging或Boosting,结合多个KNN模型的结果,以降低单个模型受假近邻影响的风险。 ### 示例代码:使用PCA降维后进行KNN分类 ```python from sklearn.decomposition import PCA from sklearn.neighbors import KNeighborsClassifier from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # 加载数据集 data = load_iris() X, y = data.data, data.target # 使用PCA降维 pca = PCA(n_components=2) X_reduced = pca.fit_transform(X) # 分割训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X_reduced, y, test_size=0.3, random_state=42) # 训练KNN模型 knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, y_train) # 预测并评估 y_pred = knn.predict(X_test) print("Accuracy:", accuracy_score(y_test, y_pred)) ``` 这段代码展示了如何利用PCA进行特征降维后再使用KNN进行分类,从而避免由于高维空间带来的假近邻问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值