最近质心分类#

使用不同收缩阈值(shrink thresholds)的 最近质心分类器 (Nearest Centroid Classifier) 示例用法。它将绘制出每个类别的决策边界。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
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

# import some data to play with
iris = datasets.load_iris()
# we only take the first two features. We could avoid this ugly
# slicing by using a two-dim dataset
X = iris.data[:, :2]
y = iris.target

for shrinkage in [None, 0.2]:
    # we create an instance of Nearest Centroid Classifier and fit the data.
    clf = NearestCentroid(shrink_threshold=shrinkage)
    clf.fit(X, y)
    y_pred = clf.predict(X)
    acc = np.mean(y == y_pred)

    _, ax = plt.subplots()
    disp = DecisionBoundaryDisplay.from_estimator(
        clf, X, ax=ax, response_method="predict", alpha=0.5
    )

    # Plot also the training points
    cmap = ListedColormap(disp.multiclass_colors_)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap, edgecolor="k", s=20)
    plt.title(
        f"3-Class classification (shrink_threshold={shrinkage})\nAccuracy: {acc:.2f}"
    )
    plt.axis("tight")

plt.show()
  • 3-Class classification (shrink_threshold=None) Accuracy: 0.81
  • 3-Class classification (shrink_threshold=0.2) Accuracy: 0.82

脚本总运行时间: (0 分 0.153 秒)

相关示例

绘制在 iris 数据集上训练的决策树的决策边界

绘制在 iris 数据集上训练的决策树的决策边界

最近邻分类

最近邻分类

比较带和不带邻域成分分析的最近邻

比较带和不带邻域成分分析的最近邻

带自定义核的 SVM

带自定义核的 SVM

由 Sphinx-Gallery 生成的图库