본문 바로가기
머신러닝

[머신러닝][파이썬] XGBoost Regressor(회귀)

by 방구석 데이터사이언티스트 2023. 7. 1.
728x90
반응형

안녕하세요. 오늘은 파이썬을 통해 XGBoost Regressor를 구현해 보도록하겠습니다.

데이터는 야구 데이터이며, 종속변수는 팀의 득점입니다. 

 

해당 자료는 랜덤포레스트 게시글과 동일한 데이터를 사용합니다.

 

1. 모듈 불러오기

import xgboost as xgb
from xgboost import plot_importance
import warnings
warnings.filterwarnings('ignore')

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from sklearn import datasets
from sklearn.model_selection import cross_val_score
from bayes_opt import BayesianOptimization

먼저 필요한 라이브러리를 불러옵니다.

xgboost 구현을 위해서 사이킷런이 아닌 xgboost 자체 모듈을 사용합니다.

 

가장 마지막 줄은 파라미터 조절을 위한 베이지안 옵티마이제이션입니다. 

2. 데이터 분리 및 파라미터 최적화

X_11 = RUN_ONE_1.iloc[:, :-1]
y_11 = RUN_ONE_1.iloc[:, -1]
X_train11, X_test11, y_train11, y_test11=train_test_split(X_11, y_11,
                                                  test_size=0.2, random_state=0)
                                                 
dtrain = xgb.DMatrix(data=X_train11, label=y_train11)
dtest = xgb.DMatrix(data=X_test11, label=y_test11)


def xgb_evaluate(max_depth, gamma, colsample_bytree,min_child_weight,eta,subsample):
    params = {'eval_metric': 'rmse',
              'objective':'reg:squarederror',
              'min_child_weight': min_child_weight,
              'max_depth': int(max_depth),
              'subsample': subsample,
              'eta': eta,
              'gamma': gamma,
              'colsample_bytree': colsample_bytree}
    # Used around 1000 boosting rounds in the full model
    cv_result = xgb.cv(params, dtrain, num_boost_round=100, nfold=3)    
    
    # Bayesian optimization only knows how to maximize, not minimize, so return the negative RMSE
    return -1.0 * cv_result['test-rmse-mean'].iloc[-1]

xgb_bo = BayesianOptimization(xgb_evaluate, {'max_depth': (3, 7), 
                                             'gamma': (0, 1),
                                             'colsample_bytree': (0.3, 0.9),
                                            'min_child_weight': (5, 9),
                                            'eta':(0.1, 0.3),
                                            'subsample':(0.7,1.0)},random_state = 0 )
# Use the expected improvement acquisition function to handle negative numbers
# Optimally needs quite a few more initiation points and number of iterations
xgb_bo.maximize(init_points=3, n_iter=5, acq='ei')

그 다음 데이터를 불러오고 필요에 맞게 분리합니다. 그리고 분리된 데이터를 xgb.DMatirx를 통해 xgb와 호환되는 행렬로 처리해줍니다. \

파라미터는 6개 정도를 휴리스틱한 범위로 설정하여 베이지안 최적화를 수행했습니다. 요즘은 AutoML로 파라미터를 쉽게 최적화 할 수 있고, 몇몇 AutoML은 베이지안 최적화를 기반으로 하는 것으로 알고 있습니다. 

3. 모델 학습

dtrain = xgb.DMatrix(data=X_train11, label=y_train11)
dtest = xgb.DMatrix(data=X_test11, label=y_test11)

params = {
         'max_depth': 3,
         'eta': 0.1,
         'objective':'reg:squarederror',
         'eval_metric': 'rmse',
         'early_stopings':10,
         'gamma': 0,
         'colsample_bytree':0.9,
         'min_child_weight':9,
         'subsample': 1
         }
num_rounds = 500

wlist = [(dtrain, 'train'),(dtest, 'eval')]
xgb_run =xgb.train(params = params, dtrain=dtrain, num_boost_round=num_rounds, early_stopping_rounds=10, evals=wlist)

pred = xgb_run.predict(dtest)



from xgboost import plot_importance # 득점모델의 변수 중요도
import matplotlib.pyplot as plt
%matplotlib inline

fig, ax = plt.subplots(figsize=(24, 34))
plot_importance(xgb_run, ax=ax)

베이지안 최적화를 통해 얻은 파라미터를 기반으로 xgboost를 학습합니다. 코드의 후반부는 변수 중요도를 보기위한 코드입니다.

변수 중요도는 말 그대로 해당 변수가 모델이 설계되는데 얼마나 영향을 미쳤는지를 나타내는 척도입니다. 하지만 변수중요도가 낮게 나왔다고해서 중요하지 않은 변수는 아니며, 이는 또한 다양한 기법을 통해 더 확인해 봐야 합니다. 

 

4. 모델 성능 측정

a11 = RUN_T.iloc[:, :-1]
b11 = RUN_T.iloc[:, -1]
atest = xgb.DMatrix(data=a11)
xgb_run_predict = xgb_run.predict(atest)
print("RMSE':{}".format(math.sqrt(mean_squared_error(xgb_run_predict, b11))) )

성능 측정은 RMSE를 통해 확인합니다. 회귀모델을 평가하기 위한 다양한 매트릭이 존재하지만, 다들 실제값과 예측값의 차이를 나타내는 방법이 다를 뿐 크게 봤을 때는 전부 오차의 정도를 얘기합니다. 

728x90
반응형

댓글