SVC 的正则化参数缩放#

以下示例说明在使用 支持向量机 进行 分类 时,缩放正则化参数的效果。对于 SVC 分类,我们关注以下公式的风险最小化:

\[C \sum_{i=1, n} \mathcal{L} (f(x_i), y_i) + \Omega (w)\]

其中

  • \(C\) 用于设置正则化的量

  • \(\mathcal{L}\) 是我们样本和模型参数的 损失 函数。

  • \(\Omega\) 是我们模型参数的 惩罚 函数。

如果我们把损失函数看作是每个样本的个体误差,那么随着我们添加更多样本,数据拟合项(即每个样本的误差之和)会增加。然而,惩罚项不会增加。

当使用 交叉验证 来设置 C 的正则化量时,主问题和交叉验证折叠中的较小问题之间会有不同数量的样本。

由于损失函数取决于样本数量,后者会影响 C 的选定值。随之而来的问题是:“如何最优地调整 C 来适应不同数量的训练样本?”

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

数据生成#

在本例中,我们研究了通过重新参数化正则化参数 C 来考虑使用 L1 或 L2 惩罚时的样本数量的影响。为此,我们创建了一个具有大量特征的合成数据集,其中只有少数特征是有信息的。因此,我们期望正则化会使系数向零收缩(L2 惩罚)或正好收缩到零(L1 惩罚)。

from sklearn.datasets import make_classification

n_samples, n_features = 100, 300
X, y = make_classification(
    n_samples=n_samples, n_features=n_features, n_informative=5, random_state=1
)

L1 惩罚情况#

在 L1 的情况下,理论认为,在强正则化条件下,即使样本量趋于无穷大,估计器也无法像知道真实分布的模型那样进行预测,因为它可能会将一些具有预测能力的特征的权重设置为零,这会导致偏差。但它确实表明,通过调整 C,可以找到正确的非零参数集及其符号。

我们定义了一个具有 L1 惩罚的线性 SVC。

from sklearn.svm import LinearSVC

model_l1 = LinearSVC(penalty="l1", loss="squared_hinge", dual=False, tol=1e-3)

我们通过交叉验证计算不同 C 值的平均测试得分。

import numpy as np
import pandas as pd

from sklearn.model_selection import ShuffleSplit, validation_curve

Cs = np.logspace(-2.3, -1.3, 10)
train_sizes = np.linspace(0.3, 0.7, 3)
labels = [f"fraction: {train_size}" for train_size in train_sizes]
shuffle_params = {
    "test_size": 0.3,
    "n_splits": 150,
    "random_state": 1,
}

results = {"C": Cs}
for label, train_size in zip(labels, train_sizes):
    cv = ShuffleSplit(train_size=train_size, **shuffle_params)
    train_scores, test_scores = validation_curve(
        model_l1,
        X,
        y,
        param_name="C",
        param_range=Cs,
        cv=cv,
        n_jobs=2,
    )
    results[label] = test_scores.mean(axis=1)
results = pd.DataFrame(results)
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(12, 6))

# plot results without scaling C
results.plot(x="C", ax=axes[0], logx=True)
axes[0].set_ylabel("CV score")
axes[0].set_title("No scaling")

for label in labels:
    best_C = results.loc[results[label].idxmax(), "C"]
    axes[0].axvline(x=best_C, linestyle="--", color="grey", alpha=0.7)

# plot results by scaling C
for train_size_idx, label in enumerate(labels):
    train_size = train_sizes[train_size_idx]
    results_scaled = results[[label]].assign(
        C_scaled=Cs * float(n_samples * np.sqrt(train_size))
    )
    results_scaled.plot(x="C_scaled", ax=axes[1], logx=True, label=label)
    best_C_scaled = results_scaled["C_scaled"].loc[results[label].idxmax()]
    axes[1].axvline(x=best_C_scaled, linestyle="--", color="grey", alpha=0.7)

axes[1].set_title("Scaling C by sqrt(1 / n_samples)")

_ = fig.suptitle("Effect of scaling C with L1 penalty")
Effect of scaling C with L1 penalty, No scaling, Scaling C by sqrt(1 / n_samples)

在较小的 C(强正则化)区域,模型学习到的所有系数都为零,导致严重的欠拟合。事实上,该区域的准确率处于随机水平。

使用默认缩放可以得到一个相对稳定的最佳 C 值,而脱离欠拟合区域的过渡取决于训练样本的数量。重新参数化可以带来更稳定的结果。

例如,请参阅 On the prediction performance of the LassoSimultaneous analysis of Lasso and Dantzig selector 中的定理 3,其中正则化参数始终假定与 1 / sqrt(n_samples) 成正比。

L2 惩罚情况#

我们可以对 L2 惩罚进行类似的实验。在这种情况下,理论认为为了实现预测一致性,随着样本量的增长,惩罚参数应保持不变。

model_l2 = LinearSVC(penalty="l2", loss="squared_hinge", dual=True)
Cs = np.logspace(-8, 4, 11)

labels = [f"fraction: {train_size}" for train_size in train_sizes]
results = {"C": Cs}
for label, train_size in zip(labels, train_sizes):
    cv = ShuffleSplit(train_size=train_size, **shuffle_params)
    train_scores, test_scores = validation_curve(
        model_l2,
        X,
        y,
        param_name="C",
        param_range=Cs,
        cv=cv,
        n_jobs=2,
    )
    results[label] = test_scores.mean(axis=1)
results = pd.DataFrame(results)
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(12, 6))

# plot results without scaling C
results.plot(x="C", ax=axes[0], logx=True)
axes[0].set_ylabel("CV score")
axes[0].set_title("No scaling")

for label in labels:
    best_C = results.loc[results[label].idxmax(), "C"]
    axes[0].axvline(x=best_C, linestyle="--", color="grey", alpha=0.8)

# plot results by scaling C
for train_size_idx, label in enumerate(labels):
    results_scaled = results[[label]].assign(
        C_scaled=Cs * float(n_samples * np.sqrt(train_sizes[train_size_idx]))
    )
    results_scaled.plot(x="C_scaled", ax=axes[1], logx=True, label=label)
    best_C_scaled = results_scaled["C_scaled"].loc[results[label].idxmax()]
    axes[1].axvline(x=best_C_scaled, linestyle="--", color="grey", alpha=0.8)
axes[1].set_title("Scaling C by sqrt(1 / n_samples)")

fig.suptitle("Effect of scaling C with L2 penalty")
plt.show()
Effect of scaling C with L2 penalty, No scaling, Scaling C by sqrt(1 / n_samples)

对于 L2 惩罚情况,重新参数化似乎对正则化最优值的稳定性影响较小。脱离过拟合区域的过渡在一个更分散的范围内发生,并且准确率似乎没有下降到随机水平。

尝试将值增加到 n_splits=1_000 以获得 L2 情况下的更好结果,由于文档构建器的限制,此处未显示。

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

相关示例

逻辑回归中的 L1 惩罚和稀疏性

逻辑回归中的 L1 惩罚和稀疏性

岭系数作为 L2 正则化的函数

岭系数作为 L2 正则化的函数

模型正则化对训练和测试误差的影响

模型正则化对训练和测试误差的影响

特征缩放的重要性

特征缩放的重要性

由 Sphinx-Gallery 生成的图库