赞
踩
监督学习是最常用的机器学习算法之一。
许多算法都有分类和回归两种形式。
1、forge数据集
使用的数据集:模拟的二分类数据集(forge数据集),有两个特征
import matplotlib.pyplot as plt
import mglearn
#生成数据集
X,y=mglearn.datasets.make_forge()
#绘图
mglearn.discrete_scatter(X[:,0],X[:,1],y)
plt.legend(["Class 0","Class 1"],loc=4)
plt.xlabel("First feature")
plt.ylabel("Second feature")
print("X.shape:{}".format(X.shape))
图中第一特征为X轴,第二特征为Y轴。数据点的颜色和形状对应不同的类别。X.shape结果表示有26个数据点,2个特征。
2、wave数据集
低维数据集
#生成数据集
X,y=mglearn.datasets.make_wave(n_samples=40)
#绘图
plt.plot(X,y,"o")
plt.ylim(-3,3)
plt.xlabel("feature")
plt.ylabel("target")
3、cancer数据集(乳腺癌数据集)
2个类别,为良性和恶性
4、boston数据集(波士顿房价数据集)
506个数据点,13个特征
原理:单一最近邻是当添加新的数据点,它的预测结果即离它最近的数据点的标签。任意个(k个)邻居,采用投票法,即将k个近邻中占多数的类别作为结果。
下面使用forge数据集进行预测
1、采用单一邻居
#单一
mglearn.plots.plot_knn_classification(n_neighbors=1)
2、多个邻居
#3个
mglearn.plots.plot_knn_classification(n_neighbors=3)
下面通过sklearn应用K近邻算法
#数据集分割 from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=0) #knn实例化 from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=3) #训练模型 clf.fit(X_train,y_train) #模型预测 clf.predict(X_test) #模型得分 clf.score(X_test,y_test)
最后结果为0.8571428571428571,约为86%
查看决策边界(decision boundary),即算法对类别0 和类别1 的分界线。
下面分别将1、3、9个邻居的决策边界可视化
fig,axes=plt.subplots(1,3,figsize=(10,3))
for n_neighbors,ax in zip([1,3,9],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)
使用更少的邻居对应更高的模型复杂度,而使用更多的邻居对应更低的模型复杂度
下面证实下模型复杂度与泛化能力的关系,用cancer数据集,查看近邻个数对于结果的影响
from matplotlib import pyplot as plt %matplotlib inline import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.datasets import load_breast_cancer #导入数据 cancer = load_breast_cancer() X = cancer.data y = cancer.target #拆分数据集 X_train,X_test,y_train,y_test = train_test_split( X,y,random_state=0) neighbors_setting = range(1,11) train_accuracy = [] test_accuracy = [] #设置不同邻居时,得到得分 for n_neighbors in neighbors_setting: clf = KNeighborsClassifier(n_neighbors=n_neighbors) clf.fit(X_train,y_train) train_accuracy.append(clf.score(X_train,y_train)) test_accuracy.append(clf.score(X_test,y_test)) plt.rcParams['font.sans-serif'] = 'SimHei' #得分进行画图 plt.plot(neighbors_setting,train_accuracy,label="训练精度") plt.plot(neighbors_setting,test_accuracy,label="测试精度") plt.xlabel("近邻n值") plt.ylabel("精度") plt.legend()
考虑单一邻居时,模型在训练集上表现得非常完美,但随着邻居个数增多,模型变得更简单,训练集精度下降。当邻居数量增大到10个时,模型又过于简单,性能变得更差,因此最佳性能在中间的某处,大约邻居数为6。
原理:单一邻居的结果是最近邻的目标值,多近邻结果就是邻居的平均值
类似KNeighborsClassifier,在KNeighborsRegressor类中实现
from sklearn.neighbors import KNeighborsRegressor
X,y = mglearn.datasets.make_wave(n_samples=40)
# 将wave数据集分为训练集和测试集
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=0)
# 模型实例化,并将邻居个数设为3
reg = KNeighborsRegressor(n_neighbors=3)
# 利用训练数据和训练目标值来拟合模型
reg.fit(X_train,y_train)
#模型预测
print(reg.predict(X_test))
#模型得分
reg.score(X_test,y_test)
使用score方法评估模型,对于回归参考的参数是R^2,即决定系数,0~1之间,1为完美预测
#使用score方法评估模型
print("Text set R^2:{:.2f}".format(reg.score(X_test,y_test)))
0.83表示拟合的较好
对于一维数据集,可以查看所有特征取值对应的预测结果,以下创建一个由许多点组成的测试数据集,并分别用1个、3个或9个邻居进行预测:
fig, axes = plt.subplots(1, 3, figsize=(15, 4)) # 创建1000个数据点,在-3和3之间均匀分布 line = np.linspace(-3, 3, 1000).reshape(-1, 1) for n_neighbors, ax in zip([1, 3, 9], axes): # 分别利用1个,3个,9个邻居进行预测 reg = KNeighborsRegressor(n_neighbors=n_neighbors) reg.fit(X_train, y_train) ax.plot(line, reg.predict(line)) ax.plot(X_train, y_train, "^", c=mglearn.cm2(0), markersize=8) ax.plot(X_test, y_test, "v", c=mglearn.cm2(1), markersize=8) ax.set_title( "{} neighbor(s)\n train score: {:.2f} test score: {:.2f}".format( n_neighbors, reg.score(X_train, y_train), reg.score(X_test, y_test))) ax.set_xlabel("Feature") ax.set_ylabel("Target") axes[0].legend(["Model predictions", "Training data/target", "Test data/target"], loc="best")
上图中,使用单一邻居,训练集中的每个点都对预测结果由显著影响,预测结果的图像经过所有数据点,这导致预测结果十分不稳定。考虑更多的邻居之后,预测结果变得更加平滑,但对训练数据的拟合也不好。
参数:1、邻居个数 2、数据点之间距离度量的方法
通常KNeighbors 分类器使用较小的邻居个数(比如3 个或5个)往往可以得到比较好的结果,但应该调节这个参数
优点:
模型很容易理解,构建模型的速度通常很快
缺点:
1、不能处理具有很多特征的数据集
2、预测速度可能会比较慢
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。