랜덤 포레스트

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...