缩放 SVC 的正则化参数#

以下示例说明了在使用 支持向量机 (Support Vector Machines) 进行 分类 时,缩放正则化参数的效果。对于 SVC 分类,我们关注的是如下方程的风险最小化:

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

其中

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

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

  • \(\Omega\) 是模型参数的 penalty(惩罚)函数

如果我们考虑将损失函数作为每个样本的独立误差,那么数据拟合项(即每个样本的误差总和)会随着样本量的增加而增加。然而,惩罚项并不会增加。

例如,在使用 交叉验证 通过 C 设置正则化强度时,主问题与交叉验证折叠(folds)内的较小问题之间的样本量是不同的。

由于损失函数取决于样本量,后者会影响所选 C 的值。由此产生的问题是:“我们如何优化调整 C 以考虑不同数量的训练样本?”

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

数据生成#

在本示例中,我们研究在使用 L1 或 L2 惩罚时,重新参数化正则化参数 C 以考虑样本数量的效果。为此,我们创建了一个具有大量特征的合成数据集,其中只有少数特征是有信息的。因此,我们预期正则化会将系数收缩到零(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 分 29.181 秒)

相关示例

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

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

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

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

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

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

特征缩放的重要性

特征缩放的重要性

由 Sphinx-Gallery 生成的图库