使用python+sklearn实现最近质心分类
发布于 2021-04-09 03:35
一个最近质心分类的用法示例。它将绘制每个类别的决策边界。输出:
None 0.8133333333333334
0.2 0.82
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.neighbors import NearestCentroid
n_neighbors = 15
# 导入一些数据进行训练
iris = datasets.load_iris()
# 我们仅采用前两个特征。
# 我们可以通过使用二维数据集来避免这种丑陋的切片(ugly slicing)
X = iris.data[:, :2]
y = iris.target
h = .02 # 网格中的步长
# 创建颜色图(maps)
cmap_light = ListedColormap(['orange', 'cyan', 'cornflowerblue'])
cmap_bold = ListedColormap(['darkorange', 'c', 'darkblue'])
for shrinkage in [None, .2]:
# 我们创建邻居分类器(Neighbours Classifier)的实例并用它来拟合数据。
clf = NearestCentroid(shrink_threshold=shrinkage)
clf.fit(X, y)
y_pred = clf.predict(X)
print(shrinkage, np.mean(y == y_pred))
# 绘制决策边界。
# 为此,我们将为网格[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))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# 将结果放入颜色图
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
# 绘制训练数据点
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=20)
plt.title("3-Class classification (shrink_threshold=%r)"
% shrinkage)
plt.axis('tight')
plt.show()
脚本的总运行时间:(0分钟0.690秒)
估计的内存使用量: 8 MB
下载Python源代码: plot_nearest_centroid.py
下载Jupyter notebook源代码: plot_nearest_centroid.ipynb
由Sphinx-Gallery生成的画廊



相关资源