| 1 |
#' Cross Validation |
| 2 |
#' |
| 3 |
#' The cross validation function of xgboost. |
| 4 |
#' |
| 5 |
#' @inheritParams xgb.train |
| 6 |
#' @param data An `xgb.DMatrix` object, with corresponding fields like `label` or bounds as required |
| 7 |
#' for model training by the objective. |
| 8 |
#' |
| 9 |
#' Note that only the basic `xgb.DMatrix` class is supported - variants such as `xgb.QuantileDMatrix` |
| 10 |
#' or `xgb.ExtMemDMatrix` are not supported here. |
| 11 |
#' @param nfold The original dataset is randomly partitioned into `nfold` equal size subsamples. |
| 12 |
#' @param prediction A logical value indicating whether to return the test fold predictions |
| 13 |
#' from each CV model. This parameter engages the [xgb.cb.cv.predict()] callback. |
| 14 |
#' @param showsd Logical value whether to show standard deviation of cross validation. |
| 15 |
#' @param metrics List of evaluation metrics to be used in cross validation, |
| 16 |
#' when it is not specified, the evaluation metric is chosen according to objective function. |
| 17 |
#' Possible options are: |
| 18 |
#' - `error`: Binary classification error rate |
| 19 |
#' - `rmse`: Root mean square error |
| 20 |
#' - `logloss`: Negative log-likelihood function |
| 21 |
#' - `mae`: Mean absolute error |
| 22 |
#' - `mape`: Mean absolute percentage error |
| 23 |
#' - `auc`: Area under curve |
| 24 |
#' - `aucpr`: Area under PR curve |
| 25 |
#' - `merror`: Exact matching error used to evaluate multi-class classification |
| 26 |
#' @param stratified Logical flag indicating whether sampling of folds should be stratified |
| 27 |
#' by the values of outcome labels. For real-valued labels in regression objectives, |
| 28 |
#' stratification will be done by discretizing the labels into up to 5 buckets beforehand. |
| 29 |
#' |
| 30 |
#' If passing "auto", will be set to `TRUE` if the objective in `params` is a classification |
| 31 |
#' objective (from XGBoost's built-in objectives, doesn't apply to custom ones), and to |
| 32 |
#' `FALSE` otherwise. |
| 33 |
#' |
| 34 |
#' This parameter is ignored when `data` has a `group` field - in such case, the splitting |
| 35 |
#' will be based on whole groups (note that this might make the folds have different sizes). |
| 36 |
#' |
| 37 |
#' Value `TRUE` here is **not** supported for custom objectives. |
| 38 |
#' @param folds List with pre-defined CV folds (each element must be a vector of test fold's indices). |
| 39 |
#' When folds are supplied, the `nfold` and `stratified` parameters are ignored. |
| 40 |
#' |
| 41 |
#' If `data` has a `group` field and the objective requires this field, each fold (list element) |
| 42 |
#' must additionally have two attributes (retrievable through `attributes`) named `group_test` |
| 43 |
#' and `group_train`, which should hold the `group` to assign through [setinfo.xgb.DMatrix()] to |
| 44 |
#' the resulting DMatrices. |
| 45 |
#' @param train_folds List specifying which indices to use for training. If `NULL` |
| 46 |
#' (the default) all indices not specified in `folds` will be used for training. |
| 47 |
#' |
| 48 |
#' This is not supported when `data` has `group` field. |
| 49 |
#' @param callbacks A list of callback functions to perform various task during boosting. |
| 50 |
#' See [xgb.Callback()]. Some of the callbacks are automatically created depending on the |
| 51 |
#' parameters' values. User can provide either existing or their own callback methods in order |
| 52 |
#' to customize the training process. |
| 53 |
#' @details |
| 54 |
#' The original sample is randomly partitioned into `nfold` equal size subsamples. |
| 55 |
#' |
| 56 |
#' Of the `nfold` subsamples, a single subsample is retained as the validation data for testing the model, |
| 57 |
#' and the remaining `nfold - 1` subsamples are used as training data. |
| 58 |
#' |
| 59 |
#' The cross-validation process is then repeated `nrounds` times, with each of the |
| 60 |
#' `nfold` subsamples used exactly once as the validation data. |
| 61 |
#' |
| 62 |
#' All observations are used for both training and validation. |
| 63 |
#' |
| 64 |
#' Adapted from \url{https://en.wikipedia.org/wiki/Cross-validation_\%28statistics\%29} |
| 65 |
#' |
| 66 |
#' @return |
| 67 |
#' An object of class 'xgb.cv.synchronous' with the following elements: |
| 68 |
#' - `call`: Function call. |
| 69 |
#' - `params`: Parameters that were passed to the xgboost library. Note that it does not |
| 70 |
#' capture parameters changed by the [xgb.cb.reset.parameters()] callback. |
| 71 |
#' - `evaluation_log`: Evaluation history stored as a `data.table` with the |
| 72 |
#' first column corresponding to iteration number and the rest corresponding to the |
| 73 |
#' CV-based evaluation means and standard deviations for the training and test CV-sets. |
| 74 |
#' It is created by the [xgb.cb.evaluation.log()] callback. |
| 75 |
#' - `niter`: Number of boosting iterations. |
| 76 |
#' - `nfeatures`: Number of features in training data. |
| 77 |
#' - `folds`: The list of CV folds' indices - either those passed through the `folds` |
| 78 |
#' parameter or randomly generated. |
| 79 |
#' |
| 80 |
#' Plus other potential elements that are the result of callbacks, such as a list `cv_predict` with |
| 81 |
#' a sub-element `pred` when passing `prediction = TRUE`, which is added by the [xgb.cb.cv.predict()] |
| 82 |
#' callback (note that one can also pass it manually under `callbacks` with different settings, |
| 83 |
#' such as saving also the models created during cross validation); or a list `early_stop` which |
| 84 |
#' will contain elements such as `best_iteration` when using the early stopping callback ([xgb.cb.early.stop()]). |
| 85 |
#' |
| 86 |
#' @examples |
| 87 |
#' data(agaricus.train, package = "xgboost") |
| 88 |
#' |
| 89 |
#' dtrain <- with(agaricus.train, xgb.DMatrix(data, label = label, nthread = 2)) |
| 90 |
#' |
| 91 |
#' cv <- xgb.cv( |
| 92 |
#' data = dtrain, |
| 93 |
#' nrounds = 20, |
| 94 |
#' early_stopping_rounds = 1, |
| 95 |
#' params = xgb.params( |
| 96 |
#' nthread = 2, |
| 97 |
#' max_depth = 3, |
| 98 |
#' objective = "binary:logistic" |
| 99 |
#' ), |
| 100 |
#' nfold = 5, |
| 101 |
#' metrics = list("rmse","auc"), |
| 102 |
#' prediction = TRUE |
| 103 |
#' ) |
| 104 |
#' print(cv) |
| 105 |
#' print(cv, verbose = TRUE) |
| 106 |
#' |
| 107 |
#' # Callbacks might add additional attributes, separated by the name of the callback |
| 108 |
#' cv$early_stop$best_iteration |
| 109 |
#' head(cv$cv_predict$pred) |
| 110 |
#' @export |
| 111 |
xgb.cv <- function(params = xgb.params(), data, nrounds, nfold, |
| 112 |
prediction = FALSE, showsd = TRUE, metrics = list(), |
| 113 |
objective = NULL, custom_metric = NULL, stratified = "auto", |
| 114 |
folds = NULL, train_folds = NULL, verbose = TRUE, print_every_n = 1L, |
| 115 |
early_stopping_rounds = NULL, maximize = NULL, callbacks = list(), ...) { |
| 116 |
check.deprecation(deprecated_cv_params, match.call(), ...) |
| 117 |
|
| 118 |
stopifnot(inherits(data, "xgb.DMatrix")) |
| 119 |
|
| 120 |
if (inherits(data, "xgb.DMatrix") && .Call(XGCheckNullPtr_R, data)) { |
| 121 |
stop("'data' is an invalid 'xgb.DMatrix' object. Must be constructed again.") |
| 122 |
} |
| 123 |
if (inherits(data, "xgb.QuantileDMatrix")) { |
| 124 |
stop("'xgb.QuantileDMatrix' is not supported as input to 'xgb.cv'.") |
| 125 |
} |
| 126 |
|
| 127 |
params <- check.booster.params(params) |
| 128 |
# TODO: should we deprecate the redundant 'metrics' parameter? |
| 129 |
for (m in metrics) |
| 130 |
params <- c(params, list("eval_metric" = m)) |
| 131 |
|
| 132 |
tmp <- check.custom.obj(params, objective) |
| 133 |
params <- tmp$params |
| 134 |
objective <- tmp$objective |
| 135 |
tmp <- check.custom.eval(params, custom_metric, maximize, early_stopping_rounds, callbacks) |
| 136 |
params <- tmp$params |
| 137 |
custom_metric <- tmp$custom_metric |
| 138 |
|
| 139 |
if (stratified == "auto") { |
| 140 |
if (is.character(params$objective)) { |
| 141 |
stratified <- ( |
| 142 |
(params$objective %in% .CLASSIFICATION_OBJECTIVES()) |
| 143 |
&& !(params$objective %in% .RANKING_OBJECTIVES()) |
| 144 |
) |
| 145 |
} else { |
| 146 |
stratified <- FALSE |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
# Check the labels and groups |
| 151 |
cv_label <- getinfo(data, "label") |
| 152 |
cv_group <- getinfo(data, "group") |
| 153 |
if (!is.null(train_folds) && NROW(cv_group)) { |
| 154 |
stop("'train_folds' is not supported for DMatrix object with 'group' field.") |
| 155 |
} |
| 156 |
|
| 157 |
# CV folds |
| 158 |
if (!is.null(folds)) { |
| 159 |
if (!is.list(folds) || length(folds) < 2) |
| 160 |
stop("'folds' must be a list with 2 or more elements that are vectors of indices for each CV-fold") |
| 161 |
nfold <- length(folds) |
| 162 |
} else { |
| 163 |
if (nfold <= 1) |
| 164 |
stop("'nfold' must be > 1") |
| 165 |
folds <- generate.cv.folds(nfold, nrow(data), stratified, cv_label, cv_group, params) |
| 166 |
} |
| 167 |
|
| 168 |
# Callbacks |
| 169 |
tmp <- .process.callbacks(callbacks, is_cv = TRUE) |
| 170 |
callbacks <- tmp$callbacks |
| 171 |
cb_names <- tmp$cb_names |
| 172 |
rm(tmp) |
| 173 |
|
| 174 |
# Early stopping callback |
| 175 |
if (!is.null(early_stopping_rounds) && !("early_stop" %in% cb_names)) { |
| 176 |
callbacks <- add.callback( |
| 177 |
callbacks, |
| 178 |
xgb.cb.early.stop( |
| 179 |
early_stopping_rounds, |
| 180 |
maximize = maximize, |
| 181 |
verbose = verbose, |
| 182 |
save_best = FALSE |
| 183 |
), |
| 184 |
as_first_elt = TRUE |
| 185 |
) |
| 186 |
} |
| 187 |
# verbosity & evaluation printing callback: |
| 188 |
params <- c(params, list(silent = 1)) |
| 189 |
print_every_n <- max(as.integer(print_every_n), 1L) |
| 190 |
if (verbose && !("print_evaluation" %in% cb_names)) { |
| 191 |
callbacks <- add.callback(callbacks, xgb.cb.print.evaluation(print_every_n, showsd = showsd)) |
| 192 |
} |
| 193 |
# evaluation log callback: always is on in CV |
| 194 |
if (!("evaluation_log" %in% cb_names)) { |
| 195 |
callbacks <- add.callback(callbacks, xgb.cb.evaluation.log()) |
| 196 |
} |
| 197 |
# CV-predictions callback |
| 198 |
if (prediction && !("cv_predict" %in% cb_names)) { |
| 199 |
callbacks <- add.callback(callbacks, xgb.cb.cv.predict(save_models = FALSE)) |
| 200 |
} |
| 201 |
|
| 202 |
# create the booster-folds |
| 203 |
# train_folds |
| 204 |
dall <- data |
| 205 |
bst_folds <- lapply(seq_along(folds), function(k) { |
| 206 |
dtest <- xgb.slice.DMatrix(dall, folds[[k]], allow_groups = TRUE) |
| 207 |
# code originally contributed by @RolandASc on stackoverflow |
| 208 |
if (is.null(train_folds)) |
| 209 |
dtrain <- xgb.slice.DMatrix(dall, unlist(folds[-k]), allow_groups = TRUE) |
| 210 |
else |
| 211 |
dtrain <- xgb.slice.DMatrix(dall, train_folds[[k]], allow_groups = TRUE) |
| 212 |
if (!is.null(attributes(folds[[k]])$group_test)) { |
| 213 |
setinfo(dtest, "group", attributes(folds[[k]])$group_test) |
| 214 |
setinfo(dtrain, "group", attributes(folds[[k]])$group_train) |
| 215 |
} |
| 216 |
bst <- xgb.Booster( |
| 217 |
params = params, |
| 218 |
cachelist = list(dtrain, dtest), |
| 219 |
modelfile = NULL |
| 220 |
) |
| 221 |
bst <- bst$bst |
| 222 |
list(dtrain = dtrain, bst = bst, evals = list(train = dtrain, test = dtest), index = folds[[k]]) |
| 223 |
}) |
| 224 |
|
| 225 |
# extract parameters that can affect the relationship b/w #trees and #iterations |
| 226 |
num_class <- max(as.numeric(NVL(params[['num_class']], 1)), 1) # nolint |
| 227 |
|
| 228 |
# those are fixed for CV (no training continuation) |
| 229 |
begin_iteration <- 1 |
| 230 |
end_iteration <- nrounds |
| 231 |
|
| 232 |
.execute.cb.before.training( |
| 233 |
callbacks, |
| 234 |
bst_folds, |
| 235 |
dall, |
| 236 |
NULL, |
| 237 |
begin_iteration, |
| 238 |
end_iteration |
| 239 |
) |
| 240 |
|
| 241 |
# synchronous CV boosting: run CV folds' models within each iteration |
| 242 |
for (iteration in begin_iteration:end_iteration) { |
| 243 |
|
| 244 |
.execute.cb.before.iter( |
| 245 |
callbacks, |
| 246 |
bst_folds, |
| 247 |
dall, |
| 248 |
NULL, |
| 249 |
iteration |
| 250 |
) |
| 251 |
|
| 252 |
msg <- lapply(bst_folds, function(fd) { |
| 253 |
xgb.iter.update( |
| 254 |
bst = fd$bst, |
| 255 |
dtrain = fd$dtrain, |
| 256 |
iter = iteration - 1, |
| 257 |
objective = objective |
| 258 |
) |
| 259 |
xgb.iter.eval( |
| 260 |
bst = fd$bst, |
| 261 |
evals = fd$evals, |
| 262 |
iter = iteration - 1, |
| 263 |
custom_metric = custom_metric |
| 264 |
) |
| 265 |
}) |
| 266 |
msg <- simplify2array(msg) |
| 267 |
|
| 268 |
should_stop <- .execute.cb.after.iter( |
| 269 |
callbacks, |
| 270 |
bst_folds, |
| 271 |
dall, |
| 272 |
NULL, |
| 273 |
iteration, |
| 274 |
msg |
| 275 |
) |
| 276 |
|
| 277 |
if (should_stop) break |
| 278 |
} |
| 279 |
|
| 280 |
cb_outputs <- .execute.cb.after.training( |
| 281 |
callbacks, |
| 282 |
bst_folds, |
| 283 |
dall, |
| 284 |
NULL, |
| 285 |
iteration, |
| 286 |
msg |
| 287 |
) |
| 288 |
|
| 289 |
# Just in case if the model is referenced in callbacks. |
| 290 |
lapply(bst_folds, function(fd) { |
| 291 |
xgb.reset.Booster(fd$bst) |
| 292 |
}) |
| 293 |
|
| 294 |
# the CV result |
| 295 |
ret <- list( |
| 296 |
call = match.call(), |
| 297 |
params = params, |
| 298 |
niter = iteration, |
| 299 |
nfeatures = ncol(dall), |
| 300 |
folds = folds |
| 301 |
) |
| 302 |
ret <- c(ret, cb_outputs) |
| 303 |
|
| 304 |
class(ret) <- 'xgb.cv.synchronous' |
| 305 |
return(invisible(ret)) |
| 306 |
} |
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
#' Print xgb.cv result |
| 311 |
#' |
| 312 |
#' Prints formatted results of [xgb.cv()]. |
| 313 |
#' |
| 314 |
#' @param x An `xgb.cv.synchronous` object. |
| 315 |
#' @param verbose Whether to print detailed data. |
| 316 |
#' @param ... Passed to `data.table.print()`. |
| 317 |
#' |
| 318 |
#' @details |
| 319 |
#' When not verbose, it would only print the evaluation results, |
| 320 |
#' including the best iteration (when available). |
| 321 |
#' |
| 322 |
#' @examples |
| 323 |
#' data(agaricus.train, package = "xgboost") |
| 324 |
#' |
| 325 |
#' train <- agaricus.train |
| 326 |
#' cv <- xgb.cv( |
| 327 |
#' data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 328 |
#' nfold = 5, |
| 329 |
#' nrounds = 2, |
| 330 |
#' params = xgb.params( |
| 331 |
#' max_depth = 2, |
| 332 |
#' nthread = 2, |
| 333 |
#' objective = "binary:logistic" |
| 334 |
#' ) |
| 335 |
#' ) |
| 336 |
#' print(cv) |
| 337 |
#' print(cv, verbose = TRUE) |
| 338 |
#' |
| 339 |
#' @rdname print.xgb.cv |
| 340 |
#' @method print xgb.cv.synchronous |
| 341 |
#' @export |
| 342 |
print.xgb.cv.synchronous <- function(x, verbose = FALSE, ...) { |
| 343 |
cat('##### xgb.cv ', length(x$folds), '-folds\n', sep = '') |
| 344 |
|
| 345 |
if (verbose) { |
| 346 |
if (!is.null(x$call)) { |
| 347 |
cat('call:\n ') |
| 348 |
print(x$call) |
| 349 |
} |
| 350 |
if (!is.null(x$params)) { |
| 351 |
cat('params (as set within xgb.cv):\n') |
| 352 |
cat(' ', |
| 353 |
paste(names(x$params), |
| 354 |
paste0('"', unlist(x$params), '"'), |
| 355 |
sep = ' = ', collapse = ', '), '\n', sep = '') |
| 356 |
} |
| 357 |
|
| 358 |
for (n in c('niter', 'best_iteration')) { |
| 359 |
if (is.null(x$early_stop[[n]])) |
| 360 |
next |
| 361 |
cat(n, ': ', x$early_stop[[n]], '\n', sep = '') |
| 362 |
} |
| 363 |
|
| 364 |
if (!is.null(x$cv_predict$pred)) { |
| 365 |
cat('pred:\n') |
| 366 |
str(x$cv_predict$pred) |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
if (verbose) |
| 371 |
cat('evaluation_log:\n') |
| 372 |
print(x$evaluation_log, row.names = FALSE, ...) |
| 373 |
|
| 374 |
if (!is.null(x$early_stop$best_iteration)) { |
| 375 |
cat('Best iteration:\n') |
| 376 |
print(x$evaluation_log[x$early_stop$best_iteration], row.names = FALSE, ...) |
| 377 |
} |
| 378 |
invisible(x) |
| 379 |
} |