Debian Codegraph @

R/callbacks.R

raw
1 .reserved_cb_names <- c("names", "class", "call", "params", "niter", "nfeatures", "folds")
2
3 #' XGBoost Callback Constructor
4 #'
5 #' Constructor for defining the structure of callback functions that can be executed
6 #' at different stages of model training (before / after training, before / after each boosting
7 #' iteration).
8 #'
9 #' @details
10 #' Arguments that will be passed to the supplied functions are as follows:
11 #' - env The same environment that is passed under argument `env`.
12 #'
13 #' It may be modified by the functions in order to e.g. keep tracking of what happens
14 #' across iterations or similar.
15 #'
16 #' This environment is only used by the functions supplied to the callback, and will
17 #' not be kept after the model fitting function terminates (see parameter `f_after_training`).
18 #'
19 #' - model The booster object when using [xgb.train()], or the folds when using [xgb.cv()].
20 #'
21 #' For [xgb.cv()], folds are a list with a structure as follows:
22 #' - `dtrain`: The training data for the fold (as an `xgb.DMatrix` object).
23 #' - `bst`: Rhe `xgb.Booster` object for the fold.
24 #' - `evals`: A list containing two DMatrices, with names `train` and `test`
25 #' (`test` is the held-out data for the fold).
26 #' - `index`: The indices of the hold-out data for that fold (base-1 indexing),
27 #' from which the `test` entry in `evals` was obtained.
28 #'
29 #' This object should **not** be in-place modified in ways that conflict with the
30 #' training (e.g. resetting the parameters for a training update in a way that resets
31 #' the number of rounds to zero in order to overwrite rounds).
32 #'
33 #' Note that any R attributes that are assigned to the booster during the callback functions,
34 #' will not be kept thereafter as the booster object variable is not re-assigned during
35 #' training. It is however possible to set C-level attributes of the booster through
36 #' [xgb.attr()] or [xgb.attributes()], which should remain available for the rest
37 #' of the iterations and after the training is done.
38 #'
39 #' For keeping variables across iterations, it's recommended to use `env` instead.
40 #' - data The data to which the model is being fit, as an `xgb.DMatrix` object.
41 #'
42 #' Note that, for [xgb.cv()], this will be the full data, while data for the specific
43 #' folds can be found in the `model` object.
44 #' - evals The evaluation data, as passed under argument `evals` to [xgb.train()].
45 #'
46 #' For [xgb.cv()], this will always be `NULL`.
47 #' - begin_iteration Index of the first boosting iteration that will be executed (base-1 indexing).
48 #'
49 #' This will typically be '1', but when using training continuation, depending on the
50 #' parameters for updates, boosting rounds will be continued from where the previous
51 #' model ended, in which case this will be larger than 1.
52 #'
53 #' - end_iteration Index of the last boostign iteration that will be executed
54 #' (base-1 indexing, inclusive of this end).
55 #'
56 #' It should match with argument `nrounds` passed to [xgb.train()] or [xgb.cv()].
57 #'
58 #' Note that boosting might be interrupted before reaching this last iteration, for
59 #' example by using the early stopping callback [xgb.cb.early.stop()].
60 #' - iteration Index of the iteration number that is being executed (first iteration
61 #' will be the same as parameter `begin_iteration`, then next one will add +1, and so on).
62 #'
63 #' - iter_feval Evaluation metrics for `evals` that were supplied, either
64 #' determined by the objective, or by parameter `custom_metric`.
65 #'
66 #' For [xgb.train()], this will be a named vector with one entry per element in
67 #' `evals`, where the names are determined as 'evals name' + '-' + 'metric name' - for
68 #' example, if `evals` contains an entry named "tr" and the metric is "rmse",
69 #' this will be a one-element vector with name "tr-rmse".
70 #'
71 #' For [xgb.cv()], this will be a 2d matrix with dimensions `[length(evals), nfolds]`,
72 #' where the row names will follow the same naming logic as the one-dimensional vector
73 #' that is passed in [xgb.train()].
74 #'
75 #' Note that, internally, the built-in callbacks such as [xgb.cb.print.evaluation] summarize
76 #' this table by calculating the row-wise means and standard deviations.
77 #'
78 #' - final_feval The evaluation results after the last boosting round is executed
79 #' (same format as `iter_feval`, and will be the exact same input as passed under
80 #' `iter_feval` to the last round that is executed during model fitting).
81 #'
82 #' - prev_cb_res Result from a previous run of a callback sharing the same name
83 #' (as given by parameter `cb_name`) when conducting training continuation, if there
84 #' was any in the booster R attributes.
85 #'
86 #' Sometimes, one might want to append the new results to the previous one, and this will
87 #' be done automatically by the built-in callbacks such as [xgb.cb.evaluation.log],
88 #' which will append the new rows to the previous table.
89 #'
90 #' If no such previous callback result is available (which it never will when fitting
91 #' a model from start instead of updating an existing model), this will be `NULL`.
92 #'
93 #' For [xgb.cv()], which doesn't support training continuation, this will always be `NULL`.
94 #'
95 #' The following names (`cb_name` values) are reserved for internal callbacks:
96 #' - print_evaluation
97 #' - evaluation_log
98 #' - reset_parameters
99 #' - early_stop
100 #' - save_model
101 #' - cv_predict
102 #' - gblinear_history
103 #'
104 #' The following names are reserved for other non-callback attributes:
105 #' - names
106 #' - class
107 #' - call
108 #' - params
109 #' - niter
110 #' - nfeatures
111 #' - folds
112 #'
113 #' When using the built-in early stopping callback ([xgb.cb.early.stop]), said callback
114 #' will always be executed before the others, as it sets some booster C-level attributes
115 #' that other callbacks might also use. Otherwise, the order of execution will match with
116 #' the order in which the callbacks are passed to the model fitting function.
117 #'
118 #' @param cb_name Name for the callback.
119 #'
120 #' If the callback produces some non-NULL result (from executing the function passed under
121 #' `f_after_training`), that result will be added as an R attribute to the resulting booster
122 #' (or as a named element in the result of CV), with the attribute name specified here.
123 #'
124 #' Names of callbacks must be unique - i.e. there cannot be two callbacks with the same name.
125 #' @param env An environment object that will be passed to the different functions in the callback.
126 #' Note that this environment will not be shared with other callbacks.
127 #' @param f_before_training A function that will be executed before the training has started.
128 #'
129 #' If passing `NULL` for this or for the other function inputs, then no function will be executed.
130 #'
131 #' If passing a function, it will be called with parameters supplied as non-named arguments
132 #' matching the function signatures that are shown in the default value for each function argument.
133 #' @param f_before_iter A function that will be executed before each boosting round.
134 #'
135 #' This function can signal whether the training should be finalized or not, by outputting
136 #' a value that evaluates to `TRUE` - i.e. if the output from the function provided here at
137 #' a given round is `TRUE`, then training will be stopped before the current iteration happens.
138 #'
139 #' Return values of `NULL` will be interpreted as `FALSE`.
140 #' @param f_after_iter A function that will be executed after each boosting round.
141 #'
142 #' This function can signal whether the training should be finalized or not, by outputting
143 #' a value that evaluates to `TRUE` - i.e. if the output from the function provided here at
144 #' a given round is `TRUE`, then training will be stopped at that round.
145 #'
146 #' Return values of `NULL` will be interpreted as `FALSE`.
147 #' @param f_after_training A function that will be executed after training is finished.
148 #'
149 #' This function can optionally output something non-NULL, which will become part of the R
150 #' attributes of the booster (assuming one passes `keep_extra_attributes=TRUE` to [xgb.train()])
151 #' under the name supplied for parameter `cb_name` imn the case of [xgb.train()]; or a part
152 #' of the named elements in the result of [xgb.cv()].
153 #' @return An `xgb.Callback` object, which can be passed to [xgb.train()] or [xgb.cv()].
154 #'
155 #' @seealso Built-in callbacks:
156 #' - [xgb.cb.print.evaluation]
157 #' - [xgb.cb.evaluation.log]
158 #' - [xgb.cb.reset.parameters]
159 #' - [xgb.cb.early.stop]
160 #' - [xgb.cb.save.model]
161 #' - [xgb.cb.cv.predict]
162 #' - [xgb.cb.gblinear.history]
163 #
164 #' @examples
165 #' # Example constructing a custom callback that calculates
166 #' # squared error on the training data (no separate test set),
167 #' # and outputs the per-iteration results.
168 #' ssq_callback <- xgb.Callback(
169 #' cb_name = "ssq",
170 #' f_before_training = function(env, model, data, evals,
171 #' begin_iteration, end_iteration) {
172 #' # A vector to keep track of a number at each iteration
173 #' env$logs <- rep(NA_real_, end_iteration - begin_iteration + 1)
174 #' },
175 #' f_after_iter = function(env, model, data, evals, iteration, iter_feval) {
176 #' # This calculates the sum of squared errors on the training data.
177 #' # Note that this can be better done by passing an 'evals' entry,
178 #' # but this demonstrates a way in which callbacks can be structured.
179 #' pred <- predict(model, data)
180 #' err <- pred - getinfo(data, "label")
181 #' sq_err <- sum(err^2)
182 #' env$logs[iteration] <- sq_err
183 #' cat(
184 #' sprintf(
185 #' "Squared error at iteration %d: %.2f\n",
186 #' iteration, sq_err
187 #' )
188 #' )
189 #'
190 #' # A return value of 'TRUE' here would signal to finalize the training
191 #' return(FALSE)
192 #' },
193 #' f_after_training = function(env, model, data, evals, iteration,
194 #' final_feval, prev_cb_res) {
195 #' return(env$logs)
196 #' }
197 #' )
198 #'
199 #' data(mtcars)
200 #'
201 #' y <- mtcars$mpg
202 #' x <- as.matrix(mtcars[, -1])
203 #'
204 #' dm <- xgb.DMatrix(x, label = y, nthread = 1)
205 #' model <- xgb.train(
206 #' data = dm,
207 #' params = xgb.params(objective = "reg:squarederror", nthread = 1),
208 #' nrounds = 5,
209 #' callbacks = list(ssq_callback)
210 #' )
211 #'
212 #' # Result from 'f_after_iter' will be available as an attribute
213 #' attributes(model)$ssq
214 #' @export
215 xgb.Callback <- function(
216 cb_name = "custom_callback",
217 env = new.env(),
218 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration) NULL,
219 f_before_iter = function(env, model, data, evals, iteration) NULL,
220 f_after_iter = function(env, model, data, evals, iteration, iter_feval) NULL,
221 f_after_training = function(env, model, data, evals, iteration, final_feval, prev_cb_res) NULL
222 ) {
223 stopifnot(is.null(f_before_training) || is.function(f_before_training))
224 stopifnot(is.null(f_before_iter) || is.function(f_before_iter))
225 stopifnot(is.null(f_after_iter) || is.function(f_after_iter))
226 stopifnot(is.null(f_after_training) || is.function(f_after_training))
227 stopifnot(is.character(cb_name) && length(cb_name) == 1)
228
229 if (cb_name %in% .reserved_cb_names) {
230 stop("Cannot use reserved callback name '", cb_name, "'.")
231 }
232
233 out <- list(
234 cb_name = cb_name,
235 env = env,
236 f_before_training = f_before_training,
237 f_before_iter = f_before_iter,
238 f_after_iter = f_after_iter,
239 f_after_training = f_after_training
240 )
241 class(out) <- "xgb.Callback"
242 return(out)
243 }
244
245 .execute.cb.before.training <- function(
246 callbacks,
247 model,
248 data,
249 evals,
250 begin_iteration,
251 end_iteration
252 ) {
253 for (callback in callbacks) {
254 if (!is.null(callback$f_before_training)) {
255 callback$f_before_training(
256 callback$env,
257 model,
258 data,
259 evals,
260 begin_iteration,
261 end_iteration
262 )
263 }
264 }
265 }
266
267 .execute.cb.before.iter <- function(
268 callbacks,
269 model,
270 data,
271 evals,
272 iteration
273 ) {
274 if (!length(callbacks)) {
275 return(FALSE)
276 }
277 out <- sapply(callbacks, function(cb) {
278 if (is.null(cb$f_before_iter)) {
279 return(FALSE)
280 }
281 should_stop <- cb$f_before_iter(
282 cb$env,
283 model,
284 data,
285 evals,
286 iteration
287 )
288 if (!NROW(should_stop)) {
289 should_stop <- FALSE
290 } else if (NROW(should_stop) > 1) {
291 should_stop <- head(as.logical(should_stop), 1)
292 }
293 return(should_stop)
294 })
295 return(any(out))
296 }
297
298 .execute.cb.after.iter <- function(
299 callbacks,
300 model,
301 data,
302 evals,
303 iteration,
304 iter_feval
305 ) {
306 if (!length(callbacks)) {
307 return(FALSE)
308 }
309 out <- sapply(callbacks, function(cb) {
310 if (is.null(cb$f_after_iter)) {
311 return(FALSE)
312 }
313 should_stop <- cb$f_after_iter(
314 cb$env,
315 model,
316 data,
317 evals,
318 iteration,
319 iter_feval
320 )
321 if (!NROW(should_stop)) {
322 should_stop <- FALSE
323 } else if (NROW(should_stop) > 1) {
324 should_stop <- head(as.logical(should_stop), 1)
325 }
326 return(should_stop)
327 })
328 return(any(out))
329 }
330
331 .execute.cb.after.training <- function(
332 callbacks,
333 model,
334 data,
335 evals,
336 iteration,
337 final_feval,
338 prev_cb_res
339 ) {
340 if (!length(callbacks)) {
341 return(NULL)
342 }
343 old_cb_res <- attributes(model)
344 out <- lapply(callbacks, function(cb) {
345 if (is.null(cb$f_after_training)) {
346 return(NULL)
347 } else {
348 return(
349 cb$f_after_training(
350 cb$env,
351 model,
352 data,
353 evals,
354 iteration,
355 final_feval,
356 getElement(old_cb_res, cb$cb_name)
357 )
358 )
359 }
360 })
361 names(out) <- sapply(callbacks, function(cb) cb$cb_name)
362 if (NROW(out)) {
363 out <- out[!sapply(out, is.null)]
364 }
365 return(out)
366 }
367
368 .summarize.feval <- function(iter_feval, showsd) {
369 if (NCOL(iter_feval) > 1L && showsd) {
370 stdev <- apply(iter_feval, 1, sd)
371 } else {
372 stdev <- NULL
373 }
374 if (NCOL(iter_feval) > 1L) {
375 iter_feval <- rowMeans(iter_feval)
376 }
377 return(list(feval = iter_feval, stdev = stdev))
378 }
379
380 .print.evaluation <- function(iter_feval, showsd, iteration) {
381 tmp <- .summarize.feval(iter_feval, showsd)
382 msg <- .format_eval_string(iteration, tmp$feval, tmp$stdev)
383 cat(msg, '\n')
384 }
385
386 # Format the evaluation metric string
387 .format_eval_string <- function(iter, eval_res, eval_err = NULL) {
388 if (length(eval_res) == 0)
389 stop('no evaluation results')
390 enames <- names(eval_res)
391 if (is.null(enames))
392 stop('evaluation results must have names')
393 iter <- sprintf('[%d]\t', iter)
394 if (!is.null(eval_err)) {
395 if (length(eval_res) != length(eval_err))
396 stop('eval_res & eval_err lengths mismatch')
397 # Note: UTF-8 code for plus/minus sign is U+00B1
398 res <- paste0(sprintf("%s:%f\U00B1%f", enames, eval_res, eval_err), collapse = '\t')
399 } else {
400 res <- paste0(sprintf("%s:%f", enames, eval_res), collapse = '\t')
401 }
402 return(paste0(iter, res))
403 }
404
405 #' Callback for printing the result of evaluation
406 #'
407 #' @description
408 #' The callback function prints the result of evaluation at every `period` iterations.
409 #' The initial and the last iteration's evaluations are always printed.
410 #'
411 #' Does not leave any attribute in the booster (see [xgb.cb.evaluation.log] for that).
412 #'
413 #' @param period Results would be printed every number of periods.
414 #' @param showsd Whether standard deviations should be printed (when available).
415 #' @return An `xgb.Callback` object, which can be passed to [xgb.train()] or [xgb.cv()].
416 #' @seealso [xgb.Callback]
417 #' @export
418 xgb.cb.print.evaluation <- function(period = 1, showsd = TRUE) {
419 if (length(period) != 1 || period != floor(period) || period < 1) {
420 stop("'period' must be a positive integer.")
421 }
422
423 xgb.Callback(
424 cb_name = "print_evaluation",
425 env = as.environment(list(period = period, showsd = showsd, is_first_call = TRUE)),
426 f_before_training = NULL,
427 f_before_iter = NULL,
428 f_after_iter = function(env, model, data, evals, iteration, iter_feval) {
429 if (is.null(iter_feval)) {
430 return(FALSE)
431 }
432 if (env$is_first_call || (iteration - 1) %% env$period == 0) {
433 .print.evaluation(iter_feval, env$showsd, iteration)
434 env$last_printed_iter <- iteration
435 }
436 env$is_first_call <- FALSE
437 return(FALSE)
438 },
439 f_after_training = function(env, model, data, evals, iteration, final_feval, prev_cb_res) {
440 if (is.null(final_feval)) {
441 return(NULL)
442 }
443 if (is.null(env$last_printed_iter) || iteration > env$last_printed_iter) {
444 .print.evaluation(final_feval, env$showsd, iteration)
445 }
446 }
447 )
448 }
449
450 #' Callback for logging the evaluation history
451 #'
452 #' @details This callback creates a table with per-iteration evaluation metrics (see parameters
453 #' `evals` and `custom_metric` in [xgb.train()]).
454 #'
455 #' Note: in the column names of the final data.table, the dash '-' character is replaced with
456 #' the underscore '_' in order to make the column names more like regular R identifiers.
457 #'
458 #' @return An `xgb.Callback` object, which can be passed to [xgb.train()] or [xgb.cv()].
459 #' @seealso [xgb.cb.print.evaluation]
460 #' @export
461 xgb.cb.evaluation.log <- function() {
462 xgb.Callback(
463 cb_name = "evaluation_log",
464 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration) {
465 env$evaluation_log <- vector("list", end_iteration - begin_iteration + 1)
466 env$next_log <- 1
467 },
468 f_before_iter = NULL,
469 f_after_iter = function(env, model, data, evals, iteration, iter_feval) {
470 tmp <- .summarize.feval(iter_feval, TRUE)
471 env$evaluation_log[[env$next_log]] <- list(iter = iteration, metrics = tmp$feval, sds = tmp$stdev)
472 env$next_log <- env$next_log + 1
473 return(FALSE)
474 },
475 f_after_training = function(env, model, data, evals, iteration, final_feval, prev_cb_res) {
476 if (!NROW(env$evaluation_log)) {
477 return(prev_cb_res)
478 }
479 # in case of early stopping
480 if (env$next_log <= length(env$evaluation_log)) {
481 env$evaluation_log <- head(env$evaluation_log, env$next_log - 1)
482 }
483
484 iters <- data.frame(iter = sapply(env$evaluation_log, function(x) x$iter))
485 metrics <- do.call(rbind, lapply(env$evaluation_log, function(x) x$metrics))
486 mnames <- gsub("-", "_", names(env$evaluation_log[[1]]$metrics), fixed = TRUE)
487 colnames(metrics) <- mnames
488 has_sds <- !is.null(env$evaluation_log[[1]]$sds)
489 if (has_sds) {
490 sds <- do.call(rbind, lapply(env$evaluation_log, function(x) x$sds))
491 colnames(sds) <- mnames
492 metrics <- lapply(
493 mnames,
494 function(metric) {
495 out <- cbind(metrics[, metric], sds[, metric])
496 colnames(out) <- paste0(metric, c("_mean", "_std"))
497 return(out)
498 }
499 )
500 metrics <- do.call(cbind, metrics)
501 }
502 evaluation_log <- cbind(iters, metrics)
503
504 if (!is.null(prev_cb_res)) {
505 if (!is.data.table(prev_cb_res)) {
506 prev_cb_res <- data.table::as.data.table(prev_cb_res)
507 }
508 prev_take <- prev_cb_res[prev_cb_res$iter < min(evaluation_log$iter)]
509 if (nrow(prev_take)) {
510 evaluation_log <- rbind(prev_cb_res, evaluation_log)
511 }
512 }
513 evaluation_log <- data.table::as.data.table(evaluation_log)
514 return(evaluation_log)
515 }
516 )
517 }
518
519 #' Callback for resetting booster parameters at each iteration
520 #'
521 #' @details
522 #' Note that when training is resumed from some previous model, and a function is used to
523 #' reset a parameter value, the `nrounds` argument in this function would be the
524 #' the number of boosting rounds in the current training.
525 #'
526 #' Does not leave any attribute in the booster.
527 #'
528 #' @param new_params List of parameters needed to be reset.
529 #' Each element's value must be either a vector of values of length `nrounds`
530 #' to be set at each iteration,
531 #' or a function of two parameters `learning_rates(iteration, nrounds)`
532 #' which returns a new parameter value by using the current iteration number
533 #' and the total number of boosting rounds.
534 #' @return An `xgb.Callback` object, which can be passed to [xgb.train()] or [xgb.cv()].
535 #' @export
536 xgb.cb.reset.parameters <- function(new_params) {
537 stopifnot(is.list(new_params))
538 pnames <- gsub(".", "_", names(new_params), fixed = TRUE)
539 not_allowed <- pnames %in%
540 c('num_class', 'num_output_group', 'size_leaf_vector', 'updater_seq')
541 if (any(not_allowed))
542 stop('Parameters ', paste(pnames[not_allowed]), " cannot be changed during boosting.")
543
544 xgb.Callback(
545 cb_name = "reset_parameters",
546 env = as.environment(list(new_params = new_params)),
547 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration) {
548 env$end_iteration <- end_iteration
549
550 pnames <- gsub(".", "_", names(env$new_params), fixed = TRUE)
551 for (n in pnames) {
552 p <- env$new_params[[n]]
553 if (is.function(p)) {
554 if (length(formals(p)) != 2)
555 stop("Parameter '", n, "' is a function but not of two arguments")
556 } else if (is.numeric(p) || is.character(p)) {
557 if (length(p) != env$end_iteration)
558 stop("Length of '", n, "' has to be equal to 'nrounds'")
559 } else {
560 stop("Parameter '", n, "' is not a function or a vector")
561 }
562 }
563 },
564 f_before_iter = function(env, model, data, evals, iteration) {
565 params <- lapply(env$new_params, function(p) {
566 if (is.function(p)) {
567 return(p(iteration, env$end_iteration))
568 } else {
569 return(p[iteration])
570 }
571 })
572
573 if (inherits(model, "xgb.Booster")) {
574 xgb.model.parameters(model) <- params
575 } else {
576 for (fd in model) {
577 xgb.model.parameters(fd$bst) <- params
578 }
579 }
580 return(FALSE)
581 },
582 f_after_iter = NULL,
583 f_after_training = NULL
584 )
585 }
586
587 #' Callback to activate early stopping
588 #'
589 #' @description
590 #' This callback function determines the condition for early stopping.
591 #'
592 #' The following attributes are assigned to the booster's object:
593 #' - `best_score` the evaluation score at the best iteration
594 #' - `best_iteration` at which boosting iteration the best score has occurred
595 #' (0-based index for interoperability of binary models)
596 #'
597 #' The same values are also stored as R attributes as a result of the callback, plus an additional
598 #' attribute `stopped_by_max_rounds` which indicates whether an early stopping by the `stopping_rounds`
599 #' condition occurred. Note that the `best_iteration` that is stored under R attributes will follow
600 #' base-1 indexing, so it will be larger by '1' than the C-level 'best_iteration' that is accessed
601 #' through [xgb.attr()] or [xgb.attributes()].
602 #'
603 #' At least one dataset is required in `evals` for early stopping to work.
604 #'
605 #' @param stopping_rounds The number of rounds with no improvement in
606 #' the evaluation metric in order to stop the training.
607 #' @param maximize Whether to maximize the evaluation metric.
608 #' @param metric_name The name of an evaluation column to use as a criteria for early
609 #' stopping. If not set, the last column would be used.
610 #' Let's say the test data in `evals` was labelled as `dtest`,
611 #' and one wants to use the AUC in test data for early stopping regardless of where
612 #' it is in the `evals`, then one of the following would need to be set:
613 #' `metric_name = 'dtest-auc'` or `metric_name = 'dtest_auc'`.
614 #' All dash '-' characters in metric names are considered equivalent to '_'.
615 #' @param verbose Whether to print the early stopping information.
616 #'
617 #' @param save_best Whether training should return the best model or the last model. If
618 #' set to `TRUE`, it will only keep the boosting rounds up to the detected best
619 #' iteration, discarding the ones that come after. This parameter is not supported by
620 #' the `xgb.cv` function and the `gblinear` booster yet.
621 #' @return An `xgb.Callback` object, which can be passed to [xgb.train()] or [xgb.cv()].
622 #' @export
623 xgb.cb.early.stop <- function(
624 stopping_rounds,
625 maximize = FALSE,
626 metric_name = NULL,
627 verbose = TRUE,
628 save_best = FALSE
629 ) {
630 if (!is.null(metric_name)) {
631 stopifnot(is.character(metric_name))
632 stopifnot(length(metric_name) == 1L)
633 }
634
635 xgb.Callback(
636 cb_name = "early_stop",
637 env = as.environment(
638 list(
639 checked_evnames = FALSE,
640 stopping_rounds = stopping_rounds,
641 maximize = maximize,
642 metric_name = metric_name,
643 verbose = verbose,
644 save_best = save_best,
645 stopped_by_max_rounds = FALSE
646 )
647 ),
648 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration) {
649 if (inherits(model, "xgb.Booster") && !length(evals)) {
650 stop("For early stopping, 'evals' must have at least one element")
651 }
652 if (!inherits(model, "xgb.Booster") && save_best) {
653 stop("'save_best' must be set to FALSE when using early stopping in 'xgb.cv'.")
654 }
655 env$begin_iteration <- begin_iteration
656 return(NULL)
657 },
658 f_before_iter = function(env, model, data, evals, iteration) NULL,
659 f_after_iter = function(env, model, data, evals, iteration, iter_feval) {
660 sds <- NULL
661 if (NCOL(iter_feval) > 1) {
662 tmp <- .summarize.feval(iter_feval, TRUE)
663 iter_feval <- tmp$feval
664 sds <- tmp$stdev
665 }
666
667 if (!env$checked_evnames) {
668
669 eval_names <- gsub('-', '_', names(iter_feval), fixed = TRUE)
670 if (!is.null(env$metric_name)) {
671 env$metric_idx <- which(gsub('-', '_', env$metric_name, fixed = TRUE) == eval_names)
672 if (length(env$metric_idx) == 0)
673 stop("'metric_name' for early stopping is not one of the following:\n",
674 paste(eval_names, collapse = ' '), '\n')
675 }
676
677 if (is.null(env$metric_name)) {
678 if (NROW(iter_feval) == 1) {
679 env$metric_idx <- 1L
680 } else {
681 env$metric_idx <- length(eval_names)
682 if (env$verbose)
683 cat('Multiple eval metrics are present. Will use ',
684 eval_names[env$metric_idx], ' for early stopping.\n', sep = '')
685 }
686 }
687
688 env$metric_name <- eval_names[env$metric_idx]
689
690 # maximize is usually NULL when not set in xgb.train and built-in metrics
691 if (is.null(env$maximize))
692 env$maximize <- grepl('(_auc|_aupr|_map|_ndcg|_pre)', env$metric_name)
693
694 if (env$verbose)
695 cat("Will train until ", env$metric_name, " hasn't improved in ",
696 env$stopping_rounds, " rounds.\n\n", sep = '')
697
698 env$best_iteration <- env$begin_iteration
699 if (env$maximize) {
700 env$best_score <- -Inf
701 } else {
702 env$best_score <- Inf
703 }
704
705 if (inherits(model, "xgb.Booster")) {
706 best_score <- xgb.attr(model, 'best_score')
707 if (NROW(best_score)) env$best_score <- as.numeric(best_score)
708 best_iteration <- xgb.attr(model, 'best_iteration')
709 if (NROW(best_iteration)) env$best_iteration <- as.numeric(best_iteration) + 1
710 }
711
712 env$checked_evnames <- TRUE
713 }
714
715 score <- iter_feval[env$metric_idx]
716 if ((env$maximize && score > env$best_score) ||
717 (!env$maximize && score < env$best_score)) {
718
719 env$best_score <- score
720 env$best_iteration <- iteration
721 # save the property to attributes, so they will occur in checkpoint
722 if (inherits(model, "xgb.Booster")) {
723 xgb.attributes(model) <- list(
724 best_iteration = env$best_iteration - 1, # convert to 0-based index
725 best_score = env$best_score
726 )
727 }
728 } else if (iteration - env$best_iteration >= env$stopping_rounds) {
729 if (env$verbose) {
730 best_msg <- .format_eval_string(iteration, iter_feval, sds)
731 cat("Stopping. Best iteration:\n", best_msg, "\n\n", sep = '')
732 }
733 env$stopped_by_max_rounds <- TRUE
734 return(TRUE)
735 }
736 return(FALSE)
737 },
738 f_after_training = function(env, model, data, evals, iteration, final_feval, prev_cb_res) {
739 if (inherits(model, "xgb.Booster") && env$save_best && env$best_iteration < iteration) {
740 # Note: it loses the attributes after being sliced,
741 # so they have to be re-assigned afterwards.
742 prev_attr <- xgb.attributes(model)
743 if (NROW(prev_attr)) {
744 suppressWarnings({
745 prev_attr <- within(prev_attr, rm("best_score", "best_iteration"))
746 })
747 }
748 .Call(XGBoosterSliceAndReplace_R, xgb.get.handle(model), 0L, env$best_iteration, 1L)
749 if (NROW(prev_attr)) {
750 xgb.attributes(model) <- prev_attr
751 }
752 }
753 attrs_set <- list(best_iteration = env$best_iteration - 1, best_score = env$best_score)
754 if (inherits(model, "xgb.Booster")) {
755 xgb.attributes(model) <- attrs_set
756 } else {
757 for (fd in model) {
758 xgb.attributes(fd$bst) <- attrs_set # to use in the cv.predict callback
759 }
760 }
761 return(
762 list(
763 best_iteration = env$best_iteration,
764 best_score = env$best_score,
765 stopped_by_max_rounds = env$stopped_by_max_rounds
766 )
767 )
768 }
769 )
770 }
771
772 .save.model.w.formatted.name <- function(model, save_name, iteration) {
773 # Note: this throws a warning if the name doesn't have anything to format through 'sprintf'
774 suppressWarnings({
775 save_name <- sprintf(save_name, iteration)
776 })
777 xgb.save(model, save_name)
778 }
779
780 #' Callback for saving a model file
781 #'
782 #' @description
783 #' This callback function allows to save an xgb-model file, either periodically
784 #' after each `save_period`'s or at the end.
785 #'
786 #' Does not leave any attribute in the booster.
787 #'
788 #' @param save_period Save the model to disk after every `save_period` iterations;
789 #' 0 means save the model at the end.
790 #' @param save_name The name or path for the saved model file.
791 #' It can contain a [sprintf()] formatting specifier to include the integer
792 #' iteration number in the file name. E.g., with `save_name = 'xgboost_%04d.model'`,
793 #' the file saved at iteration 50 would be named "xgboost_0050.model".
794 #' @return An `xgb.Callback` object, which can be passed to [xgb.train()],
795 #' but **not** to [xgb.cv()].
796 #' @export
797 xgb.cb.save.model <- function(save_period = 0, save_name = "xgboost.ubj") {
798 if (save_period < 0) {
799 stop("'save_period' cannot be negative")
800 }
801 if (!is.character(save_name) || length(save_name) != 1L) {
802 stop("'save_name' must be a single character refering to file name.")
803 }
804
805 xgb.Callback(
806 cb_name = "save_model",
807 env = as.environment(list(save_period = save_period, save_name = save_name, last_save = 0)),
808 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration) {
809 env$begin_iteration <- begin_iteration
810 },
811 f_before_iter = NULL,
812 f_after_iter = function(env, model, data, evals, iteration, iter_feval) {
813 if (env$save_period > 0 && (iteration - env$begin_iteration) %% env$save_period == 0) {
814 .save.model.w.formatted.name(model, env$save_name, iteration)
815 env$last_save <- iteration
816 }
817 return(FALSE)
818 },
819 f_after_training = function(env, model, data, evals, iteration, final_feval, prev_cb_res) {
820 if (env$save_period == 0 && iteration > env$last_save) {
821 .save.model.w.formatted.name(model, env$save_name, iteration)
822 }
823 }
824 )
825 }
826
827 #' Callback for returning cross-validation based predictions
828 #'
829 #' This callback function saves predictions for all of the test folds,
830 #' and also allows to save the folds' models.
831 #'
832 #' @details
833 #' Predictions are saved inside of the `pred` element, which is either a vector or a matrix,
834 #' depending on the number of prediction outputs per data row. The order of predictions corresponds
835 #' to the order of rows in the original dataset. Note that when a custom `folds` list is
836 #' provided in [xgb.cv()], the predictions would only be returned properly when this list is a
837 #' non-overlapping list of k sets of indices, as in a standard k-fold CV. The predictions would not be
838 #' meaningful when user-provided folds have overlapping indices as in, e.g., random sampling splits.
839 #' When some of the indices in the training dataset are not included into user-provided `folds`,
840 #' their prediction value would be `NA`.
841 #'
842 #' @param save_models A flag for whether to save the folds' models.
843 #' @param outputmargin Whether to save margin predictions (same effect as passing this
844 #' parameter to [predict.xgb.Booster]).
845 #' @return An `xgb.Callback` object, which can be passed to [xgb.cv()],
846 #' but **not** to [xgb.train()].
847 #' @export
848 xgb.cb.cv.predict <- function(save_models = FALSE, outputmargin = FALSE) {
849 xgb.Callback(
850 cb_name = "cv_predict",
851 env = as.environment(list(save_models = save_models, outputmargin = outputmargin)),
852 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration) {
853 if (inherits(model, "xgb.Booster")) {
854 stop("'cv.predict' callback is only for 'xgb.cv'.")
855 }
856 },
857 f_before_iter = NULL,
858 f_after_iter = NULL,
859 f_after_training = function(env, model, data, evals, iteration, final_feval, prev_cb_res) {
860 pred <- NULL
861 for (fd in model) {
862 pr <- predict(
863 fd$bst,
864 fd$evals[[2L]],
865 outputmargin = env$outputmargin
866 )
867 if (is.null(pred)) {
868 if (NCOL(pr) > 1L) {
869 pred <- matrix(NA_real_, nrow(data), ncol(pr))
870 } else {
871 pred <- matrix(NA_real_, nrow(data))
872 }
873 }
874 if (is.matrix(pred)) {
875 pred[fd$index, ] <- pr
876 } else {
877 pred[fd$index] <- pr
878 }
879 }
880 out <- list(pred = pred)
881 if (env$save_models) {
882 out$models <- lapply(model, function(fd) fd$bst)
883 }
884 return(out)
885 }
886 )
887 }
888
889 .list2mat <- function(coef_list, sparse) {
890 if (sparse) {
891 coef_mat <- methods::new("dgRMatrix")
892 coef_mat@p <- as.integer(c(0, cumsum(sapply(coef_list, function(x) length(x@x)))))
893 coef_mat@j <- as.integer(unlist(lapply(coef_list, slot, "i")) - 1L)
894 coef_mat@x <- unlist(lapply(coef_list, slot, "x"))
895 coef_mat@Dim <- as.integer(c(length(coef_list), length(coef_list[[1L]])))
896 # Note: function 'xgb.gblinear.history' might later on try to slice by columns
897 coef_mat <- methods::as(coef_mat, "CsparseMatrix")
898 return(coef_mat)
899 } else {
900 return(unname(do.call(rbind, coef_list)))
901 }
902 }
903
904 .extract.coef <- function(model, sparse) {
905 coefs <- .internal.coef.xgb.Booster(model, add_names = FALSE)
906 if (NCOL(coefs) > 1L) {
907 coefs <- as.vector(coefs)
908 }
909 if (sparse) {
910 coefs <- methods::as(coefs, "sparseVector")
911 }
912 return(coefs)
913 }
914
915 #' Callback for collecting coefficients history of a gblinear booster
916 #'
917 #' @details
918 #' To keep things fast and simple, gblinear booster does not internally store the history of linear
919 #' model coefficients at each boosting iteration. This callback provides a workaround for storing
920 #' the coefficients' path, by extracting them after each training iteration.
921 #'
922 #' This callback will construct a matrix where rows are boosting iterations and columns are
923 #' feature coefficients (same order as when calling [coef.xgb.Booster], with the intercept
924 #' corresponding to the first column).
925 #'
926 #' When there is more than one coefficient per feature (e.g. multi-class classification),
927 #' the result will be reshaped into a vector where coefficients are arranged first by features and
928 #' then by class (e.g. first 1 through N coefficients will be for the first class, then
929 #' coefficients N+1 through 2N for the second class, and so on).
930 #'
931 #' If the result has only one coefficient per feature in the data, then the resulting matrix
932 #' will have column names matching with the feature names, otherwise (when there's more than
933 #' one coefficient per feature) the names will be composed as 'column name' + ':' + 'class index'
934 #' (so e.g. column 'c1' for class '0' will be named 'c1:0').
935 #'
936 #' With [xgb.train()], the output is either a dense or a sparse matrix.
937 #' With with [xgb.cv()], it is a list (one element per each fold) of such matrices.
938 #'
939 #' Function [xgb.gblinear.history] provides an easy way to retrieve the
940 #' outputs from this callback.
941 #'
942 #' @param sparse When set to `FALSE`/`TRUE`, a dense/sparse matrix is used to store the result.
943 #' Sparse format is useful when one expects only a subset of coefficients to be non-zero,
944 #' when using the "thrifty" feature selector with fairly small number of top features
945 #' selected per iteration.
946 #' @return An `xgb.Callback` object, which can be passed to [xgb.train()] or [xgb.cv()].
947 #' @seealso [xgb.gblinear.history], [coef.xgb.Booster].
948 #' @examples
949 #' #### Binary classification:
950 #'
951 #' ## Keep the number of threads to 1 for examples
952 #' nthread <- 1
953 #' data.table::setDTthreads(nthread)
954 #'
955 #' # In the iris dataset, it is hard to linearly separate Versicolor class from the rest
956 #' # without considering the 2nd order interactions:
957 #' x <- model.matrix(Species ~ .^2, iris)[, -1]
958 #' colnames(x)
959 #' dtrain <- xgb.DMatrix(
960 #' scale(x),
961 #' label = 1 * (iris$Species == "versicolor"),
962 #' nthread = nthread
963 #' )
964 #' param <- xgb.params(
965 #' booster = "gblinear",
966 #' objective = "reg:logistic",
967 #' eval_metric = "auc",
968 #' reg_lambda = 0.0003,
969 #' reg_alpha = 0.0003,
970 #' nthread = nthread
971 #' )
972 #'
973 #' # For 'shotgun', which is a default linear updater, using high learning_rate values may result in
974 #' # unstable behaviour in some datasets. With this simple dataset, however, the high learning
975 #' # rate does not break the convergence, but allows us to illustrate the typical pattern of
976 #' # "stochastic explosion" behaviour of this lock-free algorithm at early boosting iterations.
977 #' bst <- xgb.train(
978 #' c(param, list(learning_rate = 1.)),
979 #' dtrain,
980 #' evals = list(tr = dtrain),
981 #' nrounds = 200,
982 #' callbacks = list(xgb.cb.gblinear.history())
983 #' )
984 #'
985 #' # Extract the coefficients' path and plot them vs boosting iteration number:
986 #' coef_path <- xgb.gblinear.history(bst)
987 #' matplot(coef_path, type = "l")
988 #'
989 #' # With the deterministic coordinate descent updater, it is safer to use higher learning rates.
990 #' # Will try the classical componentwise boosting which selects a single best feature per round:
991 #' bst <- xgb.train(
992 #' c(
993 #' param,
994 #' xgb.params(
995 #' learning_rate = 0.8,
996 #' updater = "coord_descent",
997 #' feature_selector = "thrifty",
998 #' top_k = 1
999 #' )
1000 #' ),
1001 #' dtrain,
1002 #' evals = list(tr = dtrain),
1003 #' nrounds = 200,
1004 #' callbacks = list(xgb.cb.gblinear.history())
1005 #' )
1006 #' matplot(xgb.gblinear.history(bst), type = "l")
1007 #' # Componentwise boosting is known to have similar effect to Lasso regularization.
1008 #' # Try experimenting with various values of top_k, learning_rate, nrounds,
1009 #' # as well as different feature_selectors.
1010 #'
1011 #' # For xgb.cv:
1012 #' bst <- xgb.cv(
1013 #' c(
1014 #' param,
1015 #' xgb.params(
1016 #' learning_rate = 0.8,
1017 #' updater = "coord_descent",
1018 #' feature_selector = "thrifty",
1019 #' top_k = 1
1020 #' )
1021 #' ),
1022 #' dtrain,
1023 #' nfold = 5,
1024 #' nrounds = 100,
1025 #' callbacks = list(xgb.cb.gblinear.history())
1026 #' )
1027 #' # coefficients in the CV fold #3
1028 #' matplot(xgb.gblinear.history(bst)[[3]], type = "l")
1029 #'
1030 #'
1031 #' #### Multiclass classification:
1032 #' dtrain <- xgb.DMatrix(scale(x), label = as.numeric(iris$Species) - 1, nthread = nthread)
1033 #'
1034 #' param <- xgb.params(
1035 #' booster = "gblinear",
1036 #' objective = "multi:softprob",
1037 #' num_class = 3,
1038 #' reg_lambda = 0.0003,
1039 #' reg_alpha = 0.0003,
1040 #' nthread = nthread
1041 #' )
1042 #'
1043 #' # For the default linear updater 'shotgun' it sometimes is helpful
1044 #' # to use smaller learning_rate to reduce instability
1045 #' bst <- xgb.train(
1046 #' c(param, list(learning_rate = 0.5)),
1047 #' dtrain,
1048 #' evals = list(tr = dtrain),
1049 #' nrounds = 50,
1050 #' callbacks = list(xgb.cb.gblinear.history())
1051 #' )
1052 #'
1053 #' # Will plot the coefficient paths separately for each class:
1054 #' matplot(xgb.gblinear.history(bst, class_index = 0), type = "l")
1055 #' matplot(xgb.gblinear.history(bst, class_index = 1), type = "l")
1056 #' matplot(xgb.gblinear.history(bst, class_index = 2), type = "l")
1057 #'
1058 #' # CV:
1059 #' bst <- xgb.cv(
1060 #' c(param, list(learning_rate = 0.5)),
1061 #' dtrain,
1062 #' nfold = 5,
1063 #' nrounds = 70,
1064 #' callbacks = list(xgb.cb.gblinear.history(FALSE))
1065 #' )
1066 #' # 1st fold of 1st class
1067 #' matplot(xgb.gblinear.history(bst, class_index = 0)[[1]], type = "l")
1068 #'
1069 #' @export
1070 xgb.cb.gblinear.history <- function(sparse = FALSE) {
1071 xgb.Callback(
1072 cb_name = "gblinear_history",
1073 env = as.environment(list(sparse = sparse)),
1074 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration) {
1075 if (!inherits(model, "xgb.Booster")) {
1076 model <- model[[1L]]$bst
1077 }
1078 if (xgb.booster_type(model) != "gblinear") {
1079 stop("Callback 'xgb.cb.gblinear.history' is only for booster='gblinear'.")
1080 }
1081 env$coef_hist <- vector("list", end_iteration - begin_iteration + 1)
1082 env$next_idx <- 1
1083 },
1084 f_before_iter = NULL,
1085 f_after_iter = function(env, model, data, evals, iteration, iter_feval) {
1086 if (inherits(model, "xgb.Booster")) {
1087 coef_this <- .extract.coef(model, env$sparse)
1088 } else {
1089 coef_this <- lapply(model, function(fd) .extract.coef(fd$bst, env$sparse))
1090 }
1091 env$coef_hist[[env$next_idx]] <- coef_this
1092 env$next_idx <- env$next_idx + 1
1093 return(FALSE)
1094 },
1095 f_after_training = function(env, model, data, evals, iteration, final_feval, prev_cb_res) {
1096 # in case of early stopping
1097 if (env$next_idx <= length(env$coef_hist)) {
1098 env$coef_hist <- head(env$coef_hist, env$next_idx - 1)
1099 }
1100
1101 is_booster <- inherits(model, "xgb.Booster")
1102 if (is_booster) {
1103 out <- .list2mat(env$coef_hist, env$sparse)
1104 } else {
1105 out <- lapply(
1106 X = lapply(
1107 X = seq_along(env$coef_hist[[1]]),
1108 FUN = function(i) lapply(env$coef_hist, "[[", i)
1109 ),
1110 FUN = .list2mat,
1111 env$sparse
1112 )
1113 }
1114 if (!is.null(prev_cb_res)) {
1115 if (is_booster) {
1116 out <- rbind(prev_cb_res, out)
1117 } else {
1118 # Note: this case should never be encountered, since training cannot
1119 # be continued from the result of xgb.cv, but this code should in
1120 # theory do the job if the situation were to be encountered.
1121 out <- lapply(
1122 out,
1123 function(lst) {
1124 lapply(
1125 seq_along(lst),
1126 function(i) rbind(prev_cb_res[[i]], lst[[i]])
1127 )
1128 }
1129 )
1130 }
1131 }
1132 feature_names <- getinfo(data, "feature_name")
1133 if (!NROW(feature_names)) {
1134 feature_names <- paste0("V", seq(1L, ncol(data)))
1135 }
1136 expected_ncols <- length(feature_names) + 1
1137 if (is_booster) {
1138 mat_ncols <- ncol(out)
1139 } else {
1140 mat_ncols <- ncol(out[[1L]])
1141 }
1142 if (mat_ncols %% expected_ncols == 0) {
1143 feature_names <- c("(Intercept)", feature_names)
1144 n_rep <- mat_ncols / expected_ncols
1145 if (n_rep > 1) {
1146 feature_names <- unlist(
1147 lapply(
1148 seq(1, n_rep),
1149 function(cl) paste(feature_names, cl - 1, sep = ":")
1150 )
1151 )
1152 }
1153 if (is_booster) {
1154 colnames(out) <- feature_names
1155 } else {
1156 out <- lapply(
1157 out,
1158 function(mat) {
1159 colnames(mat) <- feature_names
1160 return(mat)
1161 }
1162 )
1163 }
1164 }
1165 return(out)
1166 }
1167 )
1168 }
1169
1170 #' Extract gblinear coefficients history
1171 #'
1172 #' A helper function to extract the matrix of linear coefficients' history
1173 #' from a gblinear model created while using the [xgb.cb.gblinear.history]
1174 #' callback (which must be added manually as by default it is not used).
1175 #'
1176 #' @details
1177 #' Note that this is an R-specific function that relies on R attributes that
1178 #' are not saved when using XGBoost's own serialization functions like [xgb.load()]
1179 #' or [xgb.load.raw()].
1180 #'
1181 #' In order for a serialized model to be accepted by this function, one must use R
1182 #' serializers such as [saveRDS()].
1183 #' @param model Either an `xgb.Booster` or a result of [xgb.cv()], trained
1184 #' using the [xgb.cb.gblinear.history] callback, but **not** a booster
1185 #' loaded from [xgb.load()] or [xgb.load.raw()].
1186 #' @param class_index zero-based class index to extract the coefficients for only that
1187 #' specific class in a multinomial multiclass model. When it is `NULL`, all the
1188 #' coefficients are returned. Has no effect in non-multiclass models.
1189 #'
1190 #' @return
1191 #' For an [xgb.train()] result, a matrix (either dense or sparse) with the columns
1192 #' corresponding to iteration's coefficients and the rows corresponding to boosting iterations.
1193 #'
1194 #' For an [xgb.cv()] result, a list of such matrices is returned with the elements
1195 #' corresponding to CV folds.
1196 #'
1197 #' When there is more than one coefficient per feature (e.g. multi-class classification)
1198 #' and `class_index` is not provided,
1199 #' the result will be reshaped into a vector where coefficients are arranged first by features and
1200 #' then by class (e.g. first 1 through N coefficients will be for the first class, then
1201 #' coefficients N+1 through 2N for the second class, and so on).
1202 #' @seealso [xgb.cb.gblinear.history], [coef.xgb.Booster].
1203 #' @export
1204 xgb.gblinear.history <- function(model, class_index = NULL) {
1205
1206 if (!(inherits(model, "xgb.Booster") ||
1207 inherits(model, "xgb.cv.synchronous")))
1208 stop("model must be an object of either xgb.Booster or xgb.cv.synchronous class")
1209 is_cv <- inherits(model, "xgb.cv.synchronous")
1210
1211 if (!is_cv) {
1212 coef_path <- getElement(attributes(model), "gblinear_history")
1213 } else {
1214 coef_path <- getElement(model, "gblinear_history")
1215 }
1216 if (is.null(coef_path)) {
1217 stop("model must be trained while using the xgb.cb.gblinear.history() callback")
1218 }
1219
1220 if (!is_cv) {
1221 num_class <- xgb.num_class(model)
1222 num_feat <- xgb.num_feature(model)
1223 } else {
1224 # in case of CV, the object is expected to have this info
1225 if (model$params$booster != "gblinear")
1226 stop("It does not appear to be a gblinear model")
1227 num_class <- NVL(model$params$num_class, 1)
1228 num_feat <- model$nfeatures
1229 if (is.null(num_feat))
1230 stop("This xgb.cv result does not have nfeatures info")
1231 }
1232
1233 if (!is.null(class_index) &&
1234 num_class > 1 &&
1235 (class_index[1] < 0 || class_index[1] >= num_class))
1236 stop("class_index has to be within [0,", num_class - 1, "]")
1237
1238 if (!is.null(class_index) && num_class > 1) {
1239 seq_take <- seq(1 + class_index * (num_feat + 1), (class_index + 1) * (num_feat + 1))
1240 coef_path <- if (is.list(coef_path)) {
1241 lapply(coef_path, function(x) x[, seq_take])
1242 } else {
1243 coef_path <- coef_path[, seq_take]
1244 }
1245 }
1246 return(coef_path)
1247 }
1248
1249 .callbacks.only.train <- "save_model"
1250 .callbacks.only.cv <- "cv_predict"
1251
1252 .process.callbacks <- function(callbacks, is_cv) {
1253 if (inherits(callbacks, "xgb.Callback")) {
1254 callbacks <- list(callbacks)
1255 }
1256 if (!is.list(callbacks)) {
1257 stop("'callbacks' must be a list.")
1258 }
1259 cb_names <- character()
1260 if (length(callbacks)) {
1261 is_callback <- sapply(callbacks, inherits, "xgb.Callback")
1262 if (!all(is_callback)) {
1263 stop("Entries in 'callbacks' must be 'xgb.Callback' objects.")
1264 }
1265 cb_names <- sapply(callbacks, function(cb) cb$cb_name)
1266 if (length(cb_names) != length(callbacks)) {
1267 stop("Passed invalid callback(s).")
1268 }
1269 if (anyDuplicated(cb_names) > 0) {
1270 stop("Callbacks must have unique names.")
1271 }
1272 if (is_cv) {
1273 if (any(.callbacks.only.train %in% cb_names)) {
1274 stop(
1275 "Passed callback(s) not supported for 'xgb.cv': ",
1276 paste(intersect(.callbacks.only.train, cb_names), collapse = ", ")
1277 )
1278 }
1279 } else {
1280 if (any(.callbacks.only.cv %in% cb_names)) {
1281 stop(
1282 "Passed callback(s) not supported for 'xgb.train': ",
1283 paste(intersect(.callbacks.only.cv, cb_names), collapse = ", ")
1284 )
1285 }
1286 }
1287 # Early stopping callback needs to be executed before the others
1288 if ("early_stop" %in% cb_names) {
1289 mask <- cb_names == "early_stop"
1290 callbacks <- c(list(callbacks[[which(mask)]]), callbacks[!mask])
1291 }
1292 }
1293 return(list(callbacks = callbacks, cb_names = cb_names))
1294 }
1295
1296 # Note: don't try to use functions like 'append', as they will
1297 # merge the elements of the different callbacks into a single list.
1298 add.callback <- function(callbacks, cb, as_first_elt = FALSE) {
1299 if (!as_first_elt) {
1300 callbacks[[length(callbacks) + 1]] <- cb
1301 return(callbacks)
1302 } else {
1303 if (!length(callbacks)) {
1304 return(list(cb))
1305 }
1306 new_cb <- vector("list", length(callbacks) + 1)
1307 new_cb[[1]] <- cb
1308 new_cb[seq(2, length(new_cb))] <- callbacks
1309 return(new_cb)
1310 }
1311 }
1312
1313 has.callbacks <- function(callbacks, cb_name) {
1314 cb_names <- sapply(callbacks, function(cb) cb$name)
1315 return(cb_name %in% cb_names)
1316 }