半监督分类器与SVM在鸢尾花数据集上的决策边界#

比较Label Spreading、自训练和SVM在鸢尾花数据集上生成的决策边界。

此示例演示了Label Spreading和自训练即使在只有少量标记数据的情况下也能学习到良好的边界。

请注意,自训练使用100%数据的情况被省略了,因为它在功能上与使用100%数据训练SVC是相同的。

Unlabeled points are colored white, Label Spreading 30% data, Self-training 30% data, Label Spreading 50% data, Self-training 50% data, Label Spreading 100% data, SVC with rbf kernel
# 作者:scikit-learn 开发者
# SPDX-License-Identifier: BSD-3-Clause

import matplotlib.pyplot as plt
import numpy as np

from sklearn import datasets
from sklearn.semi_supervised import LabelSpreading, SelfTrainingClassifier
from sklearn.svm import SVC

iris = datasets.load_iris()

X = iris.data[:, :2]
y = iris.target

# 网格中的步长
h = 0.02

rng = np.random.RandomState(0)
y_rand = rng.rand(y.shape[0])
y_30 = np.copy(y)
y_30[y_rand < 0.3] = -1  # set random samples to be unlabeled
y_50 = np.copy(y)
y_50[y_rand < 0.5] = -1
# 我们创建一个 SVM 实例并拟合我们的数据。我们不对数据进行缩放,因为我们想绘制支持向量。
ls30 = (LabelSpreading().fit(X, y_30), y_30, "Label Spreading 30% data")
ls50 = (LabelSpreading().fit(X, y_50), y_50, "Label Spreading 50% data")
ls100 = (LabelSpreading().fit(X, y), y, "Label Spreading 100% data")

# 自训练的基础分类器与SVC相同
base_classifier = SVC(kernel="rbf", gamma=0.5, probability=True)
st30 = (
    SelfTrainingClassifier(base_classifier).fit(X, y_30),
    y_30,
    "Self-training 30% data",
)
st50 = (
    SelfTrainingClassifier(base_classifier).fit(X, y_50),
    y_50,
    "Self-training 50% data",
)

rbf_svc = (SVC(kernel="rbf", gamma=0.5).fit(X, y), y, "SVC with rbf kernel")

# 创建一个网格进行绘图
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))

color_map = {-1: (1, 1, 1), 0: (0, 0, 0.9), 1: (1, 0, 0), 2: (0.8, 0.6, 0)}

classifiers = (ls30, st30, ls50, st50, ls100, rbf_svc)
for i, (clf, y_train, title) in enumerate(classifiers):
    # 绘制决策边界。为此,我们将为网格 [x_min, x_max]x[y_min, y_max] 中的每个点分配一个颜色。
    plt.subplot(3, 2, i + 1)
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # 将结果放入彩色图中
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
    plt.axis("off")

    # 还要绘制训练点
    colors = [color_map[y] for y in y_train]
    plt.scatter(X[:, 0], X[:, 1], c=colors, edgecolors="black")

    plt.title(title)

plt.suptitle("Unlabeled points are colored white", y=0.1)
plt.show()

Total running time of the script: (0 minutes 0.591 seconds)

Related examples

基于高斯过程分类(GPC)的鸢尾花数据集

基于高斯过程分类(GPC)的鸢尾花数据集

sphx_glr_auto_examples_exercises_plot_iris_exercise.py

SVM 练习

多层感知器中的正则化变化

多层感知器中的正则化变化

使用完全随机树的哈希特征变换

使用完全随机树的哈希特征变换

Gallery generated by Sphinx-Gallery