ITPub博客

首页 > 人工智能 > > python机器学习:监督学习算法之K近邻算法

python机器学习:监督学习算法之K近邻算法

作者:youou 时间:2019-08-29 15:27:47 0 删除 编辑

中原说教育 


K近邻(K-NN)算法可以说是最简单的机器学习算法。构建模型只需要保存训练集即可。想要对新数据进行预测,算法会在训练数据集中找到最近的数据点,也就是他们的“邻居”。根据选取的邻居个数不同,其预测精度可能不一样,最简单的模型就是指选取一个邻居。

1、单一(或者10个)最近邻模型对forge数据集的预测结果代码和图形如下:

import mglearn

mglearn.plots.plot_knn_classification(n_neighbors=1)

mglearn.plots.plot_knn_classification(n_neighbors=10)

运行后生成的图形如下:

单一最近邻模型对forge数据集的预测结果

10个近邻模型对forge数据集的预测结果

由此可见,选择的近邻个数不同,预测结果有所变化。

2、下面,我们来看下分别使用1,2,8个近邻对forge数据进行分析预测,对应的代码如下:

import matplotlib.pyplot as plt

import mglearn

import numpy as np

from sklearn.model_selection import train_test_split

x, y = mglearn.datasets.make_forge()

x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=0)

from sklearn.neighbors import KNeighborsClassifier

clf = KNeighborsClassifier(n_neighbors=3)

clf.fit(x_train, y_train)

print("Test set predicitons: {}".format(clf.predict(x_test)))

print("Test set accuracy: {:.2f}".format(clf.score(x_test, y_test)))

fig, axes = plt.subplots(1, 3, figsize=(10, 3))

for n_neighbors, ax in zip([1, 2, 8], axes):

#fit方法返回对象本身,所以我们可以将实例化和拟合放在一行代码中

clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(x, y)

mglearn.plots.plot_2d_separator(clf, x, fill=True, eps=0.5, ax=ax, alpha=.4)

mglearn.discrete_scatter(x[:, 0], x[:, 1], y, ax=ax)

ax.set_title("{} neighbor(s)".format(n_neighbors))

ax.set_xlabel("feature 0")

ax.set_ylabel("feature 1")

axes[0].legend(loc=3)

运行后的带的决策辩解结果如下:

在选取近邻分别为1,2,8时的K近邻决策边界

如上分析,我们发现使用的近邻个数越多,则分类的曲线越平滑,也就是说,使用的紧邻越少对应越高的复杂度,使用的近邻个数越多对应越低的复杂度。

假如考虑极端情况,也就是近邻个数等于训练集中所有的数据点个数,那么每个测试点的邻居都完全相同(即所有训练点),所有预测的结果也完全相同(训练接种出现次数最多的类别)。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4729/viewspace-3160698/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-17

  • 博文量
    294
  • 访问量
    13387