使用不同 SVM 核绘制分类边界#

本示例展示了在二元二维分类问题中,SVC (支持向量分类器) 中不同的核如何影响分类边界。

SVC 的目标是找到一个超平面,通过最大化每个类别最外层数据点之间的间隔,从而有效地分离训练数据中的类别。这是通过寻找定义决策边界超平面的最佳权重向量 \(w\) 来实现的,并使误分类样本的铰链损失(由 hinge_loss 函数测量)之和最小。默认情况下,使用参数 C=1 进行正则化,这允许一定程度的误分类容忍度。

如果数据在原始特征空间中不是线性可分的,则可以设置非线性核参数。根据核的不同,该过程涉及添加新特征或变换现有特征,以丰富数据并可能增加其含义。当设置非 "linear" 的核时,SVC 应用核技巧 (kernel trick),它使用核函数计算数据点对之间的相似度,而无需显式转换整个数据集。核技巧通过仅考虑所有数据点对之间的关系,超越了原本必需的整个数据集矩阵变换。核函数使用点积将两个向量(每对观测值)映射到它们的相似度。

然后可以使用核函数计算超平面,就好像数据集在更高维空间中表示一样。使用核函数代替显式的矩阵变换可以提高性能,因为核函数的时间复杂度为 \(O({n}^2)\),而矩阵变换则根据所应用的特定变换进行缩放。

在此示例中,我们比较了支持向量机最常见的核类型:线性核 ("linear")、多项式核 ("poly")、径向基函数核 ("rbf") 和 S 形核 ("sigmoid")。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

创建数据集#

我们创建了一个具有 16 个样本和两个类别的二维分类数据集。我们绘制样本,颜色与它们各自的目标相匹配。

import matplotlib.pyplot as plt
import numpy as np

X = np.array(
    [
        [0.4, -0.7],
        [-1.5, -1.0],
        [-1.4, -0.9],
        [-1.3, -1.2],
        [-1.1, -0.2],
        [-1.2, -0.4],
        [-0.5, 1.2],
        [-1.5, 2.1],
        [1.0, 1.0],
        [1.3, 0.8],
        [1.2, 0.5],
        [0.2, -2.0],
        [0.5, -2.4],
        [0.2, -2.3],
        [0.0, -2.7],
        [1.3, 2.1],
    ]
)

y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1])

# Plotting settings
fig, ax = plt.subplots(figsize=(4, 3))
x_min, x_max, y_min, y_max = -3, 3, -3, 3
ax.set(xlim=(x_min, x_max), ylim=(y_min, y_max))

# Plot samples by color and add legend
scatter = ax.scatter(X[:, 0], X[:, 1], s=150, c=y, label=y, edgecolors="k")
ax.legend(*scatter.legend_elements(), loc="upper right", title="Classes")
ax.set_title("Samples in two-dimensional feature space")
plt.show()
Samples in two-dimensional feature space

我们可以看到样本无法通过一条直线清晰地分离。

训练 SVC 模型并绘制决策边界#

我们定义一个函数来拟合 SVC 分类器,允许 kernel 参数作为输入,然后使用 DecisionBoundaryDisplay 绘制模型学习到的决策边界。

请注意,为了简单起见,在本示例中 C 参数被设置为其默认值 (C=1),且所有核的 gamma 参数都设置为 gamma=2(尽管线性核会自动忽略它)。在性能至关重要的实际分类任务中,强烈建议进行参数调优(例如使用 GridSearchCV),以捕获数据中的不同结构。

DecisionBoundaryDisplay 中设置 response_method="predict" 会根据预测类别为区域着色。使用 response_method="decision_function" 允许我们同时绘制决策边界及其两侧的间隔。最后,通过训练好的 SVC 的 support_vectors_ 属性识别训练期间使用的支持向量(它们总是位于间隔上),并将其一并绘制出来。

from sklearn import svm
from sklearn.inspection import DecisionBoundaryDisplay


def plot_training_data_with_decision_boundary(
    kernel, ax=None, long_title=True, support_vectors=True
):
    # Train the SVC
    clf = svm.SVC(kernel=kernel, gamma=2).fit(X, y)

    # Settings for plotting
    if ax is None:
        _, ax = plt.subplots(figsize=(4, 3))
    x_min, x_max, y_min, y_max = -3, 3, -3, 3
    ax.set(xlim=(x_min, x_max), ylim=(y_min, y_max))

    # Plot decision boundary and margins
    common_params = {"estimator": clf, "X": X, "ax": ax}
    DecisionBoundaryDisplay.from_estimator(
        **common_params,
        response_method="predict",
        plot_method="pcolormesh",
        alpha=0.3,
    )
    DecisionBoundaryDisplay.from_estimator(
        **common_params,
        response_method="decision_function",
        plot_method="contour",
        levels=[-1, 0, 1],
        colors=["k", "k", "k"],
        linestyles=["--", "-", "--"],
    )

    if support_vectors:
        # Plot bigger circles around samples that serve as support vectors
        ax.scatter(
            clf.support_vectors_[:, 0],
            clf.support_vectors_[:, 1],
            s=150,
            facecolors="none",
            edgecolors="k",
        )

    # Plot samples by color and add legend
    ax.scatter(X[:, 0], X[:, 1], c=y, s=30, edgecolors="k")
    ax.legend(*scatter.legend_elements(), loc="upper right", title="Classes")
    if long_title:
        ax.set_title(f" Decision boundaries of {kernel} kernel in SVC")
    else:
        ax.set_title(kernel)

    if ax is None:
        plt.show()

线性核#

线性核是输入样本的点积

\[K(\mathbf{x}_1, \mathbf{x}_2) = \mathbf{x}_1^\top \mathbf{x}_2\]

然后将其应用于数据集中的任何两个数据点(样本)组合。两个点的点积决定了这两点之间的 cosine_similarity (余弦相似度)。值越高,点越相似。

plot_training_data_with_decision_boundary("linear")
Decision boundaries of linear kernel in SVC

在具有线性核的 SVC 上进行训练会得到一个未变换的特征空间,其中超平面和间隔是直线。由于线性核缺乏表现力,训练后的类别不能完美捕捉训练数据。

多项式核#

多项式核改变了相似度的概念。其核函数定义为

\[K(\mathbf{x}_1, \mathbf{x}_2) = (\gamma \cdot \ \mathbf{x}_1^\top\mathbf{x}_2 + r)^d\]

其中 \({d}\) 是多项式的阶数 (degree),\({\gamma}\) (gamma) 控制每个训练样本对决策边界的影响,而 \({r}\) 是将数据上移或下移的偏置项 (coef0)。这里,我们使用核函数中多项式阶数的默认值 (degree=3)。当 coef0=0(默认值)时,数据仅进行变换,不添加额外的维度。使用多项式核相当于先创建 PolynomialFeatures,然后在变换后的数据上拟合带有线性核的 SVC,尽管对于大多数数据集来说,这种替代方法的计算开销很大。

plot_training_data_with_decision_boundary("poly")
Decision boundaries of poly kernel in SVC

gamma=2 的多项式核能很好地适应训练数据,导致超平面两侧的间隔也相应地弯曲。

RBF 核#

径向基函数 (RBF) 核,也称为高斯核,是 scikit-learn 中支持向量机的默认核。它在无限维空间中测量两个数据点之间的相似度,然后通过多数投票进行分类。其核函数定义为

\[K(\mathbf{x}_1, \mathbf{x}_2) = \exp\left(-\gamma \cdot {\|\mathbf{x}_1 - \mathbf{x}_2\|^2}\right)\]

其中 \({\gamma}\) (gamma) 控制每个独立训练样本对决策边界的影响。

两个点之间的欧几里得距离 \(\|\mathbf{x}_1 - \mathbf{x}_2\|^2\) 越大,核函数的值就越接近于零。这意味着相距较远的两个点更有可能是不相似的。

plot_training_data_with_decision_boundary("rbf")
Decision boundaries of rbf kernel in SVC

在图中我们可以看到决策边界如何倾向于在相互靠近的数据点周围收缩。

S 形核 (Sigmoid kernel)#

S 形核函数的定义为

\[K(\mathbf{x}_1, \mathbf{x}_2) = \tanh(\gamma \cdot \mathbf{x}_1^\top\mathbf{x}_2 + r)\]

其中核系数 \({\gamma}\) (gamma) 控制每个训练样本对决策边界的影响,而 \({r}\) 是使数据上移或下移的偏置项 (coef0)。

在 S 形核中,两个数据点之间的相似度是使用双曲正切函数 (\(\tanh\)) 计算的。核函数对两个点 (\(\mathbf{x}_1\)\(\mathbf{x}_2\)) 的点积进行缩放并可能进行平移。

plot_training_data_with_decision_boundary("sigmoid")
Decision boundaries of sigmoid kernel in SVC

我们可以看到,使用 S 形核获得的决策边界看起来不规则且呈曲线。决策边界试图通过拟合 S 形曲线来分离类别,从而产生复杂的边界,可能无法很好地推广到未知数据。从这个例子可以明显看出,S 形核具有非常特定的用例,即处理呈现 S 形分布的数据。在这个例子中,精细的微调可能会找到更具泛化性的决策边界。由于其特殊性,与其它核相比,S 形核在实践中不太常用。

结论#

在本例中,我们可视化了使用提供的数据集训练的决策边界。这些图直观地展示了不同的核如何利用训练数据来确定分类边界。

超平面和间隔虽然是间接计算的,但可以想象成变换后的特征空间中的平面。然而,在图中,它们是相对于原始特征空间表示的,从而导致多项式、RBF 和 S 形核的决策边界呈曲线状。

请注意,这些图并不评估单个核的准确性或质量。它们旨在让您直观地理解不同核如何使用训练数据。

为了进行全面评估,建议使用 GridSearchCV 等技术微调 SVC 参数,以捕捉数据中潜在的结构。

XOR 数据集#

线性不可分数据集的一个典型例子是 XOR 模式。在这里,我们演示了不同核在此类数据集上的表现。

xx, yy = np.meshgrid(np.linspace(-3, 3, 500), np.linspace(-3, 3, 500))
np.random.seed(0)
X = np.random.randn(300, 2)
y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)

_, ax = plt.subplots(2, 2, figsize=(8, 8))
args = dict(long_title=False, support_vectors=False)
plot_training_data_with_decision_boundary("linear", ax[0, 0], **args)
plot_training_data_with_decision_boundary("poly", ax[0, 1], **args)
plot_training_data_with_decision_boundary("rbf", ax[1, 0], **args)
plot_training_data_with_decision_boundary("sigmoid", ax[1, 1], **args)
plt.show()
linear, poly, rbf, sigmoid

正如您从上图中看到的,只有 rbf 核能为上述数据集找到合理的决策边界。

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

相关示例

RBF SVM 参数

RBF SVM 参数

绘制 iris 数据集中的不同 SVM 分类器

绘制 iris 数据集中的不同 SVM 分类器

SVM:最大间隔分离超平面

SVM:最大间隔分离超平面

SVM:不平衡类别的分离超平面

SVM:不平衡类别的分离超平面

由 Sphinx-Gallery 生成的图库