隨機森林

Machine Learning with Tree-Based Models in Python

Elie Kawerk

Data Scientist

裝袋法(Bagging)

  • 基礎估計器:Decision Tree、Logistic Regression、Neural Net 等

  • 每個估計器各自以訓練集的不同自助抽樣樣本進行訓練

  • 估計器在訓練與預測時使用所有特徵

Machine Learning with Tree-Based Models in Python

隨機森林帶來更多多樣性

  • 基礎估計器:Decision Tree

  • 每個估計器以與訓練集相同大小、但不同的自助抽樣樣本訓練

  • RF 在個別樹的訓練中引入更多隨機性

  • 在每個節點無放回抽樣 $d$ 個特徵
    ($d < \text{total number of features}$)

Machine Learning with Tree-Based Models in Python

隨機森林:訓練

隨機森林訓練

Machine Learning with Tree-Based Models in Python

隨機森林:預測

隨機森林預測

Machine Learning with Tree-Based Models in Python

隨機森林:分類與迴歸

分類

  • 以多數決彙總預測
  • scikit-learn 的 RandomForestClassifier

迴歸

  • 以平均值彙總預測
  • scikit-learn 的 RandomForestRegressor
Machine Learning with Tree-Based Models in Python

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)
Machine Learning with Tree-Based Models in Python
# 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
Machine Learning with Tree-Based Models in Python

特徵重要性

以樹為基礎的方法:可量化各特徵對預測的重要性。

sklearn 中:

  • 觀察樹節點使用某特徵以降低不純度的程度(加權平均)
  • 透過屬性 feature_importance_ 取得
Machine Learning with Tree-Based Models in Python

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()
Machine Learning with Tree-Based Models in Python

sklearn 的特徵重要性

特徵重要性(RF)

Machine Learning with Tree-Based Models in Python

一起來練習吧!

Machine Learning with Tree-Based Models in Python

Preparing Video For Download...