可视化 scikit-learn 中的交叉验证行为#

选择正确的交叉验证对象是正确拟合模型的关键部分。为了避免模型过拟合、标准化测试集中的组数等,有多种将数据拆分为训练集和测试集的方法。

本示例可视化了多个常见 scikit-learn 对象的行为,以供比较。

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

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Patch

from sklearn.model_selection import (
    GroupKFold,
    GroupShuffleSplit,
    KFold,
    ShuffleSplit,
    StratifiedGroupKFold,
    StratifiedKFold,
    StratifiedShuffleSplit,
    TimeSeriesSplit,
)

rng = np.random.RandomState(1338)
cmap_data = plt.cm.Paired
cmap_cv = plt.cm.coolwarm
n_splits = 4

可视化我们的数据#

首先,我们必须了解数据的结构。它有 100 个随机生成的数据点,3 个在数据点间分布不均的类别,以及 10 个在数据点间分布均匀的“组”。

正如我们将看到的,一些交叉验证对象会对标记数据进行特定处理,有些则对分组数据有不同的表现,而另一些则完全不使用这些信息。

首先,我们将可视化我们的数据。

# Generate the class/group data
n_points = 100
X = rng.randn(100, 10)

percentiles_classes = [0.1, 0.3, 0.6]
y = np.hstack([[ii] * int(100 * perc) for ii, perc in enumerate(percentiles_classes)])

# Generate uneven groups
group_prior = rng.dirichlet([2] * 10)
groups = np.repeat(np.arange(10), rng.multinomial(100, group_prior))


def visualize_groups(classes, groups, name):
    # Visualize dataset groups
    fig, ax = plt.subplots()
    ax.scatter(
        range(len(groups)),
        [0.5] * len(groups),
        c=groups,
        marker="_",
        lw=50,
        cmap=cmap_data,
    )
    ax.scatter(
        range(len(groups)),
        [3.5] * len(groups),
        c=classes,
        marker="_",
        lw=50,
        cmap=cmap_data,
    )
    ax.set(
        ylim=[-1, 5],
        yticks=[0.5, 3.5],
        yticklabels=["Data\ngroup", "Data\nclass"],
        xlabel="Sample index",
    )


visualize_groups(y, groups, "no groups")
plot cv indices

定义一个可视化交叉验证行为的函数#

我们将定义一个函数来可视化每个交叉验证对象的行为。我们将执行 4 次数据拆分。在每次拆分时,我们将可视化为训练集选择的索引(蓝色)和测试集选择的索引(红色)。

def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10):
    """Create a sample plot for indices of a cross-validation object."""
    use_groups = "Group" in type(cv).__name__
    groups = group if use_groups else None
    # Generate the training/testing visualizations for each CV split
    for ii, (tr, tt) in enumerate(cv.split(X=X, y=y, groups=groups)):
        # Fill in indices with the training/test groups
        indices = np.array([np.nan] * len(X))
        indices[tt] = 1
        indices[tr] = 0

        # Visualize the results
        ax.scatter(
            range(len(indices)),
            [ii + 0.5] * len(indices),
            c=indices,
            marker="_",
            lw=lw,
            cmap=cmap_cv,
            vmin=-0.2,
            vmax=1.2,
        )

    # Plot the data classes and groups at the end
    ax.scatter(
        range(len(X)), [ii + 1.5] * len(X), c=y, marker="_", lw=lw, cmap=cmap_data
    )

    ax.scatter(
        range(len(X)), [ii + 2.5] * len(X), c=group, marker="_", lw=lw, cmap=cmap_data
    )

    # Formatting
    yticklabels = list(range(n_splits)) + ["class", "group"]
    ax.set(
        yticks=np.arange(n_splits + 2) + 0.5,
        yticklabels=yticklabels,
        xlabel="Sample index",
        ylabel="CV iteration",
        ylim=[n_splits + 2.2, -0.2],
        xlim=[0, 100],
    )
    ax.set_title("{}".format(type(cv).__name__), fontsize=15)
    return ax

让我们看看 KFold 交叉验证对象的表现。

fig, ax = plt.subplots()
cv = KFold(n_splits)
plot_cv_indices(cv, X, y, groups, ax, n_splits)
KFold
<Axes: title={'center': 'KFold'}, xlabel='Sample index', ylabel='CV iteration'>

正如你所见,默认情况下,KFold 交叉验证迭代器既不考虑数据点类别,也不考虑组。我们可以通过使用以下方法来改变这一点:

  • StratifiedKFold:保持每个类别的样本比例。

  • GroupKFold:确保同一个组不会出现在两个不同的折叠中。

  • StratifiedGroupKFold:在尝试返回分层折叠的同时,保持 GroupKFold 的约束。

cvs = [StratifiedKFold, GroupKFold, StratifiedGroupKFold]

for cv in cvs:
    fig, ax = plt.subplots(figsize=(6, 3))
    plot_cv_indices(cv(n_splits), X, y, groups, ax, n_splits)
    ax.legend(
        [Patch(color=cmap_cv(0.8)), Patch(color=cmap_cv(0.02))],
        ["Testing set", "Training set"],
        loc=(1.02, 0.8),
    )
    # Make the legend fit
    plt.tight_layout()
    fig.subplots_adjust(right=0.7)
  • StratifiedKFold
  • GroupKFold
  • StratifiedGroupKFold

接下来,我们将为多个 CV 迭代器可视化这种行为。

可视化多种 CV 对象的交叉验证索引#

让我们直观地比较多种 scikit-learn 交叉验证对象的交叉验证行为。下面我们将循环遍历几个常见的交叉验证对象,并可视化每个对象的行为。

请注意有些对象使用了组/类别信息,而另一些则没有。

cvs = [
    KFold,
    GroupKFold,
    ShuffleSplit,
    StratifiedKFold,
    StratifiedGroupKFold,
    GroupShuffleSplit,
    StratifiedShuffleSplit,
    TimeSeriesSplit,
]


for cv in cvs:
    this_cv = cv(n_splits=n_splits)
    fig, ax = plt.subplots(figsize=(6, 3))
    plot_cv_indices(this_cv, X, y, groups, ax, n_splits)

    ax.legend(
        [Patch(color=cmap_cv(0.8)), Patch(color=cmap_cv(0.02))],
        ["Testing set", "Training set"],
        loc=(1.02, 0.8),
    )
    # Make the legend fit
    plt.tight_layout()
    fig.subplots_adjust(right=0.7)
plt.show()
  • KFold
  • GroupKFold
  • ShuffleSplit
  • StratifiedKFold
  • StratifiedGroupKFold
  • GroupShuffleSplit
  • StratifiedShuffleSplit
  • TimeSeriesSplit

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

相关示例

带交叉验证的接收者操作特征(ROC)

带交叉验证的接收者操作特征(ROC)

带交叉验证的递归特征消除

带交叉验证的递归特征消除

嵌套 vs 非嵌套交叉验证

嵌套 vs 非嵌套交叉验证

scikit-learn 1.4 发布亮点

scikit-learn 1.4 发布亮点

由 Sphinx-Gallery 生成的图库