머신러닝 앙상블 학습(Ensemble Learning) - 부스팅(Boosting) (2) : XGBoost

2 minute read

1. XGBoost (eXtra Gradient Boost)

GBM 기반의 XGBoost는 다른 머신러닝보다 뛰어난 예측 성능을 보인다. 그러면서 GBM의 단점이었던 느린 수행 시간과 과적합 규제(Regularization) 부재의 문제 또한 극복했다는 점, Tree Pruning이 가능하다는 점, 자체적으로 내장된 교차 검증과 조기중단(Early Stopping), 결손값 처리 기능을 가지고 있다는 점도 XGBoost의 장점이다.

XGBoost도 랜덤 포레스트에 비해서는 느리다.

2. XGBoost 주요 파라미터 (사이킷런 Wrapper)

사이킷런 Wrapper에서 사용하는 XGBoost 파라미터들은 기본적으로 GBM의 파라미터와 유사하며, GBM에 해당하는 파라미터가 없다면 파이썬 Wrapper의 하이퍼 파라미터를 가져온다.

GBM 하이퍼 파라미터 설명글 보기

이전 글들에서 다루지 않았던 부분만 정리해보자. 사실 XGBoost에서 하이퍼 파라미터 튜닝에는 그렇게 공을 들이지 않는 편이 좋다.

  • min_child_weight : 결정트리의 min_child_leaf와 유사하며, 트리에서 추가적으로 가지를 나눌지를 결정하기 위해 필요한 데이터들의 weight 총합. 값이 클수록 분할을 자제하여 과적합을 조절하는 용도로 사용됨 (디폴트는 1)
  • gamma : 트리의 리프 노드를 추가적으로 나눌지를 결정할 최소 손실 감소 값으로 값이 클수록 과적합 감소 효과가 있음 (디폴트는 0)
  • reg_lambda : L2 Regularizaiton 적용 값. 값이 클수록 과적합 감소 효과가 있음 (디폴트는 1)
  • reg_alpha : L1 Reuglarization 적용 값. 값이 클수록 과적합 감소 효과가 있음 (디폴트는 0)
  • colsample_bytree : max_features와 유사하며, 트리 생성에 필요한 피처를 임의로 샘플링하는 데 사용됨 (디폴트는 1)
  • scale_pos_weight : 비대칭 클래스로 구성된 데이터셋의 균형을 유지하기 위한 파라미터 (디폴트는 1)

3. 사이킷런에서 구현하기

데이터셋을 로딩하고 train_test_split()을 진행해보자.

import pandas as pd
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

dataset = load_breast_cancer()
X_features= dataset.data
y_label = dataset.target

X_train, X_test, y_train, y_test=train_test_split(X_features, y_label, test_size=0.2, random_state=156)
print(X_train.shape , X_test.shape) # (455, 30) (114, 30)

사이킷런 Wrapper XGBoost를 적용해보자.

from xgboost import XGBClassifier
from xgboost import plot_importance

xgb_wrapper = XGBClassifier(n_estimators=400, learning_rate=0.1, max_depth=3)

evals = [(X_test, y_test)] # 원래는 이렇게 하면 과적합
xgb_wrapper.fit(X_train, y_train, early_stopping_rounds=100, eval_metric="logloss", eval_set=evals, verbose=True)

ws100_preds = xgb_wrapper.predict(X_test)
ws100_pred_proba = xgb_wrapper.predict_proba(X_test)[:, 1]
[0]	validation_0-logloss:0.61352
Will train until validation_0-logloss hasn't improved in 100 rounds.
[1]	validation_0-logloss:0.547842
.
.
.
[311]	validation_0-logloss:0.085948
Stopping. Best iteration:
[211]	validation_0-logloss:0.085593

early_stopping_rounds 값을 100으로 했기 때문에 n_estimators 값인 400회에 도달하지 않더라도 예측 오류가 100번 동안 더 이상 개선되지 않으면 반복을 중지해 수행 시간을 줄일 수 있다. 단, early_stopping_rounds를 사용하기 위해서는 조기중단을 위한 평가지표인 eval_metric과 성능평가를 수행할 데이터셋인 eval_set을 함께 지정해줘야 한다.

  • logloss : Negative log-likelihood
  • eval_set : [(X_train, y_train), (X_test, y_test)]로 입력해도 되지만 [(X_test, y_test)]가 좀 더 명확한 설정이다. 그리고 원래는 지금처럼 테스트 데이터를 사용하는 것이 아니라 별도의 validation 데이터를 사용해야 한다.

XGBClassifier의 예측 성능을 확인해보자.

from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.metrics import precision_score, recall_score
from sklearn.metrics import f1_score, roc_auc_score

confusion = confusion_matrix(y_test, ws100_preds)
accuracy = accuracy_score(y_test, ws100_preds)
precision = precision_score(y_test, ws100_preds)
recall = recall_score(y_test, ws100_preds)
f1 = f1_score(y_test, ws100_preds)
roc_auc = roc_auc_score(y_test, ws100_pred_proba)

print(confusion)
print('정확도: {0:.4f}, 정밀도: {1:.4f}, 재현율: {2:.4f}, F1: {3:.4f}, AUC:{4:.4f}'.format(accuracy, precision, recall, f1, roc_auc))
[[34  3]
 [ 1 76]]
정확도: 0.9649, 정밀도: 0.9620, 재현율: 0.9870, F1: 0.9744, AUC:0.9954

4. plot_importance()

XGBoost의 plot_importance() API를 사용하면 피처의 중요도를 쉽게 시각화할 수 있다.

from xgboost import plot_importance
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 12))
plot_importance(xgb_wrapper, ax=ax)

image

Leave a comment