| 1 |
#' @title Fit XGBoost Model |
| 2 |
#' @description Fits an XGBoost model to given data in DMatrix format (e.g. as produced by [xgb.DMatrix()]). |
| 3 |
#' See the tutorial [Introduction to Boosted Trees](https://xgboost.readthedocs.io/en/stable/tutorials/model.html) |
| 4 |
#' for a longer explanation of what XGBoost does, and the rest of the |
| 5 |
#' [XGBoost Tutorials](https://xgboost.readthedocs.io/en/latest/tutorials/index.html) for further |
| 6 |
#' explanations XGBoost's features and usage. |
| 7 |
#' |
| 8 |
#' Compared to function [xgboost()] which is a user-friendly function targeted towards interactive |
| 9 |
#' usage, ``xgb.train`` is a lower-level interface which allows finer-grained control and exposes |
| 10 |
#' further functionalities offered by the core library (such as learning-to-rank objectives), but |
| 11 |
#' which works exclusively with XGBoost's own data format ("DMatrices") instead of with regular R |
| 12 |
#' objects. |
| 13 |
#' |
| 14 |
#' The syntax of this function closely mimics the same function from the Python package for XGBoost, |
| 15 |
#' and is recommended to use for package developers over `xgboost()` as it will provide a more |
| 16 |
#' stable interface (with fewer breaking changes) and lower overhead from data validations. |
| 17 |
#' |
| 18 |
#' See also the [migration guide](https://xgboost.readthedocs.io/en/latest/R-package/migration_guide.html) |
| 19 |
#' if coming from a previous version of XGBoost in the 1.x series. |
| 20 |
#' @param params List of XGBoost parameters which control the model building process. |
| 21 |
#' See the [online documentation](https://xgboost.readthedocs.io/en/latest/parameter.html) |
| 22 |
#' and the documentation for [xgb.params()] for details. |
| 23 |
#' |
| 24 |
#' Should be passed as list with named entries. Parameters that are not specified in this |
| 25 |
#' list will use their default values. |
| 26 |
#' |
| 27 |
#' A list of named parameters can be created through the function [xgb.params()], which |
| 28 |
#' accepts all valid parameters as function arguments. |
| 29 |
#' @param data Training dataset. `xgb.train()` accepts only an `xgb.DMatrix` as the input. |
| 30 |
#' |
| 31 |
#' Note that there is a function [xgboost()] which is meant to accept R data objects |
| 32 |
#' as inputs, such as data frames and matrices. |
| 33 |
#' @param nrounds Max number of boosting iterations. |
| 34 |
#' @param evals Named list of `xgb.DMatrix` datasets to use for evaluating model performance. |
| 35 |
#' Metrics specified in either `eval_metric` (under params) or `custom_metric` (function |
| 36 |
#' argument here) will be computed for each of these datasets during each boosting iteration, |
| 37 |
#' and stored in the end as a field named `evaluation_log` in the resulting object. |
| 38 |
#' |
| 39 |
#' When either `verbose>=1` or [xgb.cb.print.evaluation()] callback is engaged, the performance |
| 40 |
#' results are continuously printed out during the training. |
| 41 |
#' |
| 42 |
#' E.g., specifying `evals=list(validation1=mat1, validation2=mat2)` allows to track |
| 43 |
#' the performance of each round's model on `mat1` and `mat2`. |
| 44 |
#' @param objective Customized objective function. Should take two arguments: the first one will be the |
| 45 |
#' current predictions (either a numeric vector or matrix depending on the number of targets / classes), |
| 46 |
#' and the second one will be the `data` DMatrix object that is used for training. |
| 47 |
#' |
| 48 |
#' It should return a list with two elements `grad` and `hess` (in that order), as either |
| 49 |
#' numeric vectors or numeric matrices depending on the number of targets / classes (same |
| 50 |
#' dimension as the predictions that are passed as first argument). |
| 51 |
#' @param custom_metric Customized evaluation function. Just like `objective`, should take two arguments, |
| 52 |
#' with the first one being the predictions and the second one the `data` DMatrix. |
| 53 |
#' |
| 54 |
#' Should return a list with two elements `metric` (name that will be displayed for this metric, |
| 55 |
#' should be a string / character), and `value` (the number that the function calculates, should |
| 56 |
#' be a numeric scalar). |
| 57 |
#' |
| 58 |
#' Note that even if passing `custom_metric`, objectives also have an associated default metric that |
| 59 |
#' will be evaluated in addition to it. In order to disable the built-in metric, one can pass |
| 60 |
#' parameter `disable_default_eval_metric = TRUE`. |
| 61 |
#' @param verbose If 0, xgboost will stay silent. If 1, it will print information about performance. |
| 62 |
#' If 2, some additional information will be printed out. |
| 63 |
#' Note that setting `verbose > 0` automatically engages the |
| 64 |
#' `xgb.cb.print.evaluation(period=1)` callback function. |
| 65 |
#' @param print_every_n When passing `verbose>0`, evaluation logs (metrics calculated on the |
| 66 |
#' data passed under `evals`) will be printed every nth iteration according to the value passed |
| 67 |
#' here. The first and last iteration are always included regardless of this 'n'. |
| 68 |
#' |
| 69 |
#' Only has an effect when passing data under `evals` and when passing `verbose>0`. The parameter |
| 70 |
#' is passed to the [xgb.cb.print.evaluation()] callback. |
| 71 |
#' @param early_stopping_rounds Number of boosting rounds after which training will be stopped |
| 72 |
#' if there is no improvement in performance (as measured by the evaluatiation metric that is |
| 73 |
#' supplied or selected by default for the objective) on the evaluation data passed under |
| 74 |
#' `evals`. |
| 75 |
#' |
| 76 |
#' Must pass `evals` in order to use this functionality. Setting this parameter adds the |
| 77 |
#' [xgb.cb.early.stop()] callback. |
| 78 |
#' |
| 79 |
#' If `NULL`, early stopping will not be used. |
| 80 |
#' @param maximize If `feval` and `early_stopping_rounds` are set, then this parameter must be set as well. |
| 81 |
#' When it is `TRUE`, it means the larger the evaluation score the better. |
| 82 |
#' This parameter is passed to the [xgb.cb.early.stop()] callback. |
| 83 |
#' @param save_period When not `NULL`, model is saved to disk after every `save_period` rounds. |
| 84 |
#' 0 means save at the end. The saving is handled by the [xgb.cb.save.model()] callback. |
| 85 |
#' @param save_name the name or path for periodically saved model file. |
| 86 |
#' @param xgb_model A previously built model to continue the training from. |
| 87 |
#' Could be either an object of class `xgb.Booster`, or its raw data, or the name of a |
| 88 |
#' file with a previously saved model. |
| 89 |
#' @param callbacks A list of callback functions to perform various task during boosting. |
| 90 |
#' See [xgb.Callback()]. Some of the callbacks are automatically created depending on the |
| 91 |
#' parameters' values. User can provide either existing or their own callback methods in order |
| 92 |
#' to customize the training process. |
| 93 |
#' |
| 94 |
#' Note that some callbacks might try to leave attributes in the resulting model object, |
| 95 |
#' such as an evaluation log (a `data.table` object) - be aware that these objects are kept |
| 96 |
#' as R attributes, and thus do not get saved when using XGBoost's own serializaters like |
| 97 |
#' [xgb.save()] (but are kept when using R serializers like [saveRDS()]). |
| 98 |
#' @param ... Not used. |
| 99 |
#' |
| 100 |
#' Some arguments that were part of this function in previous XGBoost versions are currently |
| 101 |
#' deprecated or have been renamed. If a deprecated or renamed argument is passed, will throw |
| 102 |
#' a warning (by default) and use its current equivalent instead. This warning will become an |
| 103 |
#' error if using the \link[=xgboost-options]{'strict mode' option}. |
| 104 |
#' |
| 105 |
#' If some additional argument is passed that is neither a current function argument nor |
| 106 |
#' a deprecated or renamed argument, a warning or error will be thrown depending on the |
| 107 |
#' 'strict mode' option. |
| 108 |
#' |
| 109 |
#' \bold{Important:} `...` will be removed in a future version, and all the current |
| 110 |
#' deprecation warnings will become errors. Please use only arguments that form part of |
| 111 |
#' the function signature. |
| 112 |
#' @return An object of class `xgb.Booster`. |
| 113 |
#' @details |
| 114 |
#' Compared to [xgboost()], the `xgb.train()` interface supports advanced features such as |
| 115 |
#' `evals`, customized objective and evaluation metric functions, among others, with the |
| 116 |
#' difference these work `xgb.DMatrix` objects and do not follow typical R idioms. |
| 117 |
#' |
| 118 |
#' Parallelization is automatically enabled if OpenMP is present. |
| 119 |
#' Number of threads can also be manually specified via the `nthread` parameter. |
| 120 |
#' |
| 121 |
#' While in XGBoost language bindings, the default random seed defaults to zero, in R, if a parameter `seed` |
| 122 |
#' is not manually supplied, it will generate a random seed through R's own random number generator, |
| 123 |
#' whose seed in turn is controllable through `set.seed`. If `seed` is passed, it will override the |
| 124 |
#' RNG from R. |
| 125 |
#' |
| 126 |
#' The following callbacks are automatically created when certain parameters are set: |
| 127 |
#' - [xgb.cb.print.evaluation()] is turned on when `verbose > 0` and the `print_every_n` |
| 128 |
#' parameter is passed to it. |
| 129 |
#' - [xgb.cb.evaluation.log()] is on when `evals` is present. |
| 130 |
#' - [xgb.cb.early.stop()]: When `early_stopping_rounds` is set. |
| 131 |
#' - [xgb.cb.save.model()]: When `save_period > 0` is set. |
| 132 |
#' |
| 133 |
#' Note that objects of type `xgb.Booster` as returned by this function behave a bit differently |
| 134 |
#' from typical R objects (it's an 'altrep' list class), and it makes a separation between |
| 135 |
#' internal booster attributes (restricted to jsonifyable data), accessed through [xgb.attr()] |
| 136 |
#' and shared between interfaces through serialization functions like [xgb.save()]; and |
| 137 |
#' R-specific attributes (typically the result from a callback), accessed through [attributes()] |
| 138 |
#' and [attr()], which are otherwise |
| 139 |
#' only used in the R interface, only kept when using R's serializers like [saveRDS()], and |
| 140 |
#' not anyhow used by functions like `predict.xgb.Booster()`. |
| 141 |
#' |
| 142 |
#' Be aware that one such R attribute that is automatically added is `params` - this attribute |
| 143 |
#' is assigned from the `params` argument to this function, and is only meant to serve as a |
| 144 |
#' reference for what went into the booster, but is not used in other methods that take a booster |
| 145 |
#' object - so for example, changing the booster's configuration requires calling `xgb.config<-` |
| 146 |
#' or `xgb.model.parameters<-`, while simply modifying `attributes(model)$params$<...>` will have no |
| 147 |
#' effect elsewhere. |
| 148 |
#' |
| 149 |
#' @seealso [xgb.Callback()], [predict.xgb.Booster()], [xgb.cv()] |
| 150 |
#' |
| 151 |
#' @references |
| 152 |
#' Tianqi Chen and Carlos Guestrin, "XGBoost: A Scalable Tree Boosting System", |
| 153 |
#' 22nd SIGKDD Conference on Knowledge Discovery and Data Mining, 2016, \url{https://arxiv.org/abs/1603.02754} |
| 154 |
#' |
| 155 |
#' @examples |
| 156 |
#' data(agaricus.train, package = "xgboost") |
| 157 |
#' data(agaricus.test, package = "xgboost") |
| 158 |
#' |
| 159 |
#' ## Keep the number of threads to 1 for examples |
| 160 |
#' nthread <- 1 |
| 161 |
#' data.table::setDTthreads(nthread) |
| 162 |
#' |
| 163 |
#' dtrain <- with( |
| 164 |
#' agaricus.train, xgb.DMatrix(data, label = label, nthread = nthread) |
| 165 |
#' ) |
| 166 |
#' dtest <- with( |
| 167 |
#' agaricus.test, xgb.DMatrix(data, label = label, nthread = nthread) |
| 168 |
#' ) |
| 169 |
#' evals <- list(train = dtrain, eval = dtest) |
| 170 |
#' |
| 171 |
#' ## A simple xgb.train example: |
| 172 |
#' param <- xgb.params( |
| 173 |
#' max_depth = 2, |
| 174 |
#' nthread = nthread, |
| 175 |
#' objective = "binary:logistic", |
| 176 |
#' eval_metric = "auc" |
| 177 |
#' ) |
| 178 |
#' bst <- xgb.train(param, dtrain, nrounds = 2, evals = evals, verbose = 0) |
| 179 |
#' |
| 180 |
#' ## An xgb.train example where custom objective and evaluation metric are |
| 181 |
#' ## used: |
| 182 |
#' logregobj <- function(preds, dtrain) { |
| 183 |
#' labels <- getinfo(dtrain, "label") |
| 184 |
#' preds <- 1/(1 + exp(-preds)) |
| 185 |
#' grad <- preds - labels |
| 186 |
#' hess <- preds * (1 - preds) |
| 187 |
#' return(list(grad = grad, hess = hess)) |
| 188 |
#' } |
| 189 |
#' evalerror <- function(preds, dtrain) { |
| 190 |
#' labels <- getinfo(dtrain, "label") |
| 191 |
#' err <- as.numeric(sum(labels != (preds > 0)))/length(labels) |
| 192 |
#' return(list(metric = "error", value = err)) |
| 193 |
#' } |
| 194 |
#' |
| 195 |
#' # These functions could be used by passing them as 'objective' and |
| 196 |
#' # 'eval_metric' parameters in the params list: |
| 197 |
#' param <- xgb.params( |
| 198 |
#' max_depth = 2, |
| 199 |
#' nthread = nthread, |
| 200 |
#' objective = logregobj, |
| 201 |
#' eval_metric = evalerror |
| 202 |
#' ) |
| 203 |
#' bst <- xgb.train(param, dtrain, nrounds = 2, evals = evals, verbose = 0) |
| 204 |
#' |
| 205 |
#' # ... or as dedicated 'objective' and 'custom_metric' parameters of xgb.train: |
| 206 |
#' bst <- xgb.train( |
| 207 |
#' within(param, rm("objective", "eval_metric")), |
| 208 |
#' dtrain, nrounds = 2, evals = evals, |
| 209 |
#' objective = logregobj, custom_metric = evalerror |
| 210 |
#' ) |
| 211 |
#' |
| 212 |
#' |
| 213 |
#' ## An xgb.train example of using variable learning rates at each iteration: |
| 214 |
#' param <- xgb.params( |
| 215 |
#' max_depth = 2, |
| 216 |
#' learning_rate = 1, |
| 217 |
#' nthread = nthread, |
| 218 |
#' objective = "binary:logistic", |
| 219 |
#' eval_metric = "auc" |
| 220 |
#' ) |
| 221 |
#' my_learning_rates <- list(learning_rate = c(0.5, 0.1)) |
| 222 |
#' |
| 223 |
#' bst <- xgb.train( |
| 224 |
#' param, |
| 225 |
#' dtrain, |
| 226 |
#' nrounds = 2, |
| 227 |
#' evals = evals, |
| 228 |
#' verbose = 0, |
| 229 |
#' callbacks = list(xgb.cb.reset.parameters(my_learning_rates)) |
| 230 |
#' ) |
| 231 |
#' |
| 232 |
#' ## Early stopping: |
| 233 |
#' bst <- xgb.train( |
| 234 |
#' param, dtrain, nrounds = 25, evals = evals, early_stopping_rounds = 3 |
| 235 |
#' ) |
| 236 |
#' @export |
| 237 |
xgb.train <- function(params = xgb.params(), data, nrounds, evals = list(), |
| 238 |
objective = NULL, custom_metric = NULL, verbose = 1, print_every_n = 1L, |
| 239 |
early_stopping_rounds = NULL, maximize = NULL, |
| 240 |
save_period = NULL, save_name = "xgboost.model", |
| 241 |
xgb_model = NULL, callbacks = list(), ...) { |
| 242 |
check.deprecation(deprecated_train_params, match.call(), ...) |
| 243 |
|
| 244 |
params <- check.booster.params(params) |
| 245 |
tmp <- check.custom.obj(params, objective) |
| 246 |
params <- tmp$params |
| 247 |
objective <- tmp$objective |
| 248 |
tmp <- check.custom.eval(params, custom_metric, maximize, early_stopping_rounds, callbacks) |
| 249 |
params <- tmp$params |
| 250 |
custom_metric <- tmp$custom_metric |
| 251 |
|
| 252 |
# data & evals checks |
| 253 |
dtrain <- data |
| 254 |
if (!inherits(dtrain, "xgb.DMatrix")) |
| 255 |
stop("second argument dtrain must be xgb.DMatrix") |
| 256 |
if (length(evals) > 0) { |
| 257 |
if (typeof(evals) != "list" || |
| 258 |
!all(vapply(evals, inherits, logical(1), what = 'xgb.DMatrix'))) |
| 259 |
stop("'evals' must be a list of xgb.DMatrix elements") |
| 260 |
evnames <- names(evals) |
| 261 |
if (is.null(evnames) || any(evnames == "")) |
| 262 |
stop("each element of 'evals' must have a name tag") |
| 263 |
} |
| 264 |
# Handle multiple evaluation metrics given as a list |
| 265 |
for (m in params$eval_metric) { |
| 266 |
params <- c(params, list(eval_metric = m)) |
| 267 |
} |
| 268 |
|
| 269 |
params <- c(params) |
| 270 |
params['validate_parameters'] <- TRUE |
| 271 |
if (!("seed" %in% names(params))) { |
| 272 |
params[["seed"]] <- sample(.Machine$integer.max, size = 1) |
| 273 |
} |
| 274 |
|
| 275 |
# callbacks |
| 276 |
tmp <- .process.callbacks(callbacks, is_cv = FALSE) |
| 277 |
callbacks <- tmp$callbacks |
| 278 |
cb_names <- tmp$cb_names |
| 279 |
rm(tmp) |
| 280 |
|
| 281 |
# Early stopping callback (should always come first) |
| 282 |
if (!is.null(early_stopping_rounds) && !("early_stop" %in% cb_names)) { |
| 283 |
callbacks <- add.callback( |
| 284 |
callbacks, |
| 285 |
xgb.cb.early.stop( |
| 286 |
early_stopping_rounds, |
| 287 |
maximize = maximize, |
| 288 |
verbose = verbose |
| 289 |
), |
| 290 |
as_first_elt = TRUE |
| 291 |
) |
| 292 |
} |
| 293 |
# evaluation printing callback |
| 294 |
print_every_n <- max(as.integer(print_every_n), 1L) |
| 295 |
if (verbose && !("print_evaluation" %in% cb_names)) { |
| 296 |
callbacks <- add.callback(callbacks, xgb.cb.print.evaluation(print_every_n)) |
| 297 |
} |
| 298 |
# evaluation log callback: it is automatically enabled when 'evals' is provided |
| 299 |
if (length(evals) && !("evaluation_log" %in% cb_names)) { |
| 300 |
callbacks <- add.callback(callbacks, xgb.cb.evaluation.log()) |
| 301 |
} |
| 302 |
# Model saving callback |
| 303 |
if (!is.null(save_period) && !("save_model" %in% cb_names)) { |
| 304 |
callbacks <- add.callback(callbacks, xgb.cb.save.model(save_period, save_name)) |
| 305 |
} |
| 306 |
|
| 307 |
# The tree updating process would need slightly different handling |
| 308 |
is_update <- NVL(params[['process_type']], '.') == 'update' |
| 309 |
|
| 310 |
# Construct a booster (either a new one or load from xgb_model) |
| 311 |
bst <- xgb.Booster( |
| 312 |
params = params, |
| 313 |
cachelist = append(evals, dtrain), |
| 314 |
modelfile = xgb_model |
| 315 |
) |
| 316 |
niter_init <- bst$niter |
| 317 |
bst <- bst$bst |
| 318 |
.Call( |
| 319 |
XGBoosterCopyInfoFromDMatrix_R, |
| 320 |
xgb.get.handle(bst), |
| 321 |
dtrain |
| 322 |
) |
| 323 |
|
| 324 |
if (is_update && nrounds > niter_init) |
| 325 |
stop("nrounds cannot be larger than ", niter_init, " (nrounds of xgb_model)") |
| 326 |
|
| 327 |
niter_skip <- ifelse(is_update, 0, niter_init) |
| 328 |
begin_iteration <- niter_skip + 1 |
| 329 |
end_iteration <- niter_skip + nrounds |
| 330 |
|
| 331 |
.execute.cb.before.training( |
| 332 |
callbacks, |
| 333 |
bst, |
| 334 |
dtrain, |
| 335 |
evals, |
| 336 |
begin_iteration, |
| 337 |
end_iteration |
| 338 |
) |
| 339 |
|
| 340 |
# the main loop for boosting iterations |
| 341 |
# FIX: Handle nrounds=0 to prevent 1:0 sequence and ensure 'iteration' is defined |
| 342 |
if (nrounds == 0) iteration <- end_iteration |
| 343 |
for (iteration in seq(from = begin_iteration, length.out = nrounds)) { |
| 344 |
|
| 345 |
.execute.cb.before.iter( |
| 346 |
callbacks, |
| 347 |
bst, |
| 348 |
dtrain, |
| 349 |
evals, |
| 350 |
iteration |
| 351 |
) |
| 352 |
|
| 353 |
xgb.iter.update( |
| 354 |
bst = bst, |
| 355 |
dtrain = dtrain, |
| 356 |
iter = iteration - 1, |
| 357 |
objective = objective |
| 358 |
) |
| 359 |
|
| 360 |
bst_evaluation <- NULL |
| 361 |
if (length(evals) > 0) { |
| 362 |
bst_evaluation <- xgb.iter.eval( |
| 363 |
bst = bst, |
| 364 |
evals = evals, |
| 365 |
iter = iteration - 1, |
| 366 |
custom_metric = custom_metric |
| 367 |
) |
| 368 |
} |
| 369 |
|
| 370 |
should_stop <- .execute.cb.after.iter( |
| 371 |
callbacks, |
| 372 |
bst, |
| 373 |
dtrain, |
| 374 |
evals, |
| 375 |
iteration, |
| 376 |
bst_evaluation |
| 377 |
) |
| 378 |
|
| 379 |
if (should_stop) break |
| 380 |
} |
| 381 |
|
| 382 |
cb_outputs <- .execute.cb.after.training( |
| 383 |
callbacks, |
| 384 |
bst, |
| 385 |
dtrain, |
| 386 |
evals, |
| 387 |
iteration, |
| 388 |
bst_evaluation |
| 389 |
) |
| 390 |
|
| 391 |
extra_attrs <- list( |
| 392 |
call = match.call(), |
| 393 |
params = params |
| 394 |
) |
| 395 |
bst <- xgb.reset.Booster(bst) |
| 396 |
curr_attrs <- attributes(bst) |
| 397 |
if (NROW(curr_attrs)) { |
| 398 |
curr_attrs <- curr_attrs[ |
| 399 |
setdiff( |
| 400 |
names(curr_attrs), |
| 401 |
c(names(extra_attrs), names(cb_outputs)) |
| 402 |
) |
| 403 |
] |
| 404 |
} |
| 405 |
curr_attrs <- c(extra_attrs, curr_attrs) |
| 406 |
if (NROW(cb_outputs)) { |
| 407 |
curr_attrs <- c(curr_attrs, cb_outputs) |
| 408 |
} |
| 409 |
attributes(bst) <- curr_attrs |
| 410 |
|
| 411 |
return(bst) |
| 412 |
} |
| 413 |
|
| 414 |
# nolint start: line_length_linter. |
| 415 |
#' @title XGBoost Parameters |
| 416 |
#' @description Convenience function to generate a list of named XGBoost parameters, which |
| 417 |
#' can be passed as argument `params` to [xgb.train()]. See the [online documentation]( |
| 418 |
#' https://xgboost.readthedocs.io/en/stable/parameter.html) for more details. |
| 419 |
#' |
| 420 |
#' The purpose of this function is to enable IDE autocompletions and to provide in-package |
| 421 |
#' documentation for all the possible parameters that XGBoost accepts. The output from this |
| 422 |
#' function is just a regular R list containing the parameters that were set to non-default |
| 423 |
#' values. Note that this function will not perform any validation on the supplied arguments. |
| 424 |
#' |
| 425 |
#' If passing `NULL` for a given parameter (the default for all of them), then the default |
| 426 |
#' value for that parameter will be used. Default values are automatically determined by the |
| 427 |
#' XGBoost core library upon calls to [xgb.train()] or [xgb.cv()], and are subject to change |
| 428 |
#' over XGBoost library versions. Some of them might differ according to the |
| 429 |
#' booster type (e.g. defaults for regularization are different for linear and tree-based boosters). |
| 430 |
#' @return A list with the entries that were passed non-NULL values. It is intended to |
| 431 |
#' be passed as argument `params` to [xgb.train()] or [xgb.cv()]. |
| 432 |
#' @export |
| 433 |
#' @param objective (default=`"reg:squarederror"`) |
| 434 |
#' Specify the learning task and the corresponding learning objective or a custom objective function to be used. |
| 435 |
#' |
| 436 |
#' For custom objective, see [Custom Objective and Evaluation Metric](https://xgboost.readthedocs.io/en/latest/tutorials/custom_metric_obj.html) |
| 437 |
#' and [Custom objective and metric](https://xgboost.readthedocs.io/en/latest/tutorials/saving_model.html#custom-obj-metric) for more information, |
| 438 |
#' along with the end note for function signatures. |
| 439 |
#' |
| 440 |
#' Supported values are: |
| 441 |
#' - `"reg:squarederror"`: regression with squared loss. |
| 442 |
#' - `"reg:squaredlogerror"`: regression with squared log loss \eqn{\frac{1}{2}[log(pred + 1) - log(label + 1)]^2}. All input labels are required to be greater than -1. Also, see metric `rmsle` for possible issue with this objective. |
| 443 |
#' - `"reg:logistic"`: logistic regression, output probability |
| 444 |
#' - `"reg:pseudohubererror"`: regression with Pseudo Huber loss, a twice differentiable alternative to absolute loss. |
| 445 |
#' - `"reg:absoluteerror"`: Regression with L1 error. When tree model is used, leaf value is refreshed after tree construction. If used in distributed training, the leaf value is calculated as the mean value from all workers, which is not guaranteed to be optimal. |
| 446 |
#' |
| 447 |
#' Version added: 1.7.0 |
| 448 |
#' - `"reg:quantileerror"`: Quantile loss, also known as "pinball loss". See later sections for its parameter and [Quantile Regression](https://xgboost.readthedocs.io/en/latest/python/examples/quantile_regression.html#sphx-glr-python-examples-quantile-regression-py) for a worked example. |
| 449 |
#' |
| 450 |
#' Version added: 2.0.0 |
| 451 |
#' - `"binary:logistic"`: logistic regression for binary classification, output probability |
| 452 |
#' - `"binary:logitraw"`: logistic regression for binary classification, output score before logistic transformation |
| 453 |
#' - `"binary:hinge"`: hinge loss for binary classification. This makes predictions of 0 or 1, rather than producing probabilities. |
| 454 |
#' - `"count:poisson"`: Poisson regression for count data, output mean of Poisson distribution. |
| 455 |
#' `"max_delta_step"` is set to 0.7 by default in Poisson regression (used to safeguard optimization) |
| 456 |
#' - `"survival:cox"`: Cox regression for right censored survival time data (negative values are considered right censored). |
| 457 |
#' |
| 458 |
#' Note that predictions are returned on the hazard ratio scale (i.e., as HR = exp(marginal_prediction) in the proportional hazard function `h(t) = h0(t) * HR`). |
| 459 |
#' - `"survival:aft"`: Accelerated failure time model for censored survival time data. |
| 460 |
#' See [Survival Analysis with Accelerated Failure Time](https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html) for details. |
| 461 |
#' - `"multi:softmax"`: set XGBoost to do multiclass classification using the softmax objective, you also need to set num_class(number of classes) |
| 462 |
#' - `"multi:softprob"`: same as softmax, but output a vector of `ndata * nclass`, which can be further reshaped to `ndata * nclass` matrix. The result contains predicted probability of each data point belonging to each class. |
| 463 |
#' - `"rank:ndcg"`: Use LambdaMART to perform pair-wise ranking where the normalized discounted cumulative gain (NDCG) is maximized. This objective supports position debiasing for click data. |
| 464 |
#' - `"rank:map"`: Use LambdaMART to perform pair-wise ranking where the mean average precision (MAP) is maximized |
| 465 |
#' - `"rank:pairwise"`: Use LambdaRank to perform pair-wise ranking using the `ranknet` objective. |
| 466 |
#' - `"reg:gamma"`: gamma regression with log-link. Output is a mean of gamma distribution. It might be useful, e.g., for modeling insurance claims severity, or for any outcome that might be gamma-distributed. |
| 467 |
#' - `"reg:tweedie"`: Tweedie regression with log-link. It might be useful, e.g., for modeling total loss in insurance, or for any outcome that might be tweedie-distributed. |
| 468 |
#' @param verbosity (default=1) |
| 469 |
#' Verbosity of printing messages. Valid values are 0 (silent), 1 (warning), 2 (info), 3 |
| 470 |
#' (debug). Sometimes XGBoost tries to change configurations based on heuristics, which |
| 471 |
#' is displayed as warning message. If there's unexpected behaviour, please try to |
| 472 |
#' increase value of verbosity. |
| 473 |
#' @param nthread (default to maximum number of threads available if not set) |
| 474 |
#' Number of parallel threads used to run XGBoost. When choosing it, please keep thread |
| 475 |
#' contention and hyperthreading in mind. |
| 476 |
#' @param seed Random number seed. If not specified, will take a random seed through R's own RNG engine. |
| 477 |
#' @param booster (default= `"gbtree"`) |
| 478 |
#' Which booster to use. Can be `"gbtree"`, `"gblinear"` or `"dart"`; `"gbtree"` and `"dart"` use tree based models while `"gblinear"` uses linear functions. |
| 479 |
#' @param eta,learning_rate (two aliases for the same parameter) |
| 480 |
#' Step size shrinkage used in update to prevent overfitting. After each boosting step, we can directly get the weights of new features, and `eta` shrinks the feature weights to make the boosting process more conservative. |
| 481 |
#' - range: \eqn{[0,1]} |
| 482 |
#' - default value: 0.3 for tree-based boosters, 0.5 for linear booster. |
| 483 |
#' |
| 484 |
#' Note: should only pass one of `eta` or `learning_rate`. Both refer to the same parameter and there's thus no difference between one or the other. |
| 485 |
#' @param gamma,min_split_loss (two aliases for the same parameter) (for Tree Booster) (default=0, alias: `gamma`) |
| 486 |
#' Minimum loss reduction required to make a further partition on a leaf node of the tree. The larger `min_split_loss` is, the more conservative the algorithm will be. Note that a tree where no splits were made might still contain a single terminal node with a non-zero score. |
| 487 |
#' |
| 488 |
#' range: \eqn{[0, \infty)} |
| 489 |
#' |
| 490 |
#' Note: should only pass one of `gamma` or `min_split_loss`. Both refer to the same parameter and there's thus no difference between one or the other. |
| 491 |
#' @param max_depth (for Tree Booster) (default=6, type=int32) |
| 492 |
#' Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit. 0 indicates no limit on depth. Beware that XGBoost aggressively consumes memory when training a deep tree. `"exact"` tree method requires non-zero value. |
| 493 |
#' |
| 494 |
#' range: \eqn{[0, \infty)} |
| 495 |
#' @param min_child_weight (for Tree Booster) (default=1) |
| 496 |
#' Minimum sum of instance weight (hessian) needed in a child. If the tree partition step results in a leaf node with the sum of instance weight less than `min_child_weight`, then the building process will give up further partitioning. In linear regression task, this simply corresponds to minimum number of instances needed to be in each node. The larger `min_child_weight` is, the more conservative the algorithm will be. |
| 497 |
#' |
| 498 |
#' range: \eqn{[0, \infty)} |
| 499 |
#' @param max_delta_step (for Tree Booster) (default=0) |
| 500 |
#' Maximum delta step we allow each leaf output to be. If the value is set to 0, it means there is no constraint. If it is set to a positive value, it can help making the update step more conservative. Usually this parameter is not needed, but it might help in logistic regression when class is extremely imbalanced. Set it to value of 1-10 might help control the update. |
| 501 |
#' |
| 502 |
#' range: \eqn{[0, \infty)} |
| 503 |
#' @param subsample (for Tree Booster) (default=1) |
| 504 |
#' Subsample ratio of the training instances. Setting it to 0.5 means that XGBoost would randomly sample half of the training data prior to growing trees. and this will prevent overfitting. Subsampling will occur once in every boosting iteration. |
| 505 |
#' |
| 506 |
#' range: \eqn{(0,1]} |
| 507 |
#' @param sampling_method (for Tree Booster) (default= `"uniform"`) |
| 508 |
#' The method to use to sample the training instances. |
| 509 |
#' - `"uniform"`: each training instance has an equal probability of being selected. Typically set |
| 510 |
#' `"subsample"` >= 0.5 for good results. |
| 511 |
#' - `"gradient_based"`: the selection probability for each training instance is proportional to the |
| 512 |
#' \bold{regularized absolute value} of gradients (more specifically, \eqn{\sqrt{g^2+\lambda h^2}}). |
| 513 |
#' `"subsample"` may be set to as low as 0.1 without loss of model accuracy. Note that this |
| 514 |
#' sampling method is only supported when `"tree_method"` is set to `"hist"`; other tree |
| 515 |
#' methods only support `"uniform"` sampling. |
| 516 |
#' @param colsample_bytree,colsample_bylevel,colsample_bynode (for Tree Booster) (default=1) |
| 517 |
#' This is a family of parameters for subsampling of columns. |
| 518 |
#' - All `"colsample_by*"` parameters have a range of \eqn{(0, 1]}, the default value of 1, and specify the fraction of columns to be subsampled. |
| 519 |
#' - `"colsample_bytree"` is the subsample ratio of columns when constructing each tree. Subsampling occurs once for every tree constructed. |
| 520 |
#' - `"colsample_bylevel"` is the subsample ratio of columns for each level. Subsampling occurs once for every new depth level reached in a tree. Columns are subsampled from the set of columns chosen for the current tree. |
| 521 |
#' - `"colsample_bynode"` is the subsample ratio of columns for each node (split). Subsampling occurs once every time a new split is evaluated. Columns are subsampled from the set of columns chosen for the current level. This is not supported by the exact tree method. |
| 522 |
#' - `"colsample_by*"` parameters work cumulatively. For instance, |
| 523 |
#' the combination `{'colsample_bytree'=0.5, 'colsample_bylevel'=0.5, 'colsample_bynode'=0.5}` with 64 features will leave 8 features to choose from at |
| 524 |
#' each split. |
| 525 |
#' |
| 526 |
#' One can set the `"feature_weights"` for DMatrix to |
| 527 |
#' define the probability of each feature being selected when using column sampling. |
| 528 |
#' @param lambda,reg_lambda (two aliases for the same parameter) |
| 529 |
#' |
| 530 |
#' - For tree-based boosters: |
| 531 |
#' - L2 regularization term on weights. Increasing this value will make model more conservative. |
| 532 |
#' - default: 1 |
| 533 |
#' - range: \eqn{[0, \infty]} |
| 534 |
#' - For linear booster: |
| 535 |
#' - L2 regularization term on weights. Increasing this value will make model more conservative. Normalised to number of training examples. |
| 536 |
#' - default: 0 |
| 537 |
#' - range: \eqn{[0, \infty)} |
| 538 |
#' |
| 539 |
#' Note: should only pass one of `lambda` or `reg_lambda`. Both refer to the same parameter and there's thus no difference between one or the other. |
| 540 |
#' @param alpha,reg_alpha (two aliases for the same parameter) |
| 541 |
#' - L1 regularization term on weights. Increasing this value will make model more conservative. |
| 542 |
#' - For the linear booster, it's normalised to number of training examples. |
| 543 |
#' - default: 0 |
| 544 |
#' - range: \eqn{[0, \infty)} |
| 545 |
#' |
| 546 |
#' Note: should only pass one of `alpha` or `reg_alpha`. Both refer to the same parameter and there's thus no difference between one or the other. |
| 547 |
#' @param tree_method (for Tree Booster) (default= `"auto"`) |
| 548 |
#' The tree construction algorithm used in XGBoost. See description in the [reference paper](https://arxiv.org/abs/1603.02754) and [Tree Methods](https://xgboost.readthedocs.io/en/latest/treemethod.html). |
| 549 |
#' |
| 550 |
#' Choices: `"auto"`, `"exact"`, `"approx"`, `"hist"`, this is a combination of commonly |
| 551 |
#' used updaters. For other updaters like `"refresh"`, set the parameter `updater` |
| 552 |
#' directly. |
| 553 |
#' - `"auto"`: Same as the `"hist"` tree method. |
| 554 |
#' - `"exact"`: Exact greedy algorithm. Enumerates all split candidates. |
| 555 |
#' - `"approx"`: Approximate greedy algorithm using quantile sketch and gradient histogram. |
| 556 |
#' - `"hist"`: Faster histogram optimized approximate greedy algorithm. |
| 557 |
#' @param scale_pos_weight (for Tree Booster) (default=1) |
| 558 |
#' Control the balance of positive and negative weights, useful for unbalanced classes. A typical value to consider: `sum(negative instances) / sum(positive instances)`. See [Parameters Tuning](https://xgboost.readthedocs.io/en/latest/tutorials/param_tuning.html) for more discussion. Also, see Higgs Kaggle competition demo for examples: [R](https://github.com/dmlc/xgboost/blob/master/demo/kaggle-higgs/higgs-train.R), [py1](https://github.com/dmlc/xgboost/blob/master/demo/kaggle-higgs/higgs-numpy.py), [py2](https://github.com/dmlc/xgboost/blob/master/demo/kaggle-higgs/higgs-cv.py), [py3](https://github.com/dmlc/xgboost/blob/master/demo/guide-python/cross_validation.py). |
| 559 |
#' @param updater Has different meanings depending on the type of booster. |
| 560 |
#' |
| 561 |
#' - For tree-based boosters: |
| 562 |
#' A comma separated string defining the sequence of tree updaters to run, providing a modular way to construct and to modify the trees. This is an advanced parameter that is usually set automatically, depending on some other parameters. However, it could be also set explicitly by a user. The following updaters exist: |
| 563 |
#' - `"grow_colmaker"`: non-distributed column-based construction of trees. |
| 564 |
#' - `"grow_histmaker"`: distributed tree construction with row-based data splitting based on global proposal of histogram counting. |
| 565 |
#' - `"grow_quantile_histmaker"`: Grow tree using quantized histogram. |
| 566 |
#' - `"grow_gpu_hist"`: Enabled when `tree_method` is set to `"hist"` along with `device="cuda"`. |
| 567 |
#' - `"grow_gpu_approx"`: Enabled when `tree_method` is set to `"approx"` along with `device="cuda"`. |
| 568 |
#' - `"sync"`: synchronizes trees in all distributed nodes. |
| 569 |
#' - `"refresh"`: refreshes tree's statistics and/or leaf values based on the current data. Note that no random subsampling of data rows is performed. |
| 570 |
#' - `"prune"`: prunes the splits where loss < `min_split_loss` (or `gamma`) and nodes that have depth greater than `max_depth`. |
| 571 |
#' |
| 572 |
#' - For `booster="gblinear"`: |
| 573 |
#' (default= `"shotgun"`) Choice of algorithm to fit linear model |
| 574 |
#' - `"shotgun"`: Parallel coordinate descent algorithm based on shotgun algorithm. Uses 'hogwild' parallelism and therefore produces a nondeterministic solution on each run. |
| 575 |
#' - `"coord_descent"`: Ordinary coordinate descent algorithm. Also multithreaded but still produces a deterministic solution. When the `device` parameter is set to `"cuda"` or `"gpu"`, a GPU variant would be used. |
| 576 |
#' @param refresh_leaf (for Tree Booster) (default=1) |
| 577 |
#' This is a parameter of the `"refresh"` updater. When this flag is 1, tree leafs as well as tree nodes' stats are updated. When it is 0, only node stats are updated. |
| 578 |
#' @param grow_policy (for Tree Booster) (default= `"depthwise"`) |
| 579 |
#' - Controls a way new nodes are added to the tree. |
| 580 |
#' - Currently supported only if `tree_method` is set to `"hist"` or `"approx"`. |
| 581 |
#' - Choices: `"depthwise"`, `"lossguide"` |
| 582 |
#' - `"depthwise"`: split at nodes closest to the root. |
| 583 |
#' - `"lossguide"`: split at nodes with highest loss change. |
| 584 |
#' @param max_leaves (for Tree Booster) (default=0, type=int32) |
| 585 |
#' Maximum number of nodes to be added. Not used by `"exact"` tree method. |
| 586 |
#' @param max_bin (for Tree Booster) (default=256, type=int32) |
| 587 |
#' - Only used if `tree_method` is set to `"hist"` or `"approx"`. |
| 588 |
#' - Maximum number of discrete bins to bucket continuous features. |
| 589 |
#' - Increasing this number improves the optimality of splits at the cost of higher computation time. |
| 590 |
#' @param num_parallel_tree (for Tree Booster) (default=1) |
| 591 |
#' Number of parallel trees constructed during each iteration. This option is used to support boosted random forest. |
| 592 |
#' @param monotone_constraints (for Tree Booster) |
| 593 |
#' Constraint of variable monotonicity. See [Monotonic Constraints](https://xgboost.readthedocs.io/en/latest/tutorials/monotonic.html) for more information. |
| 594 |
#' @param interaction_constraints (for Tree Booster) |
| 595 |
#' Constraints for interaction representing permitted interactions. The constraints must |
| 596 |
#' be specified in the form of a nest list, e.g. `list(c(0, 1), c(2, 3, 4))`, where each inner |
| 597 |
#' list is a group of indices of features (base-0 numeration) that are allowed to interact with each other. |
| 598 |
#' See [Feature Interaction Constraints](https://xgboost.readthedocs.io/en/latest/tutorials/feature_interaction_constraint.html) for more information. |
| 599 |
#' @param multi_strategy (for Tree Booster) (default = `"one_output_per_tree"`) |
| 600 |
#' The strategy used for training multi-target models, including multi-target regression |
| 601 |
#' and multi-class classification. See [Multiple Outputs](https://xgboost.readthedocs.io/en/latest/tutorials/multioutput.html) for more information. |
| 602 |
#' - `"one_output_per_tree"`: One model for each target. |
| 603 |
#' - `"multi_output_tree"`: Use multi-target trees. |
| 604 |
#' |
| 605 |
#' Version added: 2.0.0 |
| 606 |
#' |
| 607 |
#' Note: This parameter is working-in-progress. |
| 608 |
#' @param base_score |
| 609 |
#' - The initial prediction score of all instances, global bias |
| 610 |
#' - The parameter is automatically estimated for selected objectives before training. To |
| 611 |
#' disable the estimation, specify a real number argument. |
| 612 |
#' - If `base_margin` is supplied, `base_score` will not be added. |
| 613 |
#' - For sufficient number of iterations, changing this value will not have too much effect. |
| 614 |
#' @param eval_metric (default according to objective) |
| 615 |
#' - Evaluation metrics for validation data, a default metric will be assigned according to objective (rmse for regression, and logloss for classification, `mean average precision` for ``rank:map``, etc.) |
| 616 |
#' - User can add multiple evaluation metrics. |
| 617 |
#' - The choices are listed below: |
| 618 |
#' - `"rmse"`: root mean square error |
| 619 |
#' - `"rmsle"`: root mean square log error: \eqn{\sqrt{\frac{1}{N}[log(pred + 1) - log(label + 1)]^2}}. Default metric of `"reg:squaredlogerror"` objective. This metric reduces errors generated by outliers in dataset. But because `log` function is employed, `"rmsle"` might output `nan` when prediction value is less than -1. See `"reg:squaredlogerror"` for other requirements. |
| 620 |
#' - `"mae"`: mean absolute error. |
| 621 |
#' - `"mape"`: mean absolute percentage error. |
| 622 |
#' - `"mphe"`: mean Pseudo Huber error. Default metric of `"reg:pseudohubererror"` objective. |
| 623 |
#' - `"logloss"`: negative log-likelihood. |
| 624 |
#' - `"error"`: Binary classification error rate. It is calculated as `#(wrong cases)/#(all cases)`. For the predictions, the evaluation will regard the instances with prediction value larger than 0.5 as positive instances, and the others as negative instances. |
| 625 |
#' - `"error@t"`: a different than 0.5 binary classification threshold value could be specified by providing a numerical value through 't'. |
| 626 |
#' - `"merror"`: Multiclass classification error rate. It is calculated as `#(wrong cases)/#(all cases)`. |
| 627 |
#' - `"mlogloss"`: [Multiclass logloss](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html). |
| 628 |
#' - `"auc"`: area under the receiver-operating characteristic curve. |
| 629 |
#' Available for classification and learning-to-rank tasks. |
| 630 |
#' - When used with binary classification, the objective should be `"binary:logistic"` or similar functions that work on probability. |
| 631 |
#' - When used with multi-class classification, objective should be `"multi:softprob"` instead of `"multi:softmax"`, as the latter doesn't output probability. Also the AUC is calculated by 1-vs-rest with reference class weighted by class prevalence. |
| 632 |
#' - When used with LTR task, the AUC is computed by comparing pairs of documents to count correctly sorted pairs. This corresponds to pairwise learning to rank. The implementation has some issues with average AUC around groups and distributed workers not being well-defined. |
| 633 |
#' - On a single machine the AUC calculation is exact. In a distributed environment the AUC is a weighted average over the AUC of training rows on each node - therefore, distributed AUC is an approximation sensitive to the distribution of data across workers. Use another metric in distributed environments if precision and reproducibility are important. |
| 634 |
#' - When input dataset contains only negative or positive samples, the output is `NaN`. The behavior is implementation defined, for instance, `scikit-learn` returns \eqn{0.5} instead. |
| 635 |
#' - `"aucpr"`: area under the PR curve |
| 636 |
#' Available for classification and learning-to-rank tasks. |
| 637 |
#' |
| 638 |
#' After XGBoost 1.6, both of the requirements and restrictions for using `"aucpr"` in classification problem are similar to `"auc"`. For ranking task, only binary relevance label \eqn{y \in [0, 1]} is supported. Different from `"map"` (mean average precision), `"aucpr"` calculates the *interpolated* area under precision recall curve using continuous interpolation. |
| 639 |
#' |
| 640 |
#' - `"pre"`: Precision at \eqn{k}. Supports only learning to rank task. |
| 641 |
#' - `"ndcg"`: normalized discounted cumulative gain |
| 642 |
#' - `"map"`: mean average precision |
| 643 |
#' |
| 644 |
#' The `average precision` is defined as: |
| 645 |
#' |
| 646 |
#' \eqn{AP@l = \frac{1}{min{(l, N)}}\sum^l_{k=1}P@k \cdot I_{(k)}} |
| 647 |
#' |
| 648 |
#' where \eqn{I_{(k)}} is an indicator function that equals to \eqn{1} when the document at \eqn{k} is relevant and \eqn{0} otherwise. The \eqn{P@k} is the precision at \eqn{k}, and \eqn{N} is the total number of relevant documents. Lastly, the `mean average precision` is defined as the weighted average across all queries. |
| 649 |
#' |
| 650 |
#' - `"ndcg@n"`, `"map@n"`, `"pre@n"`: \eqn{n} can be assigned as an integer to cut off the top positions in the lists for evaluation. |
| 651 |
#' - `"ndcg-"`, `"map-"`, `"ndcg@n-"`, `"map@n-"`: In XGBoost, the NDCG and MAP evaluate the score of a list without any positive samples as \eqn{1}. By appending "-" to the evaluation metric name, we can ask XGBoost to evaluate these scores as \eqn{0} to be consistent under some conditions. |
| 652 |
#' - `"poisson-nloglik"`: negative log-likelihood for Poisson regression |
| 653 |
#' - `"gamma-nloglik"`: negative log-likelihood for gamma regression |
| 654 |
#' - `"cox-nloglik"`: negative partial log-likelihood for Cox proportional hazards regression |
| 655 |
#' - `"gamma-deviance"`: residual deviance for gamma regression |
| 656 |
#' - `"tweedie-nloglik"`: negative log-likelihood for Tweedie regression (at a specified value of the `tweedie_variance_power` parameter) |
| 657 |
#' - `"aft-nloglik"`: Negative log likelihood of Accelerated Failure Time model. |
| 658 |
#' See [Survival Analysis with Accelerated Failure Time](https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html) for details. |
| 659 |
#' - `"interval-regression-accuracy"`: Fraction of data points whose predicted labels fall in the interval-censored labels. |
| 660 |
#' Only applicable for interval-censored data. See [Survival Analysis with Accelerated Failure Time](https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html) for details. |
| 661 |
#' @param seed_per_iteration (default= `FALSE`) |
| 662 |
#' Seed PRNG determnisticly via iterator number. |
| 663 |
#' @param device (default= `"cpu"`) |
| 664 |
#' Device for XGBoost to run. User can set it to one of the following values: |
| 665 |
#' - `"cpu"`: Use CPU. |
| 666 |
#' - `"cuda"`: Use a GPU (CUDA device). |
| 667 |
#' - `"cuda:<ordinal>"`: `<ordinal>` is an integer that specifies the ordinal of the GPU (which GPU do you want to use if you have more than one devices). |
| 668 |
#' - `"gpu"`: Default GPU device selection from the list of available and supported devices. Only `"cuda"` devices are supported currently. |
| 669 |
#' - `"gpu:<ordinal>"`: Default GPU device selection from the list of available and supported devices. Only `"cuda"` devices are supported currently. |
| 670 |
#' |
| 671 |
#' For more information about GPU acceleration, see [XGBoost GPU Support](https://xgboost.readthedocs.io/en/latest/gpu/index.html). In distributed environments, ordinal selection is handled by distributed frameworks instead of XGBoost. As a result, using `"cuda:<ordinal>"` will result in an error. Use `"cuda"` instead. |
| 672 |
#' |
| 673 |
#' Version added: 2.0.0 |
| 674 |
#' |
| 675 |
#' Note: if XGBoost was installed from CRAN, it won't have GPU support enabled, thus only `"cpu"` will be available. |
| 676 |
#' To get GPU support, the R package for XGBoost must be installed from source or from the GitHub releases - see |
| 677 |
#' [instructions](https://xgboost.readthedocs.io/en/latest/install.html#r). |
| 678 |
#' @param disable_default_eval_metric (default= `FALSE`) |
| 679 |
#' Flag to disable default metric. Set to 1 or `TRUE` to disable. |
| 680 |
#' @param use_rmm Whether to use RAPIDS Memory Manager (RMM) to allocate cache GPU |
| 681 |
#' memory. The primary memory is always allocated on the RMM pool when XGBoost is built |
| 682 |
#' (compiled) with the RMM plugin enabled. Valid values are `TRUE` and `FALSE`. See |
| 683 |
#' [Using XGBoost with RAPIDS Memory Manager (RMM) plugin](https://xgboost.readthedocs.io/en/latest/python/rmm-examples/index.html) for details. |
| 684 |
#' @param max_cached_hist_node (for Non-Exact Tree Methods) (default = 65536) |
| 685 |
#' Maximum number of cached nodes for histogram. This can be used with the `"hist"` and the |
| 686 |
#' `"approx"` tree methods. |
| 687 |
#' |
| 688 |
#' Version added: 2.0.0 |
| 689 |
#' |
| 690 |
#' - For most of the cases this parameter should not be set except for growing deep |
| 691 |
#' trees. After 3.0, this parameter affects GPU algorithms as well. |
| 692 |
#' @param max_cat_to_onehot (for Non-Exact Tree Methods) |
| 693 |
#' A threshold for deciding whether XGBoost should use one-hot encoding based split for |
| 694 |
#' categorical data. When number of categories is lesser than the threshold then one-hot |
| 695 |
#' encoding is chosen, otherwise the categories will be partitioned into children nodes. |
| 696 |
#' |
| 697 |
#' Version added: 1.6.0 |
| 698 |
#' @param max_cat_threshold (for Non-Exact Tree Methods) |
| 699 |
#' Maximum number of categories considered for each split. Used only by partition-based |
| 700 |
#' splits for preventing over-fitting. |
| 701 |
#' |
| 702 |
#' Version added: 1.7.0 |
| 703 |
#' @param sample_type (for Dart Booster) (default= `"uniform"`) |
| 704 |
#' Type of sampling algorithm. |
| 705 |
#' - `"uniform"`: dropped trees are selected uniformly. |
| 706 |
#' - `"weighted"`: dropped trees are selected in proportion to weight. |
| 707 |
#' @param normalize_type (for Dart Booster) (default= `"tree"`) |
| 708 |
#' Type of normalization algorithm. |
| 709 |
#' - `"tree"`: new trees have the same weight of each of dropped trees. |
| 710 |
#' - Weight of new trees are `1 / (k + learning_rate)`. |
| 711 |
#' - Dropped trees are scaled by a factor of `k / (k + learning_rate)`. |
| 712 |
#' - `"forest"`: new trees have the same weight of sum of dropped trees (forest). |
| 713 |
#' - Weight of new trees are `1 / (1 + learning_rate)`. |
| 714 |
#' - Dropped trees are scaled by a factor of `1 / (1 + learning_rate)`. |
| 715 |
#' @param rate_drop (for Dart Booster) (default=0.0) |
| 716 |
#' Dropout rate (a fraction of previous trees to drop during the dropout). |
| 717 |
#' |
| 718 |
#' range: \eqn{[0.0, 1.0]} |
| 719 |
#' @param one_drop (for Dart Booster) (default=0) |
| 720 |
#' When this flag is enabled, at least one tree is always dropped during the dropout (allows Binomial-plus-one or epsilon-dropout from the original DART paper). |
| 721 |
#' @param skip_drop (for Dart Booster) (default=0.0) |
| 722 |
#' Probability of skipping the dropout procedure during a boosting iteration. |
| 723 |
#' - If a dropout is skipped, new trees are added in the same manner as `"gbtree"`. |
| 724 |
#' - Note that non-zero `skip_drop` has higher priority than `rate_drop` or `one_drop`. |
| 725 |
#' |
| 726 |
#' range: \eqn{[0.0, 1.0]} |
| 727 |
#' @param feature_selector (for Linear Booster) (default= `"cyclic"`) |
| 728 |
#' Feature selection and ordering method |
| 729 |
#' - `"cyclic"`: Deterministic selection by cycling through features one at a time. |
| 730 |
#' - `"shuffle"`: Similar to `"cyclic"` but with random feature shuffling prior to each update. |
| 731 |
#' - `"random"`: A random (with replacement) coordinate selector. |
| 732 |
#' - `"greedy"`: Select coordinate with the greatest gradient magnitude. It has `O(num_feature^2)` complexity. It is fully deterministic. It allows restricting the selection to `top_k` features per group with the largest magnitude of univariate weight change, by setting the `top_k` parameter. Doing so would reduce the complexity to `O(num_feature*top_k)`. |
| 733 |
#' - `"thrifty"`: Thrifty, approximately-greedy feature selector. Prior to cyclic updates, reorders features in descending magnitude of their univariate weight changes. This operation is multithreaded and is a linear complexity approximation of the quadratic greedy selection. It allows restricting the selection to `top_k` features per group with the largest magnitude of univariate weight change, by setting the `top_k` parameter. |
| 734 |
#' @param top_k (for Linear Booster) (default=0) |
| 735 |
#' The number of top features to select in `greedy` and `thrifty` feature selector. The value of 0 means using all the features. |
| 736 |
#' @param num_class Number of classes when using multi-class classification objectives (e.g. `objective="multi:softprob"`) |
| 737 |
#' @param tweedie_variance_power (for Tweedie Regression (`"objective=reg:tweedie"`)) (default=1.5) |
| 738 |
#' - Parameter that controls the variance of the Tweedie distribution `var(y) ~ E(y)^tweedie_variance_power` |
| 739 |
#' - range: \eqn{(1,2)} |
| 740 |
#' - Set closer to 2 to shift towards a gamma distribution |
| 741 |
#' - Set closer to 1 to shift towards a Poisson distribution. |
| 742 |
#' @param huber_slope (for using Pseudo-Huber (`"reg:pseudohubererror`")) (default = 1.0) |
| 743 |
#' A parameter used for Pseudo-Huber loss to define the \eqn{\delta} term. |
| 744 |
#' @param quantile_alpha (for using Quantile Loss (`"reg:quantileerror"`)) |
| 745 |
#' A scalar or a list of targeted quantiles (passed as a numeric vector). |
| 746 |
#' |
| 747 |
#' Version added: 2.0.0 |
| 748 |
#' @param aft_loss_distribution (when using AFT Survival Loss (`"survival:aft"`) and Negative Log Likelihood of AFT metric (`"aft-nloglik"`)) |
| 749 |
#' Probability Density Function, `"normal"`, `"logistic"`, or `"extreme"`. |
| 750 |
#' @param aft_loss_distribution_scale (when using AFT Survival Loss (`"survival:aft"`) and Negative Log Likelihood of AFT metric (`"aft-nloglik"`)) |
| 751 |
#' Scaling factor for the AFT distribution. Range: \eqn{(0, \infty)}. |
| 752 |
#' @param lambdarank_pair_method (for learning to rank (`"rank:ndcg"`, `"rank:map"`, `"rank:pairwise"`)) (default = `"topk"`) |
| 753 |
#' How to construct pairs for pair-wise learning. |
| 754 |
#' - `"mean"`: Sample `lambdarank_num_pair_per_sample` pairs for each document in the query list. |
| 755 |
#' - `"topk"`: Focus on top-`lambdarank_num_pair_per_sample` documents. Construct \eqn{|query|} pairs for each document at the top-`lambdarank_num_pair_per_sample` ranked by the model. |
| 756 |
#' @param lambdarank_num_pair_per_sample (for learning to rank (`"rank:ndcg"`, `"rank:map"`, `"rank:pairwise"`)) |
| 757 |
#' It specifies the number of pairs sampled for each document when pair method is `"mean"`, or the truncation level for queries when the pair method is `"topk"`. For example, to train with `ndcg@6`, set `"lambdarank_num_pair_per_sample"` to \eqn{6} and `lambdarank_pair_method` to `"topk"`. |
| 758 |
#' |
| 759 |
#' range = \eqn{[1, \infty)} |
| 760 |
#' @param lambdarank_normalization (for learning to rank (`"rank:ndcg"`, `"rank:map"`, `"rank:pairwise"`)) (default = `TRUE`) |
| 761 |
#' Whether to normalize the leaf value by lambda gradient. This can sometimes stagnate the training progress. |
| 762 |
#' |
| 763 |
#' Version added: 2.1.0 |
| 764 |
#' |
| 765 |
#' @param lambdarank_score_normalization |
| 766 |
#' |
| 767 |
#' Whether to normalize the delta metric by the difference of prediction scores. This can |
| 768 |
#' sometimes stagnate the training progress. With pairwise ranking, we can normalize the |
| 769 |
#' gradient using the difference between two samples in each pair to reduce influence from |
| 770 |
#' the pairs that have large difference in ranking scores. This can help us regularize the |
| 771 |
#' model to reduce bias and prevent overfitting. Similar to other regularization |
| 772 |
#' techniques, this might prevent training from converging. |
| 773 |
#' |
| 774 |
#' There was no normalization before 2.0. In 2.0 and later versions this is used by |
| 775 |
#' default. In 3.0, we made this an option that users can disable. |
| 776 |
#' |
| 777 |
#' Version added: 3.0.0 |
| 778 |
#' |
| 779 |
#' @param lambdarank_unbiased (for learning to rank (`"rank:ndcg"`, `"rank:map"`, `"rank:pairwise"`)) (default = `FALSE`) |
| 780 |
#' Specify whether do we need to debias input click data. |
| 781 |
#' @param lambdarank_bias_norm (for learning to rank (`"rank:ndcg"`, `"rank:map"`, `"rank:pairwise"`)) (default = 2.0) |
| 782 |
#' \eqn{L_p} normalization for position debiasing, default is \eqn{L_2}. Only relevant when `lambdarank_unbiased` is set to `TRUE`. |
| 783 |
#' @param ndcg_exp_gain (for learning to rank (`"rank:ndcg"`, `"rank:map"`, `"rank:pairwise"`)) (default = `TRUE`) |
| 784 |
#' Whether we should use exponential gain function for `NDCG`. There are two forms of gain function for `NDCG`, one is using relevance value directly while the other is using\eqn{2^{rel} - 1} to emphasize on retrieving relevant documents. When `ndcg_exp_gain` is `TRUE` (the default), relevance degree cannot be greater than 31. |
| 785 |
xgb.params <- function( |
| 786 |
objective = NULL, |
| 787 |
verbosity = NULL, |
| 788 |
nthread = NULL, |
| 789 |
seed = NULL, |
| 790 |
booster = NULL, |
| 791 |
eta = NULL, |
| 792 |
learning_rate = NULL, |
| 793 |
gamma = NULL, |
| 794 |
min_split_loss = NULL, |
| 795 |
max_depth = NULL, |
| 796 |
min_child_weight = NULL, |
| 797 |
max_delta_step = NULL, |
| 798 |
subsample = NULL, |
| 799 |
sampling_method = NULL, |
| 800 |
colsample_bytree = NULL, |
| 801 |
colsample_bylevel = NULL, |
| 802 |
colsample_bynode = NULL, |
| 803 |
lambda = NULL, |
| 804 |
reg_lambda = NULL, |
| 805 |
alpha = NULL, |
| 806 |
reg_alpha = NULL, |
| 807 |
tree_method = NULL, |
| 808 |
scale_pos_weight = NULL, |
| 809 |
updater = NULL, |
| 810 |
refresh_leaf = NULL, |
| 811 |
grow_policy = NULL, |
| 812 |
max_leaves = NULL, |
| 813 |
max_bin = NULL, |
| 814 |
num_parallel_tree = NULL, |
| 815 |
monotone_constraints = NULL, |
| 816 |
interaction_constraints = NULL, |
| 817 |
multi_strategy = NULL, |
| 818 |
base_score = NULL, |
| 819 |
eval_metric = NULL, |
| 820 |
seed_per_iteration = NULL, |
| 821 |
device = NULL, |
| 822 |
disable_default_eval_metric = NULL, |
| 823 |
use_rmm = NULL, |
| 824 |
max_cached_hist_node = NULL, |
| 825 |
max_cat_to_onehot = NULL, |
| 826 |
max_cat_threshold = NULL, |
| 827 |
sample_type = NULL, |
| 828 |
normalize_type = NULL, |
| 829 |
rate_drop = NULL, |
| 830 |
one_drop = NULL, |
| 831 |
skip_drop = NULL, |
| 832 |
feature_selector = NULL, |
| 833 |
top_k = NULL, |
| 834 |
num_class = NULL, |
| 835 |
tweedie_variance_power = NULL, |
| 836 |
huber_slope = NULL, |
| 837 |
quantile_alpha = NULL, |
| 838 |
aft_loss_distribution = NULL, |
| 839 |
aft_loss_distribution_scale = NULL, |
| 840 |
lambdarank_pair_method = NULL, |
| 841 |
lambdarank_num_pair_per_sample = NULL, |
| 842 |
lambdarank_normalization = NULL, |
| 843 |
lambdarank_score_normalization = NULL, |
| 844 |
lambdarank_unbiased = NULL, |
| 845 |
lambdarank_bias_norm = NULL, |
| 846 |
ndcg_exp_gain = NULL |
| 847 |
) { |
| 848 |
# nolint end |
| 849 |
out <- as.list(environment()) |
| 850 |
out <- out[!sapply(out, is.null)] |
| 851 |
return(out) |
| 852 |
} |