勾配ブースティングの特徴量の重要度
ランダムフォレストと同様に、勾配ブースティングモデルからも特徴量の重要度を抽出することで、どの特徴量が最も予測に有効かを把握できます。複数の木ベースのモデルを試して、それぞれの特徴量の重要度を比較してみると有益です。これにより、特定のモデルに固有の偏りを平均化することができます。
特徴量の重要度は、勾配ブースティングモデルの .feature_importances_ プロパティに numpy 配列として格納されています。見やすいグラフを作成するために、np.argsort() を使って特徴量の重要度をソートしたインデックスを取得する必要があります。重要度を大きい順に並べたいので、Pythonのインデックス指定 feat_importances[::-1] を使ってソート済みの重要度を逆順にします。
この演習はコースの一部です
Python による金融のための Machine Learning
演習の手順
- Pythonのインデックス指定を使って、
sorted_index変数を大きい順(降順)に並べ替えましょう。 feature_namesを numpy 配列に変換し、sorted_indexでインデックス指定することで、ソート済みの特徴量ラベルリストlabelsを作成しましょう。- x 軸の目盛り、
sorted_indexでインデックス指定したfeature_importances、およびlabelsを x 軸ラベルとして使用した棒グラフを作成しましょう。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Extract feature importances from the fitted gradient boosting model
feature_importances = gbr.feature_importances_
# Get the indices of the largest to smallest feature importances
sorted_index = np.argsort(feature_importances)[::____]
x = range(features.shape[1])
# Create tick labels
labels = np.array(feature_names)[____]
plt.bar(____, feature_importances[____], tick_label=____)
# Set the tick lables to be the feature names, according to the sorted feature_idx
plt.xticks(rotation=90)
plt.show()