sklearn中的nearest neighbor

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)

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

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更加合适

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏人工智能

深度学习框架之一:Theano

正文共7163个字,1张图,预计阅读时间18分钟。 参考Lasagne官网(http://lasagne.readthedocs.io/en/latest/)t...

1916
来自专栏人工智能LeadAI

基于Tensorflow实现多层感知机网络MLPs

github:https://github.com/sladesha/deep_learning

1072
来自专栏算法channel

动态规划|约束条件下的三角最短路径

这篇文章总结了题目如何符合动态规划的特点,进而如何利用动态规划求解三角约束条件下的最短路径。 1 题目 Given a triangle, find the m...

3955
来自专栏一心无二用,本人只专注于基础图像算法的实现与优化。

图像处理中任意核卷积(matlab中conv2函数)的快速实现。

     卷积其实是图像处理中最基本的操作,我们常见的一些算法比如:均值模糊、高斯模糊、锐化、Sobel、拉普拉斯、prewitt边缘检测等等一些和领域相关的算...

6038
来自专栏数据科学与人工智能

【机器学习】监督学习之KNN

一、kNN算法分析 K最近邻(k-Nearest Neighbor,KNN)分类算法可以说是最简单的机器学习算法了。它采用测量不同特征值之间的距离方法进行分类。...

2568
来自专栏小樱的经验随笔

51Nod 1289 大鱼吃小鱼(模拟,经典好题)

1289 大鱼吃小鱼            题目来源:             Codility 基准时间限制:1 秒 空间限制:131072 KB 分值: ...

3137
来自专栏机器学习、深度学习

卫星图像中的车辆分析--A Large Contextual Dataset for Classification, Detection and Counting of Cars

A Large Contextual Dataset for Classification, Detection and Counting of Cars wi...

2559
来自专栏有趣的Python

15- 深度学习之神经网络核心原理与算法-多gpu实现CNN图片分类

3993
来自专栏简书专栏

基于xgboost+GridSearchCV的波士顿房价预测

2018年8月23日笔记 sklearn官方英文用户使用指南:https://sklearn.org/user_guide.html sklearn翻译中文...

6483
来自专栏Petrichor的专栏

Selective Search (选择搜索)

[1] Selective Search for Object Recognition [2] Computer vision seminar, 5/2/2...

3172

扫码关注云+社区