Note
Go to the end to download the full example code. or to run this example in your browser via Binder
最近质心分类#
最近质心分类的示例用法。 它将绘制每个类别的决策边界。
None 0.8133333333333334
0.2 0.82
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.neighbors import NearestCentroid
# 导入一些数据来玩玩
iris = datasets.load_iris()
# 我们只取前两个特征。我们可以通过使用一个二维数据集来避免这种丑陋的切片操作。
X = iris.data[:, :2]
y = iris.target
# 创建色彩映射
cmap_light = ListedColormap(["orange", "cyan", "cornflowerblue"])
cmap_bold = ListedColormap(["darkorange", "c", "darkblue"])
for shrinkage in [None, 0.2]:
# 我们创建了一个最近质心分类器的实例并拟合了数据。
clf = NearestCentroid(shrink_threshold=shrinkage)
clf.fit(X, y)
y_pred = clf.predict(X)
print(shrinkage, np.mean(y == y_pred))
_, ax = plt.subplots()
DecisionBoundaryDisplay.from_estimator(
clf, X, cmap=cmap_light, ax=ax, response_method="predict"
)
# 还要绘制训练点
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()
Total running time of the script: (0 minutes 0.084 seconds)
Related examples
绘制在鸢尾花数据集上训练的决策树的决策边界
逻辑回归三分类器
带有自定义核函数的SVM
比较有无邻域成分分析的最近邻分类