Scikit-Learn の Elastic-Net 回帰モデル

Machine LearningMachine LearningBeginner
今すぐ練習

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

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

はじめに

この実験では、Scikit-learn の Elastic-Net 回帰モデルを使って、見たことのないデータ(テストデータ)に対する推定器の性能が学習データに対する性能と同じでないことを示します。サンプルデータを生成し、学習誤差とテスト誤差を計算し、結果関数をプロットします。

VM のヒント

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

時々、Jupyter Notebook が読み込み終わるまで数秒待つ必要があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/model_selection("Model Selection") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/model_selection -.-> lab-49320{{"Scikit-Learn の Elastic-Net 回帰モデル"}} sklearn/datasets -.-> lab-49320{{"Scikit-Learn の Elastic-Net 回帰モデル"}} ml/sklearn -.-> lab-49320{{"Scikit-Learn の Elastic-Net 回帰モデル"}} end

サンプルデータの生成

Scikit-learn のmake_regression()関数を使ってサンプルデータを生成します。学習サンプル数を 75、テストサンプル数を 150、特徴数を 500 に設定します。また、n_informativeを 50 に、shuffleを False に設定します。

import numpy as np
from sklearn import linear_model
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

n_samples_train, n_samples_test, n_features = 75, 150, 500
X, y, coef = make_regression(
    n_samples=n_samples_train + n_samples_test,
    n_features=n_features,
    n_informative=50,
    shuffle=False,
    noise=1.0,
    coef=True,
)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=n_samples_train, test_size=n_samples_test, shuffle=False
)

学習誤差とテスト誤差の計算

Scikit-learn の Elastic-Net 回帰モデルを使って学習誤差とテスト誤差を計算します。正則化パラメータalphanp.logspace()を使って 10^-5 から 10^1 の範囲の値に設定します。また、l1_ratioを 0.7 に、max_iterを 10000 に設定します。

alphas = np.logspace(-5, 1, 60)
enet = linear_model.ElasticNet(l1_ratio=0.7, max_iter=10000)
train_errors = list()
test_errors = list()
for alpha in alphas:
    enet.set_params(alpha=alpha)
    enet.fit(X_train, y_train)
    train_errors.append(enet.score(X_train, y_train))
    test_errors.append(enet.score(X_test, y_test))

i_alpha_optim = np.argmax(test_errors)
alpha_optim = alphas[i_alpha_optim]
print("Optimal regularization parameter : %s" % alpha_optim)

結果関数のプロット

matplotlibライブラリを使って結果関数をプロットします。plt.subplot()関数を使って 2 つのサブプロットを作成します。最初のサブプロットでは、正則化パラメータの関数として学習誤差とテスト誤差をプロットします。また、最適な正則化パラメータのところに垂直線をプロットします。2 番目のサブプロットでは、真の係数と推定された係数をプロットします。

import matplotlib.pyplot as plt

plt.subplot(2, 1, 1)
plt.semilogx(alphas, train_errors, label="Train")
plt.semilogx(alphas, test_errors, label="Test")
plt.vlines(
    alpha_optim,
    plt.ylim()[0],
    np.max(test_errors),
    color="k",
    linewidth=3,
    label="Optimum on test",
)
plt.legend(loc="lower right")
plt.ylim([0, 1.2])
plt.xlabel("Regularization parameter")
plt.ylabel("Performance")

## Show estimated coef_ vs true coef
plt.subplot(2, 1, 2)
plt.plot(coef, label="True coef")
plt.plot(coef_, label="Estimated coef")
plt.legend()
plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.26)
plt.show()

まとめ

この実験では、Scikit-learn の Elastic-Net 回帰モデルを使って学習誤差とテスト誤差を計算し、結果関数をプロットする方法を学びました。また、見たことのないデータ(テストデータ)に対する推定器の性能が学習データに対する性能と同じでないことも学びました。make_regression()linear_model.ElasticNet()train_test_split()np.logspace()、およびmatplotlib関数を使ってサンプルデータを生成し、学習誤差とテスト誤差を計算し、結果関数をプロットしました。