Since the interface to xgboost
in caret
has recently changed, here is a script that provides a fully commented walkthrough of using caret
to tune xgboost
hyper-parameters.
For this, I will be using the training data from the Kaggle competition "Give Me Some Credit".
1. Fitting an xgboost
model
In this section, we:
- fit an
xgboost
model with arbitrary hyperparameters
- evaluate the loss (AUC-ROC) using cross-validation (
xgb.cv
)
- plot the training versus testing evaluation metric
Here is some code to do this.
library(caret)
library(xgboost)
library(readr)
library(dplyr)
library(tidyr)
# load in the training data
df_train = read_csv("04-GiveMeSomeCredit/Data/cs-training.csv") %>%
na.omit() %>% # listwise deletion
select(-`[EMPTY]`) %>%
mutate(SeriousDlqin2yrs = factor(SeriousDlqin2yrs, # factor variable for classification
labels = c("Failure", "Success")))
# xgboost fitting with arbitrary parameters
xgb_params_1 = list(
objective = "binary:logistic", # binary classification
eta = 0.01, # learning rate
max.depth = 3, # max tree depth
eval_metric = "auc" # evaluation/loss metric
)
# fit the model with the arbitrary parameters specified above
xgb_1 = xgboost(data = as.matrix(df_train %>%
select(-SeriousDlqin2yrs)),
label = df_train$SeriousDlqin2yrs,
params = xgb_params_1,
nrounds = 100, # max number of trees to build
verbose = TRUE,
print.every.n = 1,
early.stop.round = 10 # stop if no improvement within 10 trees
)
# cross-validate xgboost to get the accurate measure of error
xgb_cv_1 = xgb.cv(params = xgb_params_1,
data = as.matrix(df_train %>%
select(-SeriousDlqin2yrs)),
label = df_train$SeriousDlqin2yrs,
nrounds = 100,
nfold = 5, # number of folds in K-fold
prediction = TRUE, # return the prediction using the final model
showsd = TRUE, # standard deviation of loss across folds
stratified = TRUE, # sample is unbalanced; use stratified sampling
verbose = TRUE,
print.every.n = 1,
early.stop.round = 10
)
# plot the AUC for the training and testing samples
xgb_cv_1$dt %>%
select(-contains("std")) %>%
mutate(IterationNum = 1:n()) %>%
gather(TestOrTrain, AUC, -IterationNum) %>%
ggplot(aes(x = IterationNum, y = AUC, group = TestOrTrain, color = TestOrTrain)) +
geom_line() +
theme_bw()
Here is what the testing versus training AUC looks like:
2. Hyperparameter search using train
For the hyperparameter search, we perform the following steps:
- create a
data.frame
with unique combinations of parameters that we want trained models for.
- Specify the control parameters that apply to each model's training, including the cross-validation parameters, and specify that the probabilities be computed so that the AUC can be computed
- cross-validate & train the models for each parameter combination, saving the AUC for each model.
Here is some code that shows how to do this.
# set up the cross-validated hyper-parameter search
xgb_grid_1 = expand.grid(
nrounds = 1000,
eta = c(0.01, 0.001, 0.0001),
max_depth = c(2, 4, 6, 8, 10),
gamma = 1
)
# pack the training control parameters
xgb_trcontrol_1 = trainControl(
method = "cv",
number = 5,
verboseIter = TRUE,
returnData = FALSE,
returnResamp = "all", # save losses across all models
classProbs = TRUE, # set to TRUE for AUC to be computed
summaryFunction = twoClassSummary,
allowParallel = TRUE
)
# train the model for each parameter combination in the grid,
# using CV to evaluate
xgb_train_1 = train(
x = as.matrix(df_train %>%
select(-SeriousDlqin2yrs)),
y = as.factor(df_train$SeriousDlqin2yrs),
trControl = xgb_trcontrol_1,
tuneGrid = xgb_grid_1,
method = "xgbTree"
)
# scatter plot of the AUC against max_depth and eta
ggplot(xgb_train_1$results, aes(x = as.factor(eta), y = max_depth, size = ROC, color = ROC)) +
geom_point() +
theme_bw() +
scale_size_continuous(guide = "none")
Lastly, you can create a bubbleplot for the AUC over the variations of eta
and max_depth
:
xgboost(max.depth)
orxgb.train(max_depth)
? Does xgboost inconsistently use dot vs underscore for the parameter in different places? Or are they converted? $\endgroup$