ランダムフォレスト

Pythonで学ぶ木ベースのMachine Learning

Elie Kawerk

Data Scientist

バギング

  • 基本推定器:決定木、ロジスティック回帰、ニューラルネットなど

  • 各推定器は訓練セットの異なるブートストラップサンプルで学習

  • 推定器はすべての特徴量を使用して学習・予測

Pythonで学ぶ木ベースのMachine Learning

ランダムフォレストによる多様性の強化

  • 基本推定器:決定木

  • 各推定器は訓練セットと同じサイズの異なるブートストラップサンプルで学習

  • RF は個々のツリーの学習にさらなるランダム性を導入

  • 各ノードで $d$ 個の特徴量を非復元抽出
    ( $d < \text{total number of features}$ )

Pythonで学ぶ木ベースのMachine Learning

ランダムフォレスト:学習

ランダムフォレストの学習

Pythonで学ぶ木ベースのMachine Learning

ランダムフォレスト:予測

ランダムフォレストの予測

Pythonで学ぶ木ベースのMachine Learning

ランダムフォレスト:分類と回帰

分類:

  • 多数決で予測を集約
  • scikit-learn の RandomForestClassifier

回帰:

  • 平均化で予測を集約
  • scikit-learn の RandomForestRegressor
Pythonで学ぶ木ベースのMachine Learning

sklearn のランダムフォレスト回帰(autoデータセット)

# Basic imports
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error as MSE
# Set seed for reproducibility
SEED = 1

# Split dataset into 70% train and 30% test
X_train, X_test, y_train, y_test = train_test_split(X, y, 
                                                    test_size=0.3,
                                                    random_state=SEED)
Pythonで学ぶ木ベースのMachine Learning
# Instantiate a random forests regressor 'rf' 400 estimators
rf = RandomForestRegressor(n_estimators=400, 
                                   min_samples_leaf=0.12,  
                                   random_state=SEED)

# Fit 'rf' to the training set rf.fit(X_train, y_train) # Predict the test set labels 'y_pred' y_pred = rf.predict(X_test)
# Evaluate the test set RMSE
rmse_test = MSE(y_test, y_pred)**(1/2)

# Print the test set RMSE
print('Test set RMSE of rf: {:.2f}'.format(rmse_test))
Test set RMSE of rf: 3.98
Pythonで学ぶ木ベースのMachine Learning

特徴量の重要度

ツリーベースの手法:各特徴量の予測への重要度を測定できます。

sklearn では:

  • ノードが特定の特徴量を使って不純度を削減する度合い(加重平均)
  • feature_importance_ 属性でアクセス可能
Pythonで学ぶ木ベースのMachine Learning

sklearn での特徴量の重要度

import pandas as pd
import matplotlib.pyplot as plt

# Create a pd.Series of features importances
importances_rf = pd.Series(rf.feature_importances_, index = X.columns)

# Sort importances_rf                                   
sorted_importances_rf = importances_rf.sort_values()   

# Make a horizontal bar plot
sorted_importances_rf.plot(kind='barh', color='lightgreen'); plt.show()
Pythonで学ぶ木ベースのMachine Learning

sklearn での特徴量の重要度

特徴量の重要度(ランダムフォレスト)

Pythonで学ぶ木ベースのMachine Learning

練習しましょう!

Pythonで学ぶ木ベースのMachine Learning

Preparing Video For Download...