ランダムフォレストによる特徴量の重要度

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

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

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

はじめに

この実験では、人工的な分類タスクにおける特徴量の重要度を評価するためにランダムフォレストを使用します。3 つの情報量のある特徴量のみからなる合成データセットを生成します。誤差バーで表される木間の変動性とともに、フォレストの特徴量の重要度をプロットします。

VM のヒント

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

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

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

ライブラリのインポート

この実験に必要なライブラリをインポートします。

import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
import pandas as pd
import numpy as np
import time

データの生成

3 つの情報量のある特徴量のみからなる合成データセットを生成します。データセットをシャッフルしないように明示的に設定し、情報量のある特徴量が X の最初の 3 列に対応するようにします。また、データセットを学習用とテスト用のサブセットに分割します。

X, y = make_classification(
    n_samples=1000,
    n_features=10,
    n_informative=3,
    n_redundant=0,
    n_repeated=0,
    n_classes=2,
    random_state=0,
    shuffle=False,
)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)

ランダムフォレストの適合

特徴量の重要度を計算するために、ランダムフォレスト分類器を適合させます。

feature_names = [f"feature {i}" for i in range(X.shape[1])]
forest = RandomForestClassifier(random_state=0)
forest.fit(X_train, y_train)

不純度の平均減少量に基づく特徴量の重要度

特徴量の重要度は、適合させた属性feature_importances_によって提供され、各木内の不純度の減少の累積の平均と標準偏差として計算されます。不純度に基づく重要度をプロットします。

start_time = time.time()
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_], axis=0)
elapsed_time = time.time() - start_time

print(f"Elapsed time to compute the importances: {elapsed_time:.3f} seconds")

forest_importances = pd.Series(importances, index=feature_names)

fig, ax = plt.subplots()
forest_importances.plot.bar(yerr=std, ax=ax)
ax.set_title("Feature importances using MDI")
ax.set_ylabel("Mean decrease in impurity")
fig.tight_layout()

特徴量の置換に基づく特徴量の重要度

置換特徴量重要度は、不純度に基づく特徴量重要度の制限を克服します。高基数の特徴量に対するバイアスがなく、留出テストセットで計算できます。完全な置換重要度を計算します。特徴量を n 回シャッフルし、モデルを再適合させてその重要度を推定します。重要度のランキングをプロットします。

start_time = time.time()
result = permutation_importance(
    forest, X_test, y_test, n_repeats=10, random_state=42, n_jobs=2
)
elapsed_time = time.time() - start_time
print(f"Elapsed time to compute the importances: {elapsed_time:.3f} seconds")

forest_importances = pd.Series(result.importances_mean, index=feature_names)

fig, ax = plt.subplots()
forest_importances.plot.bar(yerr=result.importances_std, ax=ax)
ax.set_title("Feature importances using permutation on full model")
ax.set_ylabel("Mean accuracy decrease")
fig.tight_layout()
plt.show()

まとめ

この実験では、3 つの情報量のある特徴量のみからなる合成データセットを生成し、ランダムフォレストを使って特徴量の重要度を評価しました。誤差バーで表される木間の変動性とともに、フォレストの特徴量の重要度をプロットしました。不純度に基づく重要度と特徴量の置換に基づく重要度を使って特徴量の重要度を計算しました。両方の方法を使って、同じ特徴量が最も重要であると検出されました。