| 1 |
# |
| 2 |
# This file is for the low level reusable utility functions |
| 3 |
# that are not supposed to be visible to a user. |
| 4 |
# |
| 5 |
|
| 6 |
# |
| 7 |
# General helper utilities ---------------------------------------------------- |
| 8 |
# |
| 9 |
|
| 10 |
# SQL-style NVL shortcut. |
| 11 |
NVL <- function(x, val) { |
| 12 |
if (is.null(x)) |
| 13 |
return(val) |
| 14 |
if (is.vector(x)) { |
| 15 |
x[is.na(x)] <- val |
| 16 |
return(x) |
| 17 |
} |
| 18 |
if (typeof(x) == 'closure') |
| 19 |
return(x) |
| 20 |
stop("typeof(x) == ", typeof(x), " is not supported by NVL") |
| 21 |
} |
| 22 |
|
| 23 |
# List of classification and ranking objectives |
| 24 |
.CLASSIFICATION_OBJECTIVES <- function() { |
| 25 |
return(c('binary:logistic', 'binary:logitraw', 'binary:hinge', 'multi:softmax', |
| 26 |
'multi:softprob', 'rank:pairwise', 'rank:ndcg', 'rank:map')) |
| 27 |
} |
| 28 |
|
| 29 |
.RANKING_OBJECTIVES <- function() { |
| 30 |
return(c('rank:pairwise', 'rank:ndcg', 'rank:map')) |
| 31 |
} |
| 32 |
|
| 33 |
.OBJECTIVES_NON_DEFAULT_MODE <- function() { |
| 34 |
return(c("reg:logistic", "binary:logitraw", "multi:softmax")) |
| 35 |
} |
| 36 |
|
| 37 |
.BINARY_CLASSIF_OBJECTIVES <- function() { |
| 38 |
return(c("binary:logistic", "binary:hinge")) |
| 39 |
} |
| 40 |
|
| 41 |
.MULTICLASS_CLASSIF_OBJECTIVES <- function() { |
| 42 |
return("multi:softprob") |
| 43 |
} |
| 44 |
|
| 45 |
.SURVIVAL_RIGHT_CENSORING_OBJECTIVES <- function() { # nolint |
| 46 |
return(c("survival:cox", "survival:aft")) |
| 47 |
} |
| 48 |
|
| 49 |
.SURVIVAL_ALL_CENSORING_OBJECTIVES <- function() { # nolint |
| 50 |
return("survival:aft") |
| 51 |
} |
| 52 |
|
| 53 |
.REGRESSION_OBJECTIVES <- function() { |
| 54 |
return(c( |
| 55 |
"reg:squarederror", "reg:squaredlogerror", "reg:logistic", "reg:pseudohubererror", |
| 56 |
"reg:absoluteerror", "reg:quantileerror", "count:poisson", "reg:gamma", "reg:tweedie" |
| 57 |
)) |
| 58 |
} |
| 59 |
|
| 60 |
.MULTI_TARGET_OBJECTIVES <- function() { |
| 61 |
return(c( |
| 62 |
"reg:squarederror", "reg:squaredlogerror", "reg:logistic", "reg:pseudohubererror", |
| 63 |
"reg:quantileerror", "reg:gamma" |
| 64 |
)) |
| 65 |
} |
| 66 |
|
| 67 |
|
| 68 |
# |
| 69 |
# Low-level functions for boosting -------------------------------------------- |
| 70 |
# |
| 71 |
|
| 72 |
# Merges booster params with whatever is provided in ... |
| 73 |
# plus runs some checks |
| 74 |
check.booster.params <- function(params) { |
| 75 |
if (!identical(class(params), "list")) |
| 76 |
stop("params must be a list") |
| 77 |
|
| 78 |
# in R interface, allow for '.' instead of '_' in parameter names |
| 79 |
names(params) <- gsub(".", "_", names(params), fixed = TRUE) |
| 80 |
|
| 81 |
# providing a parameter multiple times makes sense only for 'eval_metric' |
| 82 |
name_freqs <- table(names(params)) |
| 83 |
multi_names <- setdiff(names(name_freqs[name_freqs > 1]), 'eval_metric') |
| 84 |
if (length(multi_names) > 0) { |
| 85 |
warning("The following parameters were provided multiple times:\n\t", |
| 86 |
paste(multi_names, collapse = ', '), "\n Only the last value for each of them will be used.\n") |
| 87 |
# While xgboost internals would choose the last value for a multiple-times parameter, |
| 88 |
# enforce it here in R as well (b/c multi-parameters might be used further in R code, |
| 89 |
# and R takes the 1st value when multiple elements with the same name are present in a list). |
| 90 |
for (n in multi_names) { |
| 91 |
del_idx <- which(n == names(params)) |
| 92 |
del_idx <- del_idx[-length(del_idx)] |
| 93 |
params[[del_idx]] <- NULL |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
# for multiclass, expect num_class to be set |
| 98 |
if (typeof(params[['objective']]) == "character" && |
| 99 |
startsWith(NVL(params[['objective']], 'x'), 'multi:') && |
| 100 |
as.numeric(NVL(params[['num_class']], 0)) < 2) { |
| 101 |
stop("'num_class' > 1 parameter must be set for multiclass classification") |
| 102 |
} |
| 103 |
|
| 104 |
# monotone_constraints parser |
| 105 |
if (!is.null(params[['monotone_constraints']]) && |
| 106 |
typeof(params[['monotone_constraints']]) != "character") { |
| 107 |
vec2str <- paste(params[['monotone_constraints']], collapse = ',') |
| 108 |
vec2str <- paste0('(', vec2str, ')') |
| 109 |
params[['monotone_constraints']] <- vec2str |
| 110 |
} |
| 111 |
|
| 112 |
# interaction constraints parser (convert from list of column indices to string) |
| 113 |
if (!is.null(params[['interaction_constraints']]) && |
| 114 |
typeof(params[['interaction_constraints']]) != "character") { |
| 115 |
# check input class |
| 116 |
if (!identical(class(params[['interaction_constraints']]), 'list')) stop('interaction_constraints should be class list') |
| 117 |
if (!all(unique(sapply(params[['interaction_constraints']], class)) %in% c('numeric', 'integer'))) { |
| 118 |
stop('interaction_constraints should be a list of numeric/integer vectors') |
| 119 |
} |
| 120 |
|
| 121 |
# recast parameter as string |
| 122 |
interaction_constraints <- sapply(params[['interaction_constraints']], function(x) paste0('[', paste(x, collapse = ','), ']')) |
| 123 |
params[['interaction_constraints']] <- paste0('[', paste(interaction_constraints, collapse = ','), ']') |
| 124 |
} |
| 125 |
|
| 126 |
# for evaluation metrics, should generate multiple entries per metric |
| 127 |
if (NROW(params[['eval_metric']]) > 1) { |
| 128 |
eval_metrics <- as.list(params[["eval_metric"]]) |
| 129 |
names(eval_metrics) <- rep("eval_metric", length(eval_metrics)) |
| 130 |
params_without_ev_metrics <- within(params, rm("eval_metric")) |
| 131 |
params <- c(params_without_ev_metrics, eval_metrics) |
| 132 |
} |
| 133 |
return(params) |
| 134 |
} |
| 135 |
|
| 136 |
|
| 137 |
# Performs some checks related to custom objective function. |
| 138 |
check.custom.obj <- function(params, objective) { |
| 139 |
if (!is.null(params[['objective']]) && !is.null(objective)) |
| 140 |
stop("Setting objectives in 'params' and 'objective' at the same time is not allowed") |
| 141 |
|
| 142 |
if (!is.null(objective) && typeof(objective) != 'closure') { |
| 143 |
if (is.character(objective)) { |
| 144 |
msg <- paste( |
| 145 |
"Argument 'objective' is only for custom objectives.", |
| 146 |
"For built-in objectives, pass the objective under 'params'.", |
| 147 |
sep = " " |
| 148 |
) |
| 149 |
error_on_deprecated <- getOption("xgboost.strict_mode", default = FALSE) |
| 150 |
if (error_on_deprecated) { |
| 151 |
stop(msg) |
| 152 |
} else { |
| 153 |
warning(msg, " This warning will become an error in a future version.") |
| 154 |
} |
| 155 |
params$objective <- objective |
| 156 |
return(list(params = params, objective = NULL)) |
| 157 |
} |
| 158 |
stop("'objective' must be a function") |
| 159 |
} |
| 160 |
|
| 161 |
# handle the case when custom objective function was provided through params |
| 162 |
if (!is.null(params[['objective']]) && |
| 163 |
typeof(params$objective) == 'closure') { |
| 164 |
objective <- params$objective |
| 165 |
params$objective <- NULL |
| 166 |
} |
| 167 |
return(list(params = params, objective = objective)) |
| 168 |
} |
| 169 |
|
| 170 |
# Performs some checks related to custom evaluation function. |
| 171 |
check.custom.eval <- function(params, custom_metric, maximize, early_stopping_rounds, callbacks) { |
| 172 |
if (!is.null(params[['eval_metric']]) && !is.null(custom_metric)) |
| 173 |
stop("Setting evaluation metrics in 'params' and 'custom_metric' at the same time is not allowed") |
| 174 |
|
| 175 |
if (!is.null(custom_metric) && typeof(custom_metric) != 'closure') |
| 176 |
stop("'custom_metric' must be a function") |
| 177 |
|
| 178 |
# handle a situation when custom eval function was provided through params |
| 179 |
if (!is.null(params[['eval_metric']]) && |
| 180 |
typeof(params$eval_metric) == 'closure') { |
| 181 |
custom_metric <- params$eval_metric |
| 182 |
params$eval_metric <- NULL |
| 183 |
} |
| 184 |
|
| 185 |
# require maximize to be set when custom metric and early stopping are used together |
| 186 |
if (!is.null(custom_metric) && |
| 187 |
is.null(maximize) && ( |
| 188 |
!is.null(early_stopping_rounds) || |
| 189 |
has.callbacks(callbacks, "early_stop"))) |
| 190 |
stop("Please set 'maximize' to indicate whether the evaluation metric needs to be maximized or not") |
| 191 |
|
| 192 |
return(list(params = params, custom_metric = custom_metric)) |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
# Update a booster handle for an iteration with dtrain data |
| 197 |
xgb.iter.update <- function(bst, dtrain, iter, objective) { |
| 198 |
if (!inherits(dtrain, "xgb.DMatrix")) { |
| 199 |
stop("dtrain must be of xgb.DMatrix class") |
| 200 |
} |
| 201 |
handle <- xgb.get.handle(bst) |
| 202 |
|
| 203 |
if (is.null(objective)) { |
| 204 |
.Call(XGBoosterUpdateOneIter_R, handle, as.integer(iter), dtrain) |
| 205 |
} else { |
| 206 |
pred <- predict( |
| 207 |
bst, |
| 208 |
dtrain, |
| 209 |
outputmargin = TRUE, |
| 210 |
training = TRUE |
| 211 |
) |
| 212 |
gpair <- objective(pred, dtrain) |
| 213 |
n_samples <- dim(dtrain)[1L] |
| 214 |
grad <- gpair$grad |
| 215 |
hess <- gpair$hess |
| 216 |
|
| 217 |
if ((is.matrix(grad) && dim(grad)[1L] != n_samples) || |
| 218 |
(is.vector(grad) && length(grad) != n_samples) || |
| 219 |
(is.vector(grad) != is.vector(hess))) { |
| 220 |
warning(paste( |
| 221 |
"Since 2.1.0, the shape of the gradient and hessian is required to be ", |
| 222 |
"(n_samples, n_targets) or (n_samples, n_classes). Will reshape assuming ", |
| 223 |
"column-major order.", |
| 224 |
sep = "" |
| 225 |
)) |
| 226 |
grad <- matrix(grad, nrow = n_samples) |
| 227 |
hess <- matrix(hess, nrow = n_samples) |
| 228 |
} |
| 229 |
|
| 230 |
.Call( |
| 231 |
XGBoosterTrainOneIter_R, handle, dtrain, iter, grad, hess |
| 232 |
) |
| 233 |
} |
| 234 |
return(TRUE) |
| 235 |
} |
| 236 |
|
| 237 |
|
| 238 |
# Evaluate one iteration. |
| 239 |
# Returns a named vector of evaluation metrics |
| 240 |
# with the names in a 'datasetname-metricname' format. |
| 241 |
xgb.iter.eval <- function(bst, evals, iter, custom_metric) { |
| 242 |
handle <- xgb.get.handle(bst) |
| 243 |
|
| 244 |
if (length(evals) == 0) |
| 245 |
return(NULL) |
| 246 |
|
| 247 |
evnames <- names(evals) |
| 248 |
if (is.null(custom_metric)) { |
| 249 |
msg <- .Call(XGBoosterEvalOneIter_R, handle, as.integer(iter), evals, as.list(evnames)) |
| 250 |
mat <- matrix(strsplit(msg, '\\s+|:')[[1]][-1], nrow = 2) |
| 251 |
res <- structure(as.numeric(mat[2, ]), names = mat[1, ]) |
| 252 |
} else { |
| 253 |
res <- sapply(seq_along(evals), function(j) { |
| 254 |
w <- evals[[j]] |
| 255 |
## predict using all trees |
| 256 |
preds <- predict(bst, w, outputmargin = TRUE, iterationrange = "all") |
| 257 |
eval_res <- custom_metric(preds, w) |
| 258 |
out <- eval_res$value |
| 259 |
names(out) <- paste0(evnames[j], "-", eval_res$metric) |
| 260 |
out |
| 261 |
}) |
| 262 |
} |
| 263 |
return(res) |
| 264 |
} |
| 265 |
|
| 266 |
|
| 267 |
# |
| 268 |
# Helper functions for cross validation --------------------------------------- |
| 269 |
# |
| 270 |
|
| 271 |
# Possibly convert the labels into factors, depending on the objective. |
| 272 |
# The labels are converted into factors only when the given objective refers to the classification |
| 273 |
# or ranking tasks. |
| 274 |
convert.labels <- function(labels, objective_name) { |
| 275 |
if (objective_name %in% .CLASSIFICATION_OBJECTIVES()) { |
| 276 |
return(as.factor(labels)) |
| 277 |
} else { |
| 278 |
return(labels) |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
# Generates random (stratified if needed) CV folds |
| 283 |
generate.cv.folds <- function(nfold, nrows, stratified, label, group, params) { |
| 284 |
if (NROW(group)) { |
| 285 |
if (stratified) { |
| 286 |
warning( |
| 287 |
paste0( |
| 288 |
"Stratified splitting is not supported when using 'group' attribute.", |
| 289 |
" Will use unstratified splitting." |
| 290 |
) |
| 291 |
) |
| 292 |
} |
| 293 |
return(generate.group.folds(nfold, group)) |
| 294 |
} |
| 295 |
objective <- params$objective |
| 296 |
if (stratified && !is.character(objective)) { |
| 297 |
warning("Will use unstratified splitting (custom objective used)") |
| 298 |
stratified <- FALSE |
| 299 |
} |
| 300 |
# cannot stratify if label is NULL |
| 301 |
if (stratified && is.null(label)) { |
| 302 |
warning("Will use unstratified splitting (no 'labels' available)") |
| 303 |
stratified <- FALSE |
| 304 |
} |
| 305 |
|
| 306 |
# cannot do it for rank |
| 307 |
if (is.character(objective) && strtrim(objective, 5) == 'rank:') { |
| 308 |
stop("\n\tAutomatic generation of CV-folds is not implemented for ranking without 'group' field!\n", |
| 309 |
"\tConsider providing pre-computed CV-folds through the 'folds=' parameter.\n") |
| 310 |
} |
| 311 |
# shuffle |
| 312 |
rnd_idx <- sample.int(nrows) |
| 313 |
if (stratified && length(label) == length(rnd_idx)) { |
| 314 |
y <- label[rnd_idx] |
| 315 |
# - For classification, need to convert y labels to factor before making the folds, |
| 316 |
# and then do stratification by factor levels. |
| 317 |
# - For regression, leave y numeric and do stratification by quantiles. |
| 318 |
if (is.character(objective)) { |
| 319 |
y <- convert.labels(y, objective) |
| 320 |
} |
| 321 |
folds <- xgb.createFolds(y = y, k = nfold) |
| 322 |
} else { |
| 323 |
# make simple non-stratified folds |
| 324 |
kstep <- length(rnd_idx) %/% nfold |
| 325 |
folds <- list() |
| 326 |
for (i in seq_len(nfold - 1)) { |
| 327 |
folds[[i]] <- rnd_idx[seq_len(kstep)] |
| 328 |
rnd_idx <- rnd_idx[-seq_len(kstep)] |
| 329 |
} |
| 330 |
folds[[nfold]] <- rnd_idx |
| 331 |
} |
| 332 |
return(folds) |
| 333 |
} |
| 334 |
|
| 335 |
generate.group.folds <- function(nfold, group) { |
| 336 |
ngroups <- length(group) - 1 |
| 337 |
if (ngroups < nfold) { |
| 338 |
stop("DMatrix has fewer groups than folds.") |
| 339 |
} |
| 340 |
seq_groups <- seq_len(ngroups) |
| 341 |
indices <- lapply(seq_groups, function(gr) seq(group[gr] + 1, group[gr + 1])) |
| 342 |
assignments <- base::split(seq_groups, as.integer(seq_groups %% nfold)) |
| 343 |
assignments <- unname(assignments) |
| 344 |
|
| 345 |
out <- vector("list", nfold) |
| 346 |
randomized_groups <- sample(ngroups) |
| 347 |
for (idx in seq_len(nfold)) { |
| 348 |
groups_idx_test <- randomized_groups[assignments[[idx]]] |
| 349 |
groups_test <- indices[groups_idx_test] |
| 350 |
idx_test <- unlist(groups_test) |
| 351 |
attributes(idx_test)$group_test <- lengths(groups_test) |
| 352 |
attributes(idx_test)$group_train <- lengths(indices[-groups_idx_test]) |
| 353 |
out[[idx]] <- idx_test |
| 354 |
} |
| 355 |
return(out) |
| 356 |
} |
| 357 |
|
| 358 |
# Creates CV folds stratified by the values of y. |
| 359 |
# It was borrowed from caret::createFolds and simplified |
| 360 |
# by always returning an unnamed list of fold indices. |
| 361 |
xgb.createFolds <- function(y, k) { |
| 362 |
if (is.numeric(y)) { |
| 363 |
## Group the numeric data based on their magnitudes |
| 364 |
## and sample within those groups. |
| 365 |
|
| 366 |
## When the number of samples is low, we may have |
| 367 |
## issues further slicing the numeric data into |
| 368 |
## groups. The number of groups will depend on the |
| 369 |
## ratio of the number of folds to the sample size. |
| 370 |
## At most, we will use quantiles. If the sample |
| 371 |
## is too small, we just do regular unstratified |
| 372 |
## CV |
| 373 |
cuts <- floor(length(y) / k) |
| 374 |
if (cuts < 2) cuts <- 2 |
| 375 |
if (cuts > 5) cuts <- 5 |
| 376 |
y <- cut(y, |
| 377 |
unique(stats::quantile(y, probs = seq(0, 1, length = cuts))), |
| 378 |
include.lowest = TRUE) |
| 379 |
} |
| 380 |
|
| 381 |
if (k < length(y)) { |
| 382 |
## reset levels so that the possible levels and |
| 383 |
## the levels in the vector are the same |
| 384 |
y <- factor(as.character(y)) |
| 385 |
numInClass <- table(y) |
| 386 |
foldVector <- vector(mode = "integer", length(y)) |
| 387 |
|
| 388 |
## For each class, balance the fold allocation as far |
| 389 |
## as possible, then resample the remainder. |
| 390 |
## The final assignment of folds is also randomized. |
| 391 |
for (i in seq_along(numInClass)) { |
| 392 |
## create a vector of integers from 1:k as many times as possible without |
| 393 |
## going over the number of samples in the class. Note that if the number |
| 394 |
## of samples in a class is less than k, nothing is produced here. |
| 395 |
seqVector <- rep(seq_len(k), numInClass[i] %/% k) |
| 396 |
## add enough random integers to get length(seqVector) == numInClass[i] |
| 397 |
if (numInClass[i] %% k > 0) seqVector <- c(seqVector, sample.int(k, numInClass[i] %% k)) |
| 398 |
## shuffle the integers for fold assignment and assign to this classes's data |
| 399 |
## seqVector[sample.int(length(seqVector))] is used to handle length(seqVector) == 1 |
| 400 |
foldVector[y == dimnames(numInClass)$y[i]] <- seqVector[sample.int(length(seqVector))] |
| 401 |
} |
| 402 |
} else { |
| 403 |
foldVector <- seq(along = y) |
| 404 |
} |
| 405 |
|
| 406 |
out <- split(seq(along = y), foldVector) |
| 407 |
names(out) <- NULL |
| 408 |
out |
| 409 |
} |
| 410 |
|
| 411 |
#' Model Serialization and Compatibility |
| 412 |
#' |
| 413 |
#' @description |
| 414 |
#' When it comes to serializing XGBoost models, it's possible to use R serializers such as |
| 415 |
#' [save()] or [saveRDS()] to serialize an XGBoost model object, but XGBoost also provides |
| 416 |
#' its own serializers with better compatibility guarantees, which allow loading |
| 417 |
#' said models in other language bindings of XGBoost. |
| 418 |
#' |
| 419 |
#' Note that an `xgb.Booster` object (**as produced by [xgb.train()]**, see rest of the doc |
| 420 |
#' for objects produced by [xgboost()]), outside of its core components, might also keep: |
| 421 |
#' - Additional model configuration (accessible through [xgb.config()]), which includes |
| 422 |
#' model fitting parameters like `max_depth` and runtime parameters like `nthread`. |
| 423 |
#' These are not necessarily useful for prediction/importance/plotting. |
| 424 |
#' - Additional R specific attributes - e.g. results of callbacks, such as evaluation logs, |
| 425 |
#' which are kept as a `data.table` object, accessible through |
| 426 |
#' `attributes(model)$evaluation_log` if present. |
| 427 |
#' |
| 428 |
#' The first one (configurations) does not have the same compatibility guarantees as |
| 429 |
#' the model itself, including attributes that are set and accessed through |
| 430 |
#' [xgb.attributes()] - that is, such configuration might be lost after loading the |
| 431 |
#' booster in a different XGBoost version, regardless of the serializer that was used. |
| 432 |
#' These are saved when using [saveRDS()], but will be discarded if loaded into an |
| 433 |
#' incompatible XGBoost version. They are not saved when using XGBoost's |
| 434 |
#' serializers from its public interface including [xgb.save()] and [xgb.save.raw()]. |
| 435 |
#' |
| 436 |
#' The second ones (R attributes) are not part of the standard XGBoost model structure, |
| 437 |
#' and thus are not saved when using XGBoost's own serializers. These attributes are |
| 438 |
#' only used for informational purposes, such as keeping track of evaluation metrics as |
| 439 |
#' the model was fit, or saving the R call that produced the model, but are otherwise |
| 440 |
#' not used for prediction / importance / plotting / etc. |
| 441 |
#' These R attributes are only preserved when using R's serializers. |
| 442 |
#' |
| 443 |
#' In addition to the regular `xgb.Booster` objects produced by [xgb.train()], the |
| 444 |
#' function [xgboost()] produces objects with a different subclass `xgboost` (which |
| 445 |
#' inherits from `xgb.Booster`), which keeps other additional metadata as R attributes |
| 446 |
#' such as class names in classification problems, and which has a dedicated `predict` |
| 447 |
#' method that uses different defaults and takes different argument names. XGBoost's |
| 448 |
#' own serializers can work with this `xgboost` class, but as they do not keep R |
| 449 |
#' attributes, the resulting object, when deserialized, is downcasted to the regular |
| 450 |
#' `xgb.Booster` class (i.e. it loses the metadata, and the resulting object will use |
| 451 |
#' [predict.xgb.Booster()] instead of [predict.xgboost()]) - for these `xgboost` objects, |
| 452 |
#' `saveRDS` might thus be a better option if the extra functionalities are needed. |
| 453 |
#' |
| 454 |
#' Note that XGBoost models in R starting from version `2.1.0` and onwards, and |
| 455 |
#' XGBoost models before version `2.1.0`; have a very different R object structure and |
| 456 |
#' are incompatible with each other. Hence, models that were saved with R serializers |
| 457 |
#' like [saveRDS()] or [save()] before version `2.1.0` will not work with latter |
| 458 |
#' `xgboost` versions and vice versa. Be aware that the structure of R model objects |
| 459 |
#' could in theory change again in the future, so XGBoost's serializers should be |
| 460 |
#' preferred for long-term storage. |
| 461 |
#' |
| 462 |
#' Furthermore, note that model objects from XGBoost might not be serializable with third-party |
| 463 |
#' R packages like `qs` or `qs2`. |
| 464 |
#' |
| 465 |
#' @details |
| 466 |
#' Use [xgb.save()] to save the XGBoost model as a stand-alone file. You may opt into |
| 467 |
#' the JSON format by specifying the JSON extension. To read the model back, use |
| 468 |
#' [xgb.load()]. |
| 469 |
#' |
| 470 |
#' Use [xgb.save.raw()] to save the XGBoost model as a sequence (vector) of raw bytes |
| 471 |
#' in a future-proof manner. Future releases of XGBoost will be able to read the raw bytes and |
| 472 |
#' re-construct the corresponding model. To read the model back, use [xgb.load.raw()]. |
| 473 |
#' The [xgb.save.raw()] function is useful if you would like to persist the XGBoost model |
| 474 |
#' as part of another R object. |
| 475 |
#' |
| 476 |
#' Use [saveRDS()] if you require the R-specific attributes that a booster might have, such |
| 477 |
#' as evaluation logs or the model class `xgboost` instead of `xgb.Booster`, but note that |
| 478 |
#' future compatibility of such objects is outside XGBoost's control as it relies on R's |
| 479 |
#' serialization format (see e.g. the details section in [serialize] and [save()] from base R). |
| 480 |
#' |
| 481 |
#' For more details and explanation about model persistence and archival, consult the page |
| 482 |
#' \url{https://xgboost.readthedocs.io/en/latest/tutorials/saving_model.html}. |
| 483 |
#' |
| 484 |
#' @examples |
| 485 |
#' \dontshow{RhpcBLASctl::omp_set_num_threads(1)} |
| 486 |
#' data(agaricus.train, package = "xgboost") |
| 487 |
#' |
| 488 |
#' bst <- xgb.train( |
| 489 |
#' data = xgb.DMatrix(agaricus.train$data, label = agaricus.train$label, nthread = 1), |
| 490 |
#' nrounds = 2, |
| 491 |
#' params = xgb.params( |
| 492 |
#' max_depth = 2, |
| 493 |
#' nthread = 2, |
| 494 |
#' objective = "binary:logistic" |
| 495 |
#' ) |
| 496 |
#' ) |
| 497 |
#' |
| 498 |
#' # Save as a stand-alone file; load it with xgb.load() |
| 499 |
#' fname <- file.path(tempdir(), "xgb_model.ubj") |
| 500 |
#' xgb.save(bst, fname) |
| 501 |
#' bst2 <- xgb.load(fname) |
| 502 |
#' |
| 503 |
#' # Save as a stand-alone file (JSON); load it with xgb.load() |
| 504 |
#' fname <- file.path(tempdir(), "xgb_model.json") |
| 505 |
#' xgb.save(bst, fname) |
| 506 |
#' bst2 <- xgb.load(fname) |
| 507 |
#' |
| 508 |
#' # Save as a raw byte vector; load it with xgb.load.raw() |
| 509 |
#' xgb_bytes <- xgb.save.raw(bst) |
| 510 |
#' bst2 <- xgb.load.raw(xgb_bytes) |
| 511 |
#' |
| 512 |
#' # Persist XGBoost model as part of another R object |
| 513 |
#' obj <- list(xgb_model_bytes = xgb.save.raw(bst), description = "My first XGBoost model") |
| 514 |
#' # Persist the R object. Here, saveRDS() is okay, since it doesn't persist |
| 515 |
#' # xgb.Booster directly. What's being persisted is the future-proof byte representation |
| 516 |
#' # as given by xgb.save.raw(). |
| 517 |
#' fname <- file.path(tempdir(), "my_object.Rds") |
| 518 |
#' saveRDS(obj, fname) |
| 519 |
#' # Read back the R object |
| 520 |
#' obj2 <- readRDS(fname) |
| 521 |
#' # Re-construct xgb.Booster object from the bytes |
| 522 |
#' bst2 <- xgb.load.raw(obj2$xgb_model_bytes) |
| 523 |
#' |
| 524 |
#' @name a-compatibility-note-for-saveRDS-save |
| 525 |
NULL |
| 526 |
|
| 527 |
#' @name xgboost-options |
| 528 |
#' @title XGBoost Options |
| 529 |
#' @description XGBoost offers an \link[base:options]{option setting} for controlling the behavior |
| 530 |
#' of deprecated and removed function arguments. |
| 531 |
#' |
| 532 |
#' Some of the arguments in functions like [xgb.train()] or [predict.xgb.Booster()] been renamed |
| 533 |
#' from how they were in previous versions, or have been removed. |
| 534 |
#' |
| 535 |
#' In order to make the transition to newer XGBoost versions easier, some of these parameters are |
| 536 |
#' still accepted but issue a warning when using them. \bold{Note that these warnings will become |
| 537 |
#' errors in the future!!} - this is just a temporary workaround to make the transition easier. |
| 538 |
#' |
| 539 |
#' One can optionally use 'strict mode' to turn these warnings into errors, in order to ensure |
| 540 |
#' that code calling xgboost will still work once those are removed in future releases. |
| 541 |
#' |
| 542 |
#' Currently, the only supported option is `xgboost.strict_mode`, which can be set to `TRUE` or |
| 543 |
#' `FALSE` (default). |
| 544 |
#' |
| 545 |
#' In addition to an R option, it can also be enabled through by setting environment variable |
| 546 |
#' `XGB_STRICT_MODE=1`. If set, this environment variable will take precedence over the option. |
| 547 |
#' @examples |
| 548 |
#' options("xgboost.strict_mode" = FALSE) |
| 549 |
#' options("xgboost.strict_mode" = TRUE) |
| 550 |
#' Sys.setenv("XGB_STRICT_MODE" = "1") |
| 551 |
#' Sys.setenv("XGB_STRICT_MODE" = "0") |
| 552 |
NULL |
| 553 |
|
| 554 |
get.strict.mode.option <- function() { |
| 555 |
env_var_option <- Sys.getenv("XGB_STRICT_MODE") |
| 556 |
if (!nchar(env_var_option)) { |
| 557 |
return(getOption("xgboost.strict_mode", default = FALSE)) |
| 558 |
} |
| 559 |
return(tolower(as.character(env_var_option)) %in% c("1", "true", "t", "yes", "y")) |
| 560 |
} |
| 561 |
|
| 562 |
# Lookup table for the deprecated parameters bookkeeping |
| 563 |
deprecated_train_params <- list( |
| 564 |
renamed = list( |
| 565 |
'print.every.n' = 'print_every_n', |
| 566 |
'early.stop.round' = 'early_stopping_rounds', |
| 567 |
'training.data' = 'data', |
| 568 |
'dtrain' = 'data', |
| 569 |
'watchlist' = 'evals', |
| 570 |
'feval' = 'custom_metric' |
| 571 |
), |
| 572 |
removed = character() |
| 573 |
) |
| 574 |
deprecated_cv_params <- deprecated_train_params |
| 575 |
deprecated_cv_params$removed <- 'label' |
| 576 |
deprecated_xgboost_params <- list( |
| 577 |
renamed = list( |
| 578 |
'data' = 'x', |
| 579 |
'label' = 'y', |
| 580 |
'eta' = 'learning_rate', |
| 581 |
'gamma' = 'min_split_loss', |
| 582 |
'lambda' = 'reg_lambda', |
| 583 |
'alpha' = 'reg_alpha', |
| 584 |
'min.split.loss' = 'min_split_loss', |
| 585 |
'reg.lambda' = 'reg_lambda', |
| 586 |
'reg.alpha' = 'reg_alpha', |
| 587 |
'watchlist' = 'evals' |
| 588 |
), |
| 589 |
removed = c( |
| 590 |
'params', |
| 591 |
'save_period', |
| 592 |
'save_name', |
| 593 |
'xgb_model', |
| 594 |
'callbacks', |
| 595 |
'missing', |
| 596 |
'maximize' |
| 597 |
) |
| 598 |
) |
| 599 |
deprecated_dttree_params <- list( |
| 600 |
renamed = list('n_first_tree' = 'trees'), |
| 601 |
removed = c("feature_names", "text") |
| 602 |
) |
| 603 |
deprecated_plotimp_params <- list( |
| 604 |
renamed = list( |
| 605 |
'plot.height' = 'plot_height', |
| 606 |
'plot.width' = 'plot_width' |
| 607 |
), |
| 608 |
removed = character() |
| 609 |
) |
| 610 |
deprecated_multitrees_params <- list( |
| 611 |
renamed = c( |
| 612 |
deprecated_plotimp_params$renamed, |
| 613 |
list('features.keep' = 'features_keep') |
| 614 |
), |
| 615 |
removed = "feature_names" |
| 616 |
) |
| 617 |
deprecated_dump_params <- list( |
| 618 |
renamed = list('with.stats' = 'with_stats'), |
| 619 |
removed = character() |
| 620 |
) |
| 621 |
deprecated_plottree_params <- c( |
| 622 |
renamed = list( |
| 623 |
deprecated_plotimp_params$renamed, |
| 624 |
deprecated_dump_params$renamed, |
| 625 |
list('trees' = 'tree_idx') |
| 626 |
), |
| 627 |
removed = c("show_node_id", "feature_names") |
| 628 |
) |
| 629 |
deprecated_predict_params <- list( |
| 630 |
renamed = list("ntreelimit" = "iterationrange"), |
| 631 |
removed = "reshape" |
| 632 |
) |
| 633 |
deprecated_dmatrix_params <- list( |
| 634 |
renamed = character(), |
| 635 |
removed = "info" |
| 636 |
) |
| 637 |
|
| 638 |
# These got moved from 'info' to function arguments |
| 639 |
args_previous_dmatrix_info <- c("label", "weight", "base_margin", "group") |
| 640 |
|
| 641 |
# Checks the dot-parameters for deprecated names |
| 642 |
# (including partial matching), gives a deprecation warning, |
| 643 |
# and sets new parameters to the old parameters' values within its parent frame. |
| 644 |
# WARNING: has side-effects |
| 645 |
check.deprecation <- function( |
| 646 |
deprecated_list, |
| 647 |
fn_call, |
| 648 |
..., |
| 649 |
env = parent.frame(), |
| 650 |
allow_unrecognized = FALSE |
| 651 |
) { |
| 652 |
params <- list(...) |
| 653 |
if (length(params) == 0) { |
| 654 |
return(NULL) |
| 655 |
} |
| 656 |
error_on_deprecated <- get.strict.mode.option() |
| 657 |
throw_err_or_depr_msg <- function(...) { |
| 658 |
if (error_on_deprecated) { |
| 659 |
stop(...) |
| 660 |
} else { |
| 661 |
warning(..., " This warning will become an error in a future version.") |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
if (is.null(names(params)) || min(nchar(names(params))) == 0L) { |
| 666 |
throw_err_or_depr_msg("Passed invalid positional arguments") |
| 667 |
} |
| 668 |
list_renamed <- deprecated_list$renamed |
| 669 |
list_removed <- deprecated_list$removed |
| 670 |
has_params_arg <- |
| 671 |
length(list_renamed) == length(deprecated_train_params$renamed) && |
| 672 |
list_renamed[[1L]] == deprecated_train_params$renamed[[1L]] |
| 673 |
is_dmatrix_constructor <- |
| 674 |
length(list_removed) == length(deprecated_dmatrix_params$removed) && |
| 675 |
list_removed[[1L]] == deprecated_dmatrix_params$removed[[1L]] |
| 676 |
all_match <- pmatch(names(params), names(list_renamed)) |
| 677 |
# throw error on unrecognized parameters |
| 678 |
if (!allow_unrecognized && anyNA(all_match)) { |
| 679 |
|
| 680 |
names_unrecognized <- names(params)[is.na(all_match)] |
| 681 |
# make it informative if they match something that goes under 'params' |
| 682 |
if (has_params_arg) { |
| 683 |
names_params <- formalArgs(xgb.params) |
| 684 |
names_params <- c(names_params, gsub("_", ".", names_params, fixed = TRUE)) |
| 685 |
names_under_params <- intersect(names_unrecognized, names_params) |
| 686 |
if (length(names_under_params)) { |
| 687 |
if (error_on_deprecated) { |
| 688 |
stop( |
| 689 |
"Passed invalid function arguments: ", |
| 690 |
paste(head(names_under_params), collapse = ", "), |
| 691 |
". These should be passed as a list to argument 'params'." |
| 692 |
) |
| 693 |
} else { |
| 694 |
warning( |
| 695 |
"Passed invalid function arguments: ", |
| 696 |
paste(head(names_under_params), collapse = ", "), |
| 697 |
". These should be passed as a list to argument 'params'.", |
| 698 |
" Conversion from argument to 'params' entry will be done automatically, but this ", |
| 699 |
"behavior will become an error in a future version." |
| 700 |
) |
| 701 |
if (any(names_under_params %in% names(env[["params"]]))) { |
| 702 |
repeteated_params <- intersect(names_under_params, names(env[["params"]])) |
| 703 |
stop( |
| 704 |
"Passed entries as both function argument(s) and as elements under 'params': ", |
| 705 |
paste(head(repeteated_params), collapse = ", ") |
| 706 |
) |
| 707 |
} else { |
| 708 |
env[["params"]] <- c(env[["params"]], params[names_under_params]) |
| 709 |
} |
| 710 |
} |
| 711 |
names_unrecognized <- setdiff(names_unrecognized, names_under_params) |
| 712 |
} |
| 713 |
} else if (is_dmatrix_constructor && NROW(params$info)) { |
| 714 |
# same thing for the earlier 'info' in 'xgb.DMatrix' |
| 715 |
throw_err_or_depr_msg( |
| 716 |
"Passed invalid argument 'info' - entries on it should be passed as direct arguments." |
| 717 |
) |
| 718 |
entries_info <- names(params$info) |
| 719 |
if (length(setdiff(entries_info, args_previous_dmatrix_info))) { |
| 720 |
stop( |
| 721 |
"Passed unrecognized entries under info: ", |
| 722 |
paste(setdiff(entries_info, args_previous_dmatrix_info) |> head(), collapse = ", ") |
| 723 |
) |
| 724 |
} |
| 725 |
for (entry_name in entries_info) { |
| 726 |
if (!is.null(env[[entry_name]])) { |
| 727 |
stop("Passed entry under both 'info' and function argument(s): ", entry_name) |
| 728 |
} |
| 729 |
env[[entry_name]] <- params$info[[entry_name]] |
| 730 |
} |
| 731 |
names_unrecognized <- setdiff(names_unrecognized, "info") |
| 732 |
} |
| 733 |
|
| 734 |
# check for parameters that were removed from a previous version |
| 735 |
names_removed <- intersect(names_unrecognized, list_removed) |
| 736 |
if (length(names_removed)) { |
| 737 |
throw_err_or_depr_msg( |
| 738 |
"Parameter(s) have been removed from this function: ", |
| 739 |
paste(names_removed, collapse = ", "), "." |
| 740 |
) |
| 741 |
names_unrecognized <- setdiff(names_unrecognized, list_removed) |
| 742 |
} |
| 743 |
|
| 744 |
# otherwise throw a generic error |
| 745 |
if (length(names_unrecognized)) { |
| 746 |
throw_err_or_depr_msg( |
| 747 |
"Passed unrecognized parameters: ", |
| 748 |
paste(head(names_unrecognized), collapse = ", "), "." |
| 749 |
) |
| 750 |
} |
| 751 |
|
| 752 |
} else { |
| 753 |
|
| 754 |
names_removed <- intersect(names(params)[is.na(all_match)], list_removed) |
| 755 |
if (length(names_removed)) { |
| 756 |
throw_err_or_depr_msg( |
| 757 |
"Parameter(s) have been removed from this function: ", |
| 758 |
paste(names_removed, collapse = ", "), "." |
| 759 |
) |
| 760 |
} |
| 761 |
|
| 762 |
} |
| 763 |
|
| 764 |
matched_params <- list_renamed[all_match[!is.na(all_match)]] |
| 765 |
idx_orig <- seq_along(params)[!is.na(all_match)] |
| 766 |
function_args_passed <- names(as.list(fn_call))[-1L] |
| 767 |
for (idx in seq_along(matched_params)) { |
| 768 |
match_old <- names(matched_params)[[idx]] |
| 769 |
match_new <- matched_params[[idx]] |
| 770 |
throw_err_or_depr_msg( |
| 771 |
"Parameter '", match_old, "' has been renamed to '", |
| 772 |
match_new, "'." |
| 773 |
) |
| 774 |
if (match_new %in% function_args_passed) { |
| 775 |
stop("Passed both '", match_new, "' and '", match_old, "'.") |
| 776 |
} |
| 777 |
env[[match_new]] <- params[[idx_orig[idx]]] |
| 778 |
} |
| 779 |
} |