xgboost: Regression

    # nolint start
    library(mlexperiments)
    library(mllrnrs)

See https://github.com/kapsner/mllrnrs/blob/main/R/learner_xgboost.R for implementation details.

# Preprocessing

## Import and Prepare Data

    library(mlbench)
    data("BostonHousing")
    dataset <- BostonHousing |>
      data.table::as.data.table() |>
      na.omit()

    feature_cols <- colnames(dataset)[1:13]
    target_col <- "medv"

## General Configurations

    seed <- 123
    if (isTRUE(as.logical(Sys.getenv("_R_CHECK_LIMIT_CORES_")))) {
      # on cran
      ncores <- 2L
    } else {
      ncores <- ifelse(
        test = parallel::detectCores() > 4,
        yes = 4L,
        no = ifelse(
          test = parallel::detectCores() < 2L,
          yes = 1L,
          no = parallel::detectCores()
        )
      )
    }
    options("mlexperiments.bayesian.max_init" = 4L)
    options("mlexperiments.optim.xgb.nrounds" = 20L)
    options("mlexperiments.optim.xgb.early_stopping_rounds" = 5L)

## Generate Training- and Test Data

    data_split <- splitTools::partition(
      y = dataset[, get(target_col)],
      p = c(train = 0.7, test = 0.3),
      type = "stratified",
      seed = seed
    )

    train_x <- model.matrix(
      ~ -1 + .,
      dataset[data_split$train, .SD, .SDcols = feature_cols]
    )
    train_y <- log(dataset[data_split$train, get(target_col)])

    test_x <- model.matrix(
      ~ -1 + .,
      dataset[data_split$test, .SD, .SDcols = feature_cols]
    )
    test_y <- log(dataset[data_split$test, get(target_col)])

## Generate Training Data Folds

    fold_list <- splitTools::create_folds(
      y = train_y,
      k = 3,
      type = "stratified",
      seed = seed
    )

# Experiments

## Prepare Experiments

    # required learner arguments, not optimized
    learner_args <- list(
      objective = "reg:squarederror",
      eval_metric = "rmse"
    )

    # set arguments for predict function and performance metric,
    # required for mlexperiments::MLCrossValidation and
    # mlexperiments::MLNestedCV
    predict_args <- NULL
    performance_metric <- metric("rmsle")
    performance_metric_args <- NULL
    return_models <- FALSE

    # required for grid search and initialization of bayesian optimization
    parameter_grid <- expand.grid(
      subsample = seq(0.6, 1, .2),
      colsample_bytree = seq(0.6, 1, .2),
      min_child_weight = seq(1, 5, 4),
      learning_rate = seq(0.1, 0.2, 0.1),
      max_depth = seq(1, 5, 4)
    )
    # reduce to a maximum of 10 rows
    if (nrow(parameter_grid) > 10) {
      set.seed(123)
      sample_rows <- sample(seq_len(nrow(parameter_grid)), 10, FALSE)
      parameter_grid <- kdry::mlh_subset(parameter_grid, sample_rows)
    }

    # required for bayesian optimization
    parameter_bounds <- list(
      subsample = c(0.2, 1),
      colsample_bytree = c(0.2, 1),
      min_child_weight = c(1L, 10L),
      learning_rate = c(0.1, 0.2),
      max_depth =  c(1L, 10L)
    )
    optim_args <- list(
      n_iter = ncores,
      kappa = 3.5,
      acq = "ucb"
    )

## Hyperparameter Tuning

### Grid Search

    tuner <- mlexperiments::MLTuneParameters$new(
      learner = mllrnrs::LearnerXgboost$new(
        metric_optimization_higher_better = FALSE
      ),
      strategy = "grid",
      ncores = ncores,
      seed = seed
    )

    tuner$parameter_grid <- parameter_grid
    tuner$learner_args <- learner_args
    tuner$split_type <- "stratified"

    tuner$set_data(
      x = train_x,
      y = train_y
    )

    tuner_results_grid <- tuner$execute(k = 3)
    #>
    #> Parameter settings [=====================================>----------------------------------------------------------] 4/10 ( 40%)
    #> Parameter settings [===============================================>------------------------------------------------] 5/10 ( 50%)
    #> Parameter settings [=========================================================>--------------------------------------] 6/10 ( 60%)
    #> Parameter settings [==================================================================>-----------------------------] 7/10 ( 70%)
    #> Parameter settings [============================================================================>-------------------] 8/10 ( 80%)
    #> Parameter settings [=====================================================================================>----------] 9/10 ( 90%)
    #> Parameter settings [===============================================================================================] 10/10 (100%)

    head(tuner_results_grid)
    #>    setting_id metric_optim_mean nrounds subsample colsample_bytree min_child_weight learning_rate max_depth        objective
    #>         <int>             <num>   <int>     <num>            <num>            <num>         <num>     <num>           <char>
    #> 1:          1         0.1872223      62       0.6              0.8                5           0.2         1 reg:squarederror
    #> 2:          2         0.1688788      99       1.0              0.8                5           0.1         5 reg:squarederror
    #> 3:          3         0.1916676      97       0.8              0.8                5           0.1         1 reg:squarederror
    #> 4:          4         0.1662343      55       0.6              0.8                5           0.2         5 reg:squarederror
    #> 5:          5         0.1635528     100       1.0              0.8                1           0.1         5 reg:squarederror
    #> 6:          6         0.1641982     100       0.8              0.8                5           0.1         5 reg:squarederror
    #>    eval_metric
    #>         <char>
    #> 1:        rmse
    #> 2:        rmse
    #> 3:        rmse
    #> 4:        rmse
    #> 5:        rmse
    #> 6:        rmse

### Bayesian Optimization

    tuner <- mlexperiments::MLTuneParameters$new(
      learner = mllrnrs::LearnerXgboost$new(
        metric_optimization_higher_better = FALSE
      ),
      strategy = "bayesian",
      ncores = ncores,
      seed = seed
    )

    tuner$parameter_grid <- parameter_grid
    tuner$parameter_bounds <- parameter_bounds

    tuner$learner_args <- learner_args
    tuner$optim_args <- optim_args

    tuner$split_type <- "stratified"

    tuner$set_data(
      x = train_x,
      y = train_y
    )

    tuner_results_bayesian <- tuner$execute(k = 3)
    #>
    #> Registering parallel backend using 4 cores.

    head(tuner_results_bayesian)
    #>    Epoch setting_id subsample colsample_bytree min_child_weight learning_rate max_depth gpUtility acqOptimum inBounds Elapsed
    #>    <num>      <int>     <num>            <num>            <num>         <num>     <num>     <num>     <lgcl>   <lgcl>   <num>
    #> 1:     0          1       0.6              0.8                5           0.2         1        NA      FALSE     TRUE   0.915
    #> 2:     0          2       1.0              0.8                5           0.1         5        NA      FALSE     TRUE   1.028
    #> 3:     0          3       0.8              0.8                5           0.1         1        NA      FALSE     TRUE   0.935
    #> 4:     0          4       0.6              0.8                5           0.2         5        NA      FALSE     TRUE   1.013
    #> 5:     0          5       1.0              0.8                1           0.1         5        NA      FALSE     TRUE   0.248
    #> 6:     0          6       0.8              0.8                5           0.1         5        NA      FALSE     TRUE   0.218
    #>         Score metric_optim_mean nrounds errorMessage        objective eval_metric
    #>         <num>             <num>   <int>       <lgcl>           <char>      <char>
    #> 1: -0.1872223         0.1872223      62           NA reg:squarederror        rmse
    #> 2: -0.1688788         0.1688788      99           NA reg:squarederror        rmse
    #> 3: -0.1916676         0.1916676      97           NA reg:squarederror        rmse
    #> 4: -0.1662343         0.1662343      55           NA reg:squarederror        rmse
    #> 5: -0.1635528         0.1635528     100           NA reg:squarederror        rmse
    #> 6: -0.1641982         0.1641982     100           NA reg:squarederror        rmse

## k-Fold Cross Validation

    validator <- mlexperiments::MLCrossValidation$new(
      learner = mllrnrs::LearnerXgboost$new(
        metric_optimization_higher_better = FALSE
      ),
      fold_list = fold_list,
      ncores = ncores,
      seed = seed
    )

    validator$learner_args <- tuner$results$best.setting[-1]

    validator$predict_args <- predict_args
    validator$performance_metric <- performance_metric
    validator$performance_metric_args <- performance_metric_args
    validator$return_models <- return_models

    validator$set_data(
      x = train_x,
      y = train_y
    )

    validator_results <- validator$execute()
    #>
    #> CV fold: Fold1
    #>
    #> CV fold: Fold2
    #>
    #> CV fold: Fold3

    head(validator_results)
    #>      fold performance subsample colsample_bytree min_child_weight learning_rate max_depth nrounds        objective eval_metric
    #>    <char>       <num>     <num>            <num>            <num>         <num>     <num>   <int>           <char>      <char>
    #> 1:  Fold1  0.03396237       0.6                1                1           0.1         5      99 reg:squarederror        rmse
    #> 2:  Fold2  0.05035231       0.6                1                1           0.1         5      99 reg:squarederror        rmse
    #> 3:  Fold3  0.03987737       0.6                1                1           0.1         5      99 reg:squarederror        rmse

## Nested Cross Validation

### Inner Grid Search

    validator <- mlexperiments::MLNestedCV$new(
      learner = mllrnrs::LearnerXgboost$new(
        metric_optimization_higher_better = FALSE
      ),
      strategy = "grid",
      fold_list = fold_list,
      k_tuning = 3L,
      ncores = ncores,
      seed = seed
    )

    validator$parameter_grid <- parameter_grid
    validator$learner_args <- learner_args
    validator$split_type <- "stratified"

    validator$predict_args <- predict_args
    validator$performance_metric <- performance_metric
    validator$performance_metric_args <- performance_metric_args
    validator$return_models <- return_models

    validator$set_data(
      x = train_x,
      y = train_y
    )

    validator_results <- validator$execute()
    #>
    #> CV fold: Fold1
    #>
    #> Parameter settings [=====================================>----------------------------------------------------------] 4/10 ( 40%)
    #> Parameter settings [===============================================>------------------------------------------------] 5/10 ( 50%)
    #> Parameter settings [=========================================================>--------------------------------------] 6/10 ( 60%)
    #> Parameter settings [==================================================================>-----------------------------] 7/10 ( 70%)
    #> Parameter settings [============================================================================>-------------------] 8/10 ( 80%)
    #> Parameter settings [=====================================================================================>----------] 9/10 ( 90%)
    #> Parameter settings [===============================================================================================] 10/10 (100%)
    #> CV fold: Fold2
    #> CV progress [====================================================================>-----------------------------------] 2/3 ( 67%)
    #>
    #> Parameter settings [============================>-------------------------------------------------------------------] 3/10 ( 30%)
    #> Parameter settings [=====================================>----------------------------------------------------------] 4/10 ( 40%)
    #> Parameter settings [===============================================>------------------------------------------------] 5/10 ( 50%)
    #> Parameter settings [=========================================================>--------------------------------------] 6/10 ( 60%)
    #> Parameter settings [==================================================================>-----------------------------] 7/10 ( 70%)
    #> Parameter settings [============================================================================>-------------------] 8/10 ( 80%)
    #> Parameter settings [=====================================================================================>----------] 9/10 ( 90%)
    #> Parameter settings [===============================================================================================] 10/10 (100%)
    #> CV fold: Fold3
    #> CV progress [========================================================================================================] 3/3 (100%)
    #>
    #> Parameter settings [===============================================>------------------------------------------------] 5/10 ( 50%)
    #> Parameter settings [=========================================================>--------------------------------------] 6/10 ( 60%)
    #> Parameter settings [==================================================================>-----------------------------] 7/10 ( 70%)
    #> Parameter settings [============================================================================>-------------------] 8/10 ( 80%)
    #> Parameter settings [=====================================================================================>----------] 9/10 ( 90%)
    #> Parameter settings [===============================================================================================] 10/10 (100%)

    head(validator_results)
    #>      fold performance nrounds subsample colsample_bytree min_child_weight learning_rate max_depth        objective eval_metric
    #>    <char>       <num>   <int>     <num>            <num>            <num>         <num>     <num>           <char>      <char>
    #> 1:  Fold1  0.03942935      53       0.8              0.8                5           0.1         5 reg:squarederror        rmse
    #> 2:  Fold2  0.05037283     100       0.6              1.0                1           0.1         5 reg:squarederror        rmse
    #> 3:  Fold3  0.04125686      35       0.6              1.0                5           0.2         5 reg:squarederror        rmse

### Inner Bayesian Optimization

    validator <- mlexperiments::MLNestedCV$new(
      learner = mllrnrs::LearnerXgboost$new(
        metric_optimization_higher_better = FALSE
      ),
      strategy = "bayesian",
      fold_list = fold_list,
      k_tuning = 3L,
      ncores = ncores,
      seed = seed
    )

    validator$parameter_grid <- parameter_grid
    validator$learner_args <- learner_args
    validator$split_type <- "stratified"

    validator$parameter_bounds <- parameter_bounds
    validator$optim_args <- optim_args

    validator$predict_args <- predict_args
    validator$performance_metric <- performance_metric
    validator$performance_metric_args <- performance_metric_args
    validator$return_models <- TRUE

    validator$set_data(
      x = train_x,
      y = train_y
    )

    validator_results <- validator$execute()
    #>
    #> CV fold: Fold1
    #>
    #> Registering parallel backend using 4 cores.
    #>
    #> CV fold: Fold2
    #> CV progress [====================================================================>-----------------------------------] 2/3 ( 67%)
    #>
    #> Registering parallel backend using 4 cores.
    #>
    #> CV fold: Fold3
    #> CV progress [========================================================================================================] 3/3 (100%)
    #>
    #> Registering parallel backend using 4 cores.

    head(validator_results)
    #>      fold performance subsample colsample_bytree min_child_weight learning_rate max_depth nrounds        objective eval_metric
    #>    <char>       <num>     <num>            <num>            <num>         <num>     <num>   <int>           <char>      <char>
    #> 1:  Fold1  0.04712865 0.5029800        0.4977050                6     0.1195995         2      53 reg:squarederror        rmse
    #> 2:  Fold2  0.05054316 0.4489853        0.7725962                2     0.2000000         5      65 reg:squarederror        rmse
    #> 3:  Fold3  0.04027241 0.7465061        0.8234365                1     0.2000000         5      29 reg:squarederror        rmse

## Holdout Test Dataset Performance

### Predict Outcome in Holdout Test Dataset

    preds_xgboost <- mlexperiments::predictions(
      object = validator,
      newdata = test_x
    )

### Evaluate Performance on Holdout Test Dataset

    perf_xgboost <- mlexperiments::performance(
      object = validator,
      prediction_results = preds_xgboost,
      y_ground_truth = test_y,
      type = "regression"
    )
    perf_xgboost
    #>     model performance      SSE        MSE      RMSE       MEDSE      SAE       MAE      MEDAE       RSQ    EXPVAR      RRSE
    #>    <char>       <num>    <num>      <num>     <num>       <num>    <num>     <num>      <num>     <num>     <num>     <num>
    #> 1:  Fold1  0.04135927 4.102050 0.02646484 0.1626802 0.006572713 17.66284 0.1139538 0.08107227 0.8278688 0.8280100 0.4148870
    #> 2:  Fold2  0.04757084 4.799370 0.03096368 0.1759650 0.006181385 19.54728 0.1261115 0.07862178 0.7986077 0.9943971 0.4487675
    #> 3:  Fold3  0.03918577 3.567998 0.02301934 0.1517213 0.006275152 17.01818 0.1097947 0.07921586 0.8502788 0.8048249 0.3869382
    #>          RAE       MAPE KendallTau SpearmanRho
    #>        <num>      <num>      <num>       <num>
    #> 1: 0.3847300 0.03826134  0.7533943   0.9036017
    #> 2: 0.4257766 0.04426443  0.7628554   0.9148171
    #> 3: 0.3706880 0.03763162  0.7815047   0.9278985