GridSearchCV を使ったモデルのハイパーパラメータの最適化

Beginner

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

はじめに

このチュートリアルでは、Scikit-Learn の GridSearchCV 関数について学びます。GridSearchCV は、与えられたモデルの最適なハイパーパラメータを検索するために使用される関数です。これは、推定器の指定されたパラメータ値に対する網羅的な検索です。これらの方法を適用するために使用される推定器のパラメータは、パラメータグリッド上の交差検証付きグリッド検索によって最適化されます。

VM のヒント

VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使って練習しましょう。

Jupyter Notebook の読み込みには数秒かかる場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題がある場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

ライブラリのインポート

必要なライブラリをインポートして始めましょう。

import numpy as np
from matplotlib import pyplot as plt

from sklearn.datasets import make_hastie_10_2
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier

データセットの読み込み

このステップでは、Scikit-Learn の make_hastie_10_2 関数を使ってデータセットを読み込みます。この関数は、2 値分類用の合成データセットを生成します。

X, y = make_hastie_10_2(n_samples=8000, random_state=42)

ハイパーパラメータと評価指標の定義

このステップでは、DecisionTreeClassifier モデルのハイパーパラメータと使用する評価指標を定義します。AUC(曲線下の面積)と正解率の指標を使用します。

scoring = {"AUC": "roc_auc", "Accuracy": make_scorer(accuracy_score)}

グリッドサーチを実行する

このステップでは、GridSearchCV 関数を使ってグリッドサーチを実行します。DecisionTreeClassifier モデルの min_samples_split パラメータの最適なハイパーパラメータを検索します。

gs = GridSearchCV(
    DecisionTreeClassifier(random_state=42),
    param_grid={"min_samples_split": range(2, 403, 20)},
    scoring=scoring,
    refit="AUC",
    n_jobs=2,
    return_train_score=True,
)
gs.fit(X, y)
results = gs.cv_results_

結果を可視化する

このステップでは、グリッドサーチの結果をグラフで可視化します。学習セットとテストセットの両方に対する AUC と正解率のスコアをプロットします。

plt.figure(figsize=(13, 13))
plt.title("GridSearchCV evaluating using multiple scorers simultaneously", fontsize=16)

plt.xlabel("min_samples_split")
plt.ylabel("Score")

ax = plt.gca()
ax.set_xlim(0, 402)
ax.set_ylim(0.73, 1)

## Get the regular numpy array from the MaskedArray
X_axis = np.array(results["param_min_samples_split"].data, dtype=float)

for scorer, color in zip(sorted(scoring), ["g", "k"]):
    for sample, style in (("train", "--"), ("test", "-")):
        sample_score_mean = results["mean_%s_%s" % (sample, scorer)]
        sample_score_std = results["std_%s_%s" % (sample, scorer)]
        ax.fill_between(
            X_axis,
            sample_score_mean - sample_score_std,
            sample_score_mean + sample_score_std,
            alpha=0.1 if sample == "test" else 0,
            color=color,
        )
        ax.plot(
            X_axis,
            sample_score_mean,
            style,
            color=color,
            alpha=1 if sample == "test" else 0.7,
            label="%s (%s)" % (scorer, sample),
        )

    best_index = np.nonzero(results["rank_test_%s" % scorer] == 1)[0][0]
    best_score = results["mean_test_%s" % scorer][best_index]

    ## Plot a dotted vertical line at the best score for that scorer marked by x
    ax.plot(
        [
            X_axis[best_index],
        ]
        * 2,
        [0, best_score],
        linestyle="-.",
        color=color,
        marker="x",
        markeredgewidth=3,
        ms=8,
    )

    ## Annotate the best score for that scorer
    ax.annotate("%0.2f" % best_score, (X_axis[best_index], best_score + 0.005))

plt.legend(loc="best")
plt.grid(False)
plt.show()

まとめ

このチュートリアルでは、Scikit-Learn の GridSearchCV 関数について学びました。データセットの読み込み方法、ハイパーパラメータと評価指標の定義方法、グリッドサーチの実行方法、およびグラフを使った結果の可視化方法を見ました。GridSearchCV は、特定のモデルに対する最適なハイパーパラメータを検索する際に使用する重要な関数です。