카테고리 없음

XGBoost Metric 확인

카카오그래놀라 2021. 10. 12. 14:41

XGBoost Metric 종류

https://xgboost.readthedocs.io/en/latest/parameter.html#:~:text=too%20much%20effect.-,eval_metric,-%5Bdefault%20according%20to

 

 

XGBoost Parameters — xgboost 1.6.0-dev documentation

XGBoost Parameters Before running XGBoost, we must set three types of parameters: general parameters, booster parameters and task parameters. General parameters relate to which booster we are using to do boosting, commonly tree or linear model Booster para

xgboost.readthedocs.io

 

자주 쓰이는 Metric 예시

 

사용 방법

선언한 모델 메소드 fit()을 실행할 때,

eval_set

eval_metric을 지정해주면 됩니다.

 

eval_set 지정 방법

리스트안에 x, y 값을 튜플로 묶어 담아두면 됩니다. 밑의 코드를 보면 이해가 빠릅니다.

 

eval_metric 지정 방법

위에서 알아본, XGBoost 메트릭의 이름('rmse', 'rmsle', 'mae', 'auc' 등)을 써주면 됩니다. 밑의 코드를 보면 이해가 빠릅니다.

x = data.drop(['target'], axis=1)
y = data['target']

train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.2, random_state=32)

model = xgb.XGBRegressor()
model.fit(
    train_x,
    train_y,
    eval_set=[(train_x, train_y),(test_x, test_y)],
    eval_metric='rmse'
    )
pred = model.predict(test_x)

 

 

 

 

추가 팁: Custom Metric 사용하기

준비물

1. xgboost.DMatrix

위의 경우, Scikit-learn interface를 통해 모델을 학습했습니다. Custom Metric을 사용하기 위해서는 Python Package 형태로 학습을 진행해야합니다.

이를 위해서 우선 데이터를 xgboost.DMatrix로 바꿔줘야 합니다.

바꾸는 방법은 굉장히 쉬운데, 아래 코드를 통해 쉽게 확인할 수 있습니다.

xgb.DMatrix에 x값 및 label에 y값을 넘겨주면 쉽게 만들 수 있습니다.

x = data.drop(['target'], axis=1)
y = data['target']
train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.2, random_state=32)

train = xgb.DMatrix(train_x, label=train_y)
test = xgb.DMatrix(test_x, label=test_y)

 

2. Metric 함수

y_pred, Dmatrix를 인자로 받는 함수를 만들어 줍니다.

Dmatrix의 get_label() 메서드를 통해 y_label 값을 얻을 수 있습니다.

y_pred와 y_label을 통해 Metric 함수를 작성합니다.

return 값으로, Metric 함수이름과 Metric함수를 넘겨주면 됩니다.

def custom_rmse(y_pred, Dmatrix):
    labels = Dmatrix.get_label()
    return ('custom_rmse', np.sqrt(np.mean(np.power(y_pred - labels, 2))))

 

사용 예시

xgboost.DMatrix는 train()메서드를 통해 모델을 훈련합니다. 인자값으로 feval=함수명 을 입력해주면 custom Metric을 사용할 수 있습니다.

param = {
    'max_depth':5, 
    'objective': 'reg:squarederror', 
    'eta' : 0.1,
}
model = xgb.train(param, train, num_boost_round=100, evals=[(test, 'test')], feval=custom_rmse)

 

 

 

 

LightGBM Metric 확인을 알아보고 싶다면, 아래 글을 참고하세요!
https://deep-deep-deep.tistory.com/159

 

LightGBM metric 확인

LightGBM 지원 Metric https://lightgbm.readthedocs.io/en/latest/Parameters.html?highlight=metric#metric Parameters — LightGBM 3.3.0.99 documentation objective 🔗︎, default = regression, type = enum..

deep-deep-deep.tistory.com