多层感知器正则化

Beginner

This tutorial is from open-source community. Access the source code

简介

本实验演示了如何在多层感知器(MLP)中使用正则化来对抗过拟合。我们将比较正则化参数 alpha 的不同值,并观察决策函数如何变化。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到笔记本标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入库

我们将首先导入本实验所需的库。我们将使用 scikit-learn 创建合成数据集,使用 MLPClassifier 构建 MLP 模型,使用 StandardScaler 对数据进行标准化,并使用 make_pipeline 创建一个由变换和分类器组成的管道。

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline

定义 alpha 值

我们将为正则化参数 alpha 定义不同的值。我们将使用 np.logspace 在 0.1 和 10 之间生成 5 个对数间距的值。

alphas = np.logspace(-1, 1, 5)

创建分类器

我们将为每个 alpha 值创建 MLP 分类器。我们将创建一个管道,其中包括用于标准化数据的 StandardScaler 和具有不同 alpha 值的 MLPClassifier。我们将求解器设置为 'lbfgs',它是拟牛顿法家族中的一种优化器。我们将 max_iter 设置为 2000,并将 early_stopping 设置为 True 以防止过拟合。我们将使用两个隐藏层,每个隐藏层有 10 个神经元。

classifiers = []
names = []
for alpha in alphas:
    classifiers.append(
        make_pipeline(
            StandardScaler(),
            MLPClassifier(
                solver="lbfgs",
                alpha=alpha,
                random_state=1,
                max_iter=2000,
                early_stopping=True,
                hidden_layer_sizes=[10, 10],
            ),
        )
    )
    names.append(f"alpha {alpha:.2f}")

创建数据集

我们将使用 scikit-learn 中的 make_classification、make_moons 和 make_circles 函数创建三个合成数据集。我们将使用 train_test_split 将每个数据集拆分为训练集和测试集。

X, y = make_classification(
    n_features=2, n_redundant=0, n_informative=2, random_state=0, n_clusters_per_class=1
)
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape)
linearly_separable = (X, y)

datasets = [
    make_moons(noise=0.3, random_state=0),
    make_circles(noise=0.2, factor=0.5, random_state=1),
    linearly_separable,
]

figure = plt.figure(figsize=(17, 9))
i = 1
## 遍历数据集
for X, y in datasets:
    ## 拆分为训练和测试部分
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.4, random_state=42
    )

绘制数据集

我们将绘制每个数据集,并将训练点和测试点用不同颜色表示。

    x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
    y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    ## 先绘制数据集
    cm = plt.cm.RdBu
    cm_bright = ListedColormap(["#FF0000", "#0000FF"])
    ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
    ## 绘制训练点
    ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)
    ## 以及测试点
    ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
    ax.set_xlim(xx.min(), xx.max())
    ax.set_ylim(yy.min(), yy.max())
    ax.set_xticks(())
    ax.set_yticks(())
    i += 1

拟合分类器并绘制决策边界

我们将在每个数据集上拟合每个分类器,并绘制决策边界。我们将使用 contourf 来绘制决策边界,使用 scatter 来绘制训练点和测试点。我们还将在每个图上显示准确率得分。

    ## 遍历分类器
    for name, clf in zip(names, classifiers):
        ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
        clf.fit(X_train, y_train)
        score = clf.score(X_test, y_test)

        ## 绘制决策边界。为此,我们将为网格 [x_min, x_max] x [y_min, y_max] 中的每个点分配一种颜色。
        if hasattr(clf, "decision_function"):
            Z = clf.decision_function(np.column_stack([xx.ravel(), yy.ravel()]))
        else:
            Z = clf.predict_proba(np.column_stack([xx.ravel(), yy.ravel()]))[:, 1]

        ## 将结果放入颜色图中
        Z = Z.reshape(xx.shape)
        ax.contourf(xx, yy, Z, cmap=cm, alpha=0.8)

        ## 也绘制训练点
        ax.scatter(
            X_train[:, 0],
            X_train[:, 1],
            c=y_train,
            cmap=cm_bright,
            edgecolors="black",
            s=25,
        )
        ## 和测试点
        ax.scatter(
            X_test[:, 0],
            X_test[:, 1],
            c=y_test,
            cmap=cm_bright,
            alpha=0.6,
            edgecolors="black",
            s=25,
        )

        ax.set_xlim(xx.min(), xx.max())
        ax.set_ylim(yy.min(), yy.max())
        ax.set_xticks(())
        ax.set_yticks(())
        ax.set_title(name)
        ax.text(
            xx.max() - 0.3,
            yy.min() + 0.3,
            f"{score:.3f}".lstrip("0"),
            size=15,
            horizontalalignment="right",
        )
        i += 1

显示图表

最后,我们将调整子图布局并显示图表。

figure.subplots_adjust(left=0.02, right=0.98)
plt.show()

总结

在本实验中,我们学习了如何在多层感知器中使用正则化来对抗过拟合。我们比较了正则化参数 alpha 的不同值,并观察了决策函数是如何变化的。我们还学习了如何创建合成数据集、标准化数据、创建多层感知器分类器以及绘制决策边界。