モデルの複雑さと交差検証スコアのバランス

Machine LearningMachine LearningBeginner
オンラインで実践に進む

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、最適な精度スコアの 1 標準偏差以内で適切な精度を見つけることで、モデルの複雑さと交差検証スコアをバランスさせる方法を学びます。また、PCA コンポーネントの数を最小限に抑えます。scikit-learn の digits データセットと、PCA と LinearSVC から構成されるパイプラインを使用します。

VM のヒント

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

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

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

ライブラリのインポート

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

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.svm import LinearSVC

関数の定義

この実験の後で使用される 2 つの関数を定義します。

def lower_bound(cv_results):
    """
    最良の `mean_test_scores` の 1 標準偏差以内の下限を計算します。

    パラメータ
    ----------
    cv_results : numpy(masked) ndarrays の辞書
        `GridSearchCV` の cv_results_ 属性を参照してください

    戻り値
    -------
    float
        最良の `mean_test_score` の 1 標準偏差以内の下限
    """
    best_score_idx = np.argmax(cv_results["mean_test_score"])

    return (
        cv_results["mean_test_score"][best_score_idx]
        - cv_results["std_test_score"][best_score_idx]
    )


def best_low_complexity(cv_results):
    """
    交差検証スコアとモデルの複雑さをバランスさせます。

    パラメータ
    ----------
    cv_results : numpy(masked) ndarrays の辞書
        `GridSearchCV` の cv_results_ 属性を参照してください。

    戻り値
    ------
    int
        最良の `mean_test_score` の 1 標準偏差以内のテストスコアを持ちながら、最も少ない PCA コンポーネントを持つモデルのインデックス
    """
    threshold = lower_bound(cv_results)
    candidate_idx = np.flatnonzero(cv_results["mean_test_score"] >= threshold)
    best_idx = candidate_idx[
        cv_results["param_reduce_dim__n_components"][candidate_idx].argmin()
    ]
    return best_idx

データの読み込みとパイプラインの定義

scikit-learn から digits データセットを読み込み、PCA と LinearSVC から構成されるパイプラインを定義します。

pipe = Pipeline(
    [
        ("reduce_dim", PCA(random_state=42)),
        ("classify", LinearSVC(random_state=42, C=0.01, dual="auto")),
    ]
)

X, y = load_digits(return_X_y=True)

GridSearchCV のパラメータを定義する

GridSearchCV のパラメータを定義します。

param_grid = {"reduce_dim__n_components": [6, 8, 10, 12, 14]}

GridSearchCV オブジェクトを定義する

GridSearchCV オブジェクトを定義し、モデルに適合させます。

grid = GridSearchCV(
    pipe,
    cv=10,
    n_jobs=1,
    param_grid=param_grid,
    scoring="accuracy",
    refit=best_low_complexity,
)

grid.fit(X, y)

結果を可視化する

PCA コンポーネントの数に対する正解率をプロットすることで結果を可視化します。

n_components = grid.cv_results_["param_reduce_dim__n_components"]
test_scores = grid.cv_results_["mean_test_score"]

plt.figure()
plt.bar(n_components, test_scores, width=1.3, color="b")

lower = lower_bound(grid.cv_results_)
plt.axhline(np.max(test_scores), linestyle="--", color="y", label="Best score")
plt.axhline(lower, linestyle="--", color=".5", label="Best score - 1 std")

plt.title("Balance model complexity and cross-validated score")
plt.xlabel("Number of PCA components used")
plt.ylabel("Digit classification accuracy")
plt.xticks(n_components.tolist())
plt.ylim((0, 1.0))
plt.legend(loc="upper left")

best_index_ = grid.best_index_

print("The best_index_ is %d" % best_index_)
print("The n_components selected is %d" % n_components[best_index_])
print(
    "The corresponding accuracy score is %.2f"
    % grid.cv_results_["mean_test_score"][best_index_]
)
plt.show()

まとめ

この実験では、PCA と LinearSVC を使ってモデルの複雑さと交差検証スコアのバランスをとる方法を学びました。GridSearchCV を使って、最良スコアの 1 標準偏差以内で正解率を最大化しながら、最適な PCA コンポーネント数を見つけました。また、結果を可視化して、モデルの複雑さと正解率のトレードオフをよりよく理解しました。