| 1 |
#' Construct xgb.DMatrix object |
| 2 |
#' |
| 3 |
#' Construct an 'xgb.DMatrix' object from a given data source, which can then be passed to functions |
| 4 |
#' such as [xgb.train()] or [predict()]. |
| 5 |
#' |
| 6 |
#' Function `xgb.QuantileDMatrix()` will construct a DMatrix with quantization for the histogram |
| 7 |
#' method already applied to it, which can be used to reduce memory usage (compared to using a |
| 8 |
#' a regular DMatrix first and then creating a quantization out of it) when using the histogram |
| 9 |
#' method (`tree_method = "hist"`, which is the default algorithm), but is not usable for the |
| 10 |
#' sorted-indices method (`tree_method = "exact"`), nor for the approximate method |
| 11 |
#' (`tree_method = "approx"`). |
| 12 |
#' |
| 13 |
#' @param data Data from which to create a DMatrix, which can then be used for fitting models or |
| 14 |
#' for getting predictions out of a fitted model. |
| 15 |
#' |
| 16 |
#' Supported input types are as follows: |
| 17 |
#' - `matrix` objects, with types `numeric`, `integer`, or `logical`. |
| 18 |
#' - `data.frame` objects, with columns of types `numeric`, `integer`, `logical`, or `factor` |
| 19 |
#' |
| 20 |
#' Note that xgboost uses base-0 encoding for categorical types, hence `factor` types (which use base-1 |
| 21 |
#' encoding') will be converted inside the function call. Be aware that the encoding used for `factor` |
| 22 |
#' types is not kept as part of the model, so in subsequent calls to `predict`, it is the user's |
| 23 |
#' responsibility to ensure that factor columns have the same levels as the ones from which the DMatrix |
| 24 |
#' was constructed. |
| 25 |
#' |
| 26 |
#' Other column types are not supported. |
| 27 |
#' - CSR matrices, as class `dgRMatrix` from package `Matrix`. |
| 28 |
#' - CSC matrices, as class `dgCMatrix` from package `Matrix`. |
| 29 |
#' |
| 30 |
#' These are **not** supported by `xgb.QuantileDMatrix`. |
| 31 |
#' - XGBoost's own binary format for DMatrices, as produced by [xgb.DMatrix.save()]. |
| 32 |
#' - Single-row CSR matrices, as class `dsparseVector` from package `Matrix`, which is interpreted |
| 33 |
#' as a single row (only when making predictions from a fitted model). |
| 34 |
#' |
| 35 |
#' @param label Label of the training data. For classification problems, should be passed encoded as |
| 36 |
#' integers with numeration starting at zero. |
| 37 |
#' @param weight Weight for each instance. |
| 38 |
#' |
| 39 |
#' Note that, for ranking task, weights are per-group. In ranking task, one weight |
| 40 |
#' is assigned to each group (not each data point). This is because we |
| 41 |
#' only care about the relative ordering of data points within each group, |
| 42 |
#' so it doesn't make sense to assign weights to individual data points. |
| 43 |
#' @param base_margin Base margin used for boosting from existing model. |
| 44 |
#' |
| 45 |
#' In the case of multi-output models, one can also pass multi-dimensional base_margin. |
| 46 |
#' @param missing A float value to represents missing values in data (not used when creating DMatrix |
| 47 |
#' from text files). It is useful to change when a zero, infinite, or some other |
| 48 |
#' extreme value represents missing values in data. |
| 49 |
#' @param silent whether to suppress printing an informational message after loading from a file. |
| 50 |
#' @param feature_names Set names for features. Overrides column names in data frame and matrix. |
| 51 |
#' |
| 52 |
#' Note: columns are not referenced by name when calling `predict`, so the column order there |
| 53 |
#' must be the same as in the DMatrix construction, regardless of the column names. |
| 54 |
#' @param feature_types Set types for features. |
| 55 |
#' |
| 56 |
#' If `data` is a `data.frame` and passing `feature_types` is not supplied, |
| 57 |
#' feature types will be deduced automatically from the column types. |
| 58 |
#' |
| 59 |
#' Otherwise, one can pass a character vector with the same length as number of columns in `data`, |
| 60 |
#' with the following possible values: |
| 61 |
#' - "c", which represents categorical columns. |
| 62 |
#' - "q", which represents numeric columns. |
| 63 |
#' - "int", which represents integer columns. |
| 64 |
#' - "i", which represents logical (boolean) columns. |
| 65 |
#' |
| 66 |
#' Note that, while categorical types are treated differently from the rest for model fitting |
| 67 |
#' purposes, the other types do not influence the generated model, but have effects in other |
| 68 |
#' functionalities such as feature importances. |
| 69 |
#' |
| 70 |
#' **Important**: Categorical features, if specified manually through `feature_types`, must |
| 71 |
#' be encoded as integers with numeration starting at zero, and the same encoding needs to be |
| 72 |
#' applied when passing data to [predict()]. Even if passing `factor` types, the encoding will |
| 73 |
#' not be saved, so make sure that `factor` columns passed to `predict` have the same `levels`. |
| 74 |
#' @param nthread Number of threads used for creating DMatrix. |
| 75 |
#' @param group Group size for all ranking group. |
| 76 |
#' @param qid Query ID for data samples, used for ranking. |
| 77 |
#' @param label_lower_bound Lower bound for survival training. |
| 78 |
#' @param label_upper_bound Upper bound for survival training. |
| 79 |
#' @param feature_weights Set feature weights for column sampling. |
| 80 |
#' @param data_split_mode Not used yet. This parameter is for distributed training, which is not yet available for the R package. |
| 81 |
#' @inheritParams xgb.train |
| 82 |
#' @return An 'xgb.DMatrix' object. If calling `xgb.QuantileDMatrix`, it will have additional |
| 83 |
#' subclass `xgb.QuantileDMatrix`. |
| 84 |
#' |
| 85 |
#' @details |
| 86 |
#' Note that DMatrix objects are not serializable through R functions such as [saveRDS()] or [save()]. |
| 87 |
#' If a DMatrix gets serialized and then de-serialized (for example, when saving data in an R session or caching |
| 88 |
#' chunks in an Rmd file), the resulting object will not be usable anymore and will need to be reconstructed |
| 89 |
#' from the original source of data. |
| 90 |
#' |
| 91 |
#' @examples |
| 92 |
#' data(agaricus.train, package = "xgboost") |
| 93 |
#' |
| 94 |
#' ## Keep the number of threads to 1 for examples |
| 95 |
#' nthread <- 1 |
| 96 |
#' data.table::setDTthreads(nthread) |
| 97 |
#' dtrain <- with( |
| 98 |
#' agaricus.train, xgb.DMatrix(data, label = label, nthread = nthread) |
| 99 |
#' ) |
| 100 |
#' fname <- file.path(tempdir(), "xgb.DMatrix.data") |
| 101 |
#' xgb.DMatrix.save(dtrain, fname) |
| 102 |
#' dtrain <- xgb.DMatrix(fname, nthread = 1) |
| 103 |
#' @export |
| 104 |
#' @rdname xgb.DMatrix |
| 105 |
xgb.DMatrix <- function( |
| 106 |
data, |
| 107 |
label = NULL, |
| 108 |
weight = NULL, |
| 109 |
base_margin = NULL, |
| 110 |
missing = NA, |
| 111 |
silent = FALSE, |
| 112 |
feature_names = colnames(data), |
| 113 |
feature_types = NULL, |
| 114 |
nthread = NULL, |
| 115 |
group = NULL, |
| 116 |
qid = NULL, |
| 117 |
label_lower_bound = NULL, |
| 118 |
label_upper_bound = NULL, |
| 119 |
feature_weights = NULL, |
| 120 |
data_split_mode = "row", |
| 121 |
... |
| 122 |
) { |
| 123 |
check.deprecation(deprecated_dmatrix_params, match.call(), ...) |
| 124 |
if (!is.null(group) && !is.null(qid)) { |
| 125 |
stop("Either one of 'group' or 'qid' should be NULL") |
| 126 |
} |
| 127 |
if (data_split_mode != "row") { |
| 128 |
stop("'data_split_mode' is not supported yet.") |
| 129 |
} |
| 130 |
nthread <- as.integer(NVL(nthread, -1L)) |
| 131 |
if (typeof(data) == "character") { |
| 132 |
if (length(data) > 1) { |
| 133 |
stop( |
| 134 |
"'data' has class 'character' and length ", length(data), |
| 135 |
".\n 'data' accepts either a numeric matrix or a single filename." |
| 136 |
) |
| 137 |
} |
| 138 |
data <- path.expand(data) |
| 139 |
if (data_split_mode == "row") { |
| 140 |
data_split_mode <- 0L |
| 141 |
} else if (data_split_mode == "col") { |
| 142 |
data_split_mode <- 1L |
| 143 |
} else { |
| 144 |
stop("Passed invalid 'data_split_mode': ", data_split_mode) |
| 145 |
} |
| 146 |
handle <- .Call(XGDMatrixCreateFromURI_R, data, as.integer(silent), data_split_mode) |
| 147 |
} else if (is.matrix(data)) { |
| 148 |
handle <- .Call( |
| 149 |
XGDMatrixCreateFromMat_R, data, missing, nthread |
| 150 |
) |
| 151 |
} else if (inherits(data, "dgCMatrix")) { |
| 152 |
handle <- .Call( |
| 153 |
XGDMatrixCreateFromCSC_R, |
| 154 |
data@p, |
| 155 |
data@i, |
| 156 |
data@x, |
| 157 |
nrow(data), |
| 158 |
missing, |
| 159 |
nthread |
| 160 |
) |
| 161 |
} else if (inherits(data, "dgRMatrix")) { |
| 162 |
handle <- .Call( |
| 163 |
XGDMatrixCreateFromCSR_R, |
| 164 |
data@p, |
| 165 |
data@j, |
| 166 |
data@x, |
| 167 |
ncol(data), |
| 168 |
missing, |
| 169 |
nthread |
| 170 |
) |
| 171 |
} else if (inherits(data, "dsparseVector")) { |
| 172 |
indptr <- c(0L, as.integer(length(data@i))) |
| 173 |
ind <- as.integer(data@i) - 1L |
| 174 |
handle <- .Call( |
| 175 |
XGDMatrixCreateFromCSR_R, |
| 176 |
indptr, |
| 177 |
ind, |
| 178 |
data@x, |
| 179 |
length(data), |
| 180 |
missing, |
| 181 |
nthread |
| 182 |
) |
| 183 |
} else if (is.data.frame(data)) { |
| 184 |
tmp <- .process.df.for.dmatrix(data, feature_types) |
| 185 |
feature_types <- tmp$feature_types |
| 186 |
handle <- .Call( |
| 187 |
XGDMatrixCreateFromDF_R, tmp$lst, missing, nthread |
| 188 |
) |
| 189 |
rm(tmp) |
| 190 |
} else { |
| 191 |
stop("xgb.DMatrix does not support construction from ", typeof(data)) |
| 192 |
} |
| 193 |
|
| 194 |
dmat <- handle |
| 195 |
attributes(dmat) <- list( |
| 196 |
class = "xgb.DMatrix", |
| 197 |
fields = new.env() |
| 198 |
) |
| 199 |
.set.dmatrix.fields( |
| 200 |
dmat = dmat, |
| 201 |
label = label, |
| 202 |
weight = weight, |
| 203 |
base_margin = base_margin, |
| 204 |
feature_names = feature_names, |
| 205 |
feature_types = feature_types, |
| 206 |
group = group, |
| 207 |
qid = qid, |
| 208 |
label_lower_bound = label_lower_bound, |
| 209 |
label_upper_bound = label_upper_bound, |
| 210 |
feature_weights = feature_weights |
| 211 |
) |
| 212 |
|
| 213 |
return(dmat) |
| 214 |
} |
| 215 |
|
| 216 |
.process.df.for.dmatrix <- function(df, feature_types) { |
| 217 |
if (!nrow(df) || !ncol(df)) { |
| 218 |
stop("'data' is an empty data.frame.") |
| 219 |
} |
| 220 |
if (!is.null(feature_types)) { |
| 221 |
if (!is.character(feature_types) || length(feature_types) != ncol(df)) { |
| 222 |
stop( |
| 223 |
"'feature_types' must be a character vector with one entry per column in 'data'." |
| 224 |
) |
| 225 |
} |
| 226 |
} else { |
| 227 |
feature_types <- sapply(df, function(col) { |
| 228 |
if (is.factor(col)) { |
| 229 |
return("c") |
| 230 |
} else if (is.integer(col)) { |
| 231 |
return("int") |
| 232 |
} else if (is.logical(col)) { |
| 233 |
return("i") |
| 234 |
} else { |
| 235 |
if (!is.numeric(col)) { |
| 236 |
stop("Invalid type in dataframe.") |
| 237 |
} |
| 238 |
return("float") |
| 239 |
} |
| 240 |
}) |
| 241 |
} |
| 242 |
|
| 243 |
lst <- lapply(df, function(col) { |
| 244 |
is_factor <- is.factor(col) |
| 245 |
col <- as.numeric(col) |
| 246 |
if (is_factor) { |
| 247 |
col <- col - 1 |
| 248 |
} |
| 249 |
return(col) |
| 250 |
}) |
| 251 |
|
| 252 |
return(list(lst = lst, feature_types = feature_types)) |
| 253 |
} |
| 254 |
|
| 255 |
.set.dmatrix.fields <- function( |
| 256 |
dmat, |
| 257 |
label, |
| 258 |
weight, |
| 259 |
base_margin, |
| 260 |
feature_names, |
| 261 |
feature_types, |
| 262 |
group, |
| 263 |
qid, |
| 264 |
label_lower_bound, |
| 265 |
label_upper_bound, |
| 266 |
feature_weights |
| 267 |
) { |
| 268 |
if (!is.null(label)) { |
| 269 |
setinfo(dmat, "label", label) |
| 270 |
} |
| 271 |
if (!is.null(weight)) { |
| 272 |
setinfo(dmat, "weight", weight) |
| 273 |
} |
| 274 |
if (!is.null(base_margin)) { |
| 275 |
setinfo(dmat, "base_margin", base_margin) |
| 276 |
} |
| 277 |
if (!is.null(feature_names)) { |
| 278 |
setinfo(dmat, "feature_name", feature_names) |
| 279 |
} |
| 280 |
if (!is.null(feature_types)) { |
| 281 |
setinfo(dmat, "feature_type", feature_types) |
| 282 |
} |
| 283 |
if (!is.null(group)) { |
| 284 |
setinfo(dmat, "group", group) |
| 285 |
} |
| 286 |
if (!is.null(qid)) { |
| 287 |
setinfo(dmat, "qid", qid) |
| 288 |
} |
| 289 |
if (!is.null(label_lower_bound)) { |
| 290 |
setinfo(dmat, "label_lower_bound", label_lower_bound) |
| 291 |
} |
| 292 |
if (!is.null(label_upper_bound)) { |
| 293 |
setinfo(dmat, "label_upper_bound", label_upper_bound) |
| 294 |
} |
| 295 |
if (!is.null(feature_weights)) { |
| 296 |
setinfo(dmat, "feature_weights", feature_weights) |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
#' @param ref The training dataset that provides quantile information, needed when creating |
| 301 |
#' validation/test dataset with [xgb.QuantileDMatrix()]. Supplying the training DMatrix |
| 302 |
#' as a reference means that the same quantisation applied to the training data is |
| 303 |
#' applied to the validation/test data |
| 304 |
#' @param max_bin The number of histogram bin, should be consistent with the training parameter |
| 305 |
#' `max_bin`. |
| 306 |
#' |
| 307 |
#' This is only supported when constructing a QuantileDMatrix. |
| 308 |
#' @export |
| 309 |
#' @rdname xgb.DMatrix |
| 310 |
xgb.QuantileDMatrix <- function( |
| 311 |
data, |
| 312 |
label = NULL, |
| 313 |
weight = NULL, |
| 314 |
base_margin = NULL, |
| 315 |
missing = NA, |
| 316 |
feature_names = colnames(data), |
| 317 |
feature_types = NULL, |
| 318 |
nthread = NULL, |
| 319 |
group = NULL, |
| 320 |
qid = NULL, |
| 321 |
label_lower_bound = NULL, |
| 322 |
label_upper_bound = NULL, |
| 323 |
feature_weights = NULL, |
| 324 |
ref = NULL, |
| 325 |
max_bin = NULL |
| 326 |
) { |
| 327 |
nthread <- as.integer(NVL(nthread, -1L)) |
| 328 |
if (!is.null(ref) && !inherits(ref, "xgb.DMatrix")) { |
| 329 |
stop("'ref' must be an xgb.DMatrix object.") |
| 330 |
} |
| 331 |
|
| 332 |
# Note: when passing an integer matrix, it won't get casted to numeric. |
| 333 |
# Since 'int' values as understood by languages like C cannot have missing values, |
| 334 |
# R represents missingness there by assigning them a value equal to the minimum |
| 335 |
# integer. The 'missing' value here is set before the data, so in case of integers, |
| 336 |
# need to make the conversion manually beforehand. |
| 337 |
if (is.matrix(data) && storage.mode(data) %in% c("integer", "logical") && is.na(missing)) { |
| 338 |
missing <- .Call(XGGetRNAIntAsDouble) |
| 339 |
} |
| 340 |
|
| 341 |
iterator_env <- as.environment( |
| 342 |
list( |
| 343 |
data = data, |
| 344 |
label = label, |
| 345 |
weight = weight, |
| 346 |
base_margin = base_margin, |
| 347 |
missing = missing, |
| 348 |
feature_names = feature_names, |
| 349 |
feature_types = feature_types, |
| 350 |
group = group, |
| 351 |
qid = qid, |
| 352 |
label_lower_bound = label_lower_bound, |
| 353 |
label_upper_bound = label_upper_bound, |
| 354 |
feature_weights = feature_weights |
| 355 |
) |
| 356 |
) |
| 357 |
data_iterator <- .single.data.iterator(iterator_env) |
| 358 |
|
| 359 |
env_keep_alive <- new.env() |
| 360 |
env_keep_alive$keepalive <- NULL |
| 361 |
|
| 362 |
# Note: the ProxyDMatrix has its finalizer assigned in the R externalptr |
| 363 |
# object, but that finalizer will only be called once the object is |
| 364 |
# garbage-collected, which doesn't happen immediately after it goes out |
| 365 |
# of scope, hence this piece of code to tigger its destruction earlier |
| 366 |
# and free memory right away. |
| 367 |
proxy_handle <- .make.proxy.handle() |
| 368 |
on.exit({ |
| 369 |
.Call(XGDMatrixFree_R, proxy_handle) |
| 370 |
}) |
| 371 |
iterator_next <- function() { |
| 372 |
return(xgb.ProxyDMatrix(proxy_handle, data_iterator, env_keep_alive)) |
| 373 |
} |
| 374 |
iterator_reset <- function() { |
| 375 |
env_keep_alive$keepalive <- NULL |
| 376 |
return(data_iterator$f_reset(iterator_env)) |
| 377 |
} |
| 378 |
calling_env <- environment() |
| 379 |
|
| 380 |
dmat <- .Call( |
| 381 |
XGQuantileDMatrixCreateFromCallback_R, |
| 382 |
iterator_next, |
| 383 |
iterator_reset, |
| 384 |
calling_env, |
| 385 |
proxy_handle, |
| 386 |
nthread, |
| 387 |
missing, |
| 388 |
max_bin, |
| 389 |
ref |
| 390 |
) |
| 391 |
attributes(dmat) <- list( |
| 392 |
class = c("xgb.DMatrix", "xgb.QuantileDMatrix"), |
| 393 |
fields = attributes(proxy_handle)$fields |
| 394 |
) |
| 395 |
return(dmat) |
| 396 |
} |
| 397 |
|
| 398 |
#' XGBoost Data Iterator |
| 399 |
#' |
| 400 |
#' @description |
| 401 |
#' Interface to create a custom data iterator in order to construct a DMatrix |
| 402 |
#' from external memory. |
| 403 |
#' |
| 404 |
#' This function is responsible for generating an R object structure containing callback |
| 405 |
#' functions and an environment shared with them. |
| 406 |
#' |
| 407 |
#' The output structure from this function is then meant to be passed to [xgb.ExtMemDMatrix()], |
| 408 |
#' which will consume the data and create a DMatrix from it by executing the callback functions. |
| 409 |
#' |
| 410 |
#' For more information, and for a usage example, see the documentation for [xgb.ExtMemDMatrix()]. |
| 411 |
#' |
| 412 |
#' @param env An R environment to pass to the callback functions supplied here, which can be |
| 413 |
#' used to keep track of variables to determine how to handle the batches. |
| 414 |
#' |
| 415 |
#' For example, one might want to keep track of an iteration number in this environment in order |
| 416 |
#' to know which part of the data to pass next. |
| 417 |
#' @param f_next `function(env)` which is responsible for: |
| 418 |
#' - Accessing or retrieving the next batch of data in the iterator. |
| 419 |
#' - Supplying this data by calling function [xgb.DataBatch()] on it and returning the result. |
| 420 |
#' - Keeping track of where in the iterator batch it is or will go next, which can for example |
| 421 |
#' be done by modifiying variables in the `env` variable that is passed here. |
| 422 |
#' - Signaling whether there are more batches to be consumed or not, by returning `NULL` |
| 423 |
#' when the stream of data ends (all batches in the iterator have been consumed), or the result from |
| 424 |
#' calling [xgb.DataBatch()] when there are more batches in the line to be consumed. |
| 425 |
#' @param f_reset `function(env)` which is responsible for reseting the data iterator |
| 426 |
#' (i.e. taking it back to the first batch, called before and after the sequence of batches |
| 427 |
#' has been consumed). |
| 428 |
#' |
| 429 |
#' Note that, after resetting the iterator, the batches will be accessed again, so the same data |
| 430 |
#' (and in the same order) must be passed in subsequent iterations. |
| 431 |
#' @return An `xgb.DataIter` object, containing the same inputs supplied here, which can then |
| 432 |
#' be passed to [xgb.ExtMemDMatrix()]. |
| 433 |
#' @seealso [xgb.ExtMemDMatrix()], [xgb.DataBatch()]. |
| 434 |
#' @export |
| 435 |
xgb.DataIter <- function(env = new.env(), f_next, f_reset) { |
| 436 |
if (!is.function(f_next)) { |
| 437 |
stop("'f_next' must be a function.") |
| 438 |
} |
| 439 |
if (!is.function(f_reset)) { |
| 440 |
stop("'f_reset' must be a function.") |
| 441 |
} |
| 442 |
out <- list( |
| 443 |
env = env, |
| 444 |
f_next = f_next, |
| 445 |
f_reset = f_reset |
| 446 |
) |
| 447 |
class(out) <- "xgb.DataIter" |
| 448 |
return(out) |
| 449 |
} |
| 450 |
|
| 451 |
.qdm.single.fnext <- function(env) { |
| 452 |
curr_iter <- env[["iter"]] |
| 453 |
if (curr_iter >= 1L) { |
| 454 |
return(NULL) |
| 455 |
} |
| 456 |
|
| 457 |
on.exit({ |
| 458 |
env[["iter"]] <- curr_iter + 1L |
| 459 |
}) |
| 460 |
return( |
| 461 |
xgb.DataBatch( |
| 462 |
data = env[["data"]], |
| 463 |
label = env[["label"]], |
| 464 |
weight = env[["weight"]], |
| 465 |
base_margin = env[["base_margin"]], |
| 466 |
feature_names = env[["feature_names"]], |
| 467 |
feature_types = env[["feature_types"]], |
| 468 |
group = env[["group"]], |
| 469 |
qid = env[["qid"]], |
| 470 |
label_lower_bound = env[["label_lower_bound"]], |
| 471 |
label_upper_bound = env[["label_upper_bound"]], |
| 472 |
feature_weights = env[["feature_weights"]] |
| 473 |
) |
| 474 |
) |
| 475 |
} |
| 476 |
|
| 477 |
.qdm.single.freset <- function(env) { |
| 478 |
env[["iter"]] <- 0L |
| 479 |
return(invisible(NULL)) |
| 480 |
} |
| 481 |
|
| 482 |
.single.data.iterator <- function(env) { |
| 483 |
env[["iter"]] <- 0L |
| 484 |
return(xgb.DataIter(env, .qdm.single.fnext, .qdm.single.freset)) |
| 485 |
} |
| 486 |
|
| 487 |
# Only for internal usage |
| 488 |
.make.proxy.handle <- function() { |
| 489 |
out <- .Call(XGProxyDMatrixCreate_R) |
| 490 |
attributes(out) <- list( |
| 491 |
class = c("xgb.DMatrix", "xgb.ProxyDMatrix"), |
| 492 |
fields = new.env() |
| 493 |
) |
| 494 |
return(out) |
| 495 |
} |
| 496 |
|
| 497 |
#' Structure for Data Batches |
| 498 |
#' |
| 499 |
#' @description |
| 500 |
#' Helper function to supply data in batches of a data iterator when |
| 501 |
#' constructing a DMatrix from external memory through [xgb.ExtMemDMatrix()] |
| 502 |
#' or through [xgb.QuantileDMatrix.from_iterator()]. |
| 503 |
#' |
| 504 |
#' This function is **only** meant to be called inside of a callback function (which |
| 505 |
#' is passed as argument to function [xgb.DataIter()] to construct a data iterator) |
| 506 |
#' when constructing a DMatrix through external memory - otherwise, one should call |
| 507 |
#' [xgb.DMatrix()] or [xgb.QuantileDMatrix()]. |
| 508 |
#' |
| 509 |
#' The object that results from calling this function directly is **not** like |
| 510 |
#' an `xgb.DMatrix` - i.e. cannot be used to train a model, nor to get predictions - only |
| 511 |
#' possible usage is to supply data to an iterator, from which a DMatrix is then constructed. |
| 512 |
#' |
| 513 |
#' For more information and for example usage, see the documentation for [xgb.ExtMemDMatrix()]. |
| 514 |
#' @inheritParams xgb.DMatrix |
| 515 |
#' @param data Batch of data belonging to this batch. |
| 516 |
#' |
| 517 |
#' Note that not all of the input types supported by [xgb.DMatrix()] are possible |
| 518 |
#' to pass here. Supported types are: |
| 519 |
#' - `matrix`, with types `numeric`, `integer`, and `logical`. Note that for types |
| 520 |
#' `integer` and `logical`, missing values might not be automatically recognized as |
| 521 |
#' as such - see the documentation for parameter `missing` in [xgb.ExtMemDMatrix()] |
| 522 |
#' for details on this. |
| 523 |
#' - `data.frame`, with the same types as supported by 'xgb.DMatrix' and same |
| 524 |
#' conversions applied to it. See the documentation for parameter `data` in |
| 525 |
#' [xgb.DMatrix()] for details on it. |
| 526 |
#' - CSR matrices, as class `dgRMatrix` from package "Matrix". |
| 527 |
#' @return An object of class `xgb.DataBatch`, which is just a list containing the |
| 528 |
#' data and parameters passed here. It does **not** inherit from `xgb.DMatrix`. |
| 529 |
#' @seealso [xgb.DataIter()], [xgb.ExtMemDMatrix()]. |
| 530 |
#' @export |
| 531 |
xgb.DataBatch <- function( |
| 532 |
data, |
| 533 |
label = NULL, |
| 534 |
weight = NULL, |
| 535 |
base_margin = NULL, |
| 536 |
feature_names = colnames(data), |
| 537 |
feature_types = NULL, |
| 538 |
group = NULL, |
| 539 |
qid = NULL, |
| 540 |
label_lower_bound = NULL, |
| 541 |
label_upper_bound = NULL, |
| 542 |
feature_weights = NULL |
| 543 |
) { |
| 544 |
stopifnot(inherits(data, c("matrix", "data.frame", "dgRMatrix"))) |
| 545 |
out <- list( |
| 546 |
data = data, |
| 547 |
label = label, |
| 548 |
weight = weight, |
| 549 |
base_margin = base_margin, |
| 550 |
feature_names = feature_names, |
| 551 |
feature_types = feature_types, |
| 552 |
group = group, |
| 553 |
qid = qid, |
| 554 |
label_lower_bound = label_lower_bound, |
| 555 |
label_upper_bound = label_upper_bound, |
| 556 |
feature_weights = feature_weights |
| 557 |
) |
| 558 |
class(out) <- "xgb.DataBatch" |
| 559 |
return(out) |
| 560 |
} |
| 561 |
|
| 562 |
# This is only for internal usage, class is not exposed to the user. |
| 563 |
xgb.ProxyDMatrix <- function(proxy_handle, data_iterator, env_keep_alive) { |
| 564 |
env_keep_alive$keepalive <- NULL |
| 565 |
lst <- data_iterator$f_next(data_iterator$env) |
| 566 |
if (is.null(lst)) { |
| 567 |
return(0L) |
| 568 |
} |
| 569 |
if (!inherits(lst, "xgb.DataBatch")) { |
| 570 |
stop("DataIter 'f_next' must return either NULL or the result from calling 'xgb.DataBatch'.") |
| 571 |
} |
| 572 |
|
| 573 |
if (!is.null(lst$group) && !is.null(lst$qid)) { |
| 574 |
stop("Either one of 'group' or 'qid' should be NULL") |
| 575 |
} |
| 576 |
if (is.data.frame(lst$data)) { |
| 577 |
data <- lst$data |
| 578 |
lst$data <- NULL |
| 579 |
tmp <- .process.df.for.dmatrix(data, lst$feature_types) |
| 580 |
lst$feature_types <- tmp$feature_types |
| 581 |
data <- NULL |
| 582 |
env_keep_alive$keepalive <- tmp |
| 583 |
.Call(XGProxyDMatrixSetDataColumnar_R, proxy_handle, tmp$lst) |
| 584 |
} else if (is.matrix(lst$data)) { |
| 585 |
env_keep_alive$keepalive <- lst |
| 586 |
.Call(XGProxyDMatrixSetDataDense_R, proxy_handle, lst$data) |
| 587 |
} else if (inherits(lst$data, "dgRMatrix")) { |
| 588 |
tmp <- list(p = lst$data@p, j = lst$data@j, x = lst$data@x, ncol = ncol(lst$data)) |
| 589 |
env_keep_alive$keepalive <- tmp |
| 590 |
.Call(XGProxyDMatrixSetDataCSR_R, proxy_handle, tmp) |
| 591 |
} else { |
| 592 |
stop("'data' has unsupported type.") |
| 593 |
} |
| 594 |
|
| 595 |
.set.dmatrix.fields( |
| 596 |
dmat = proxy_handle, |
| 597 |
label = lst$label, |
| 598 |
weight = lst$weight, |
| 599 |
base_margin = lst$base_margin, |
| 600 |
feature_names = lst$feature_names, |
| 601 |
feature_types = lst$feature_types, |
| 602 |
group = lst$group, |
| 603 |
qid = lst$qid, |
| 604 |
label_lower_bound = lst$label_lower_bound, |
| 605 |
label_upper_bound = lst$label_upper_bound, |
| 606 |
feature_weights = lst$feature_weights |
| 607 |
) |
| 608 |
|
| 609 |
return(1L) |
| 610 |
} |
| 611 |
|
| 612 |
#' DMatrix from External Data |
| 613 |
#' |
| 614 |
#' @description |
| 615 |
#' Create a special type of XGBoost 'DMatrix' object from external data |
| 616 |
#' supplied by an [xgb.DataIter()] object, potentially passed in batches from a |
| 617 |
#' bigger set that might not fit entirely in memory. |
| 618 |
#' |
| 619 |
#' The data supplied by the iterator is accessed on-demand as needed, multiple times, |
| 620 |
#' without being concatenated, but note that fields like 'label' **will** be |
| 621 |
#' concatenated from multiple calls to the data iterator. |
| 622 |
#' |
| 623 |
#' For more information, see the guide 'Using XGBoost External Memory Version': |
| 624 |
#' \url{https://xgboost.readthedocs.io/en/stable/tutorials/external_memory.html} |
| 625 |
#' @details |
| 626 |
#' Be aware that construction of external data DMatrices \bold{will cache data on disk} |
| 627 |
#' in a compressed format, under the path supplied in `cache_prefix`. |
| 628 |
#' |
| 629 |
#' External data is not supported for the exact tree method. |
| 630 |
#' @inheritParams xgb.DMatrix |
| 631 |
#' @param data_iterator A data iterator structure as returned by [xgb.DataIter()], |
| 632 |
#' which includes an environment shared between function calls, and functions to access |
| 633 |
#' the data in batches on-demand. |
| 634 |
#' @param cache_prefix The path of cache file, caller must initialize all the directories in this path. |
| 635 |
#' @param missing A float value to represents missing values in data. |
| 636 |
#' |
| 637 |
#' Note that, while functions like [xgb.DMatrix()] can take a generic `NA` and interpret it |
| 638 |
#' correctly for different types like `numeric` and `integer`, if an `NA` value is passed here, |
| 639 |
#' it will not be adapted for different input types. |
| 640 |
#' |
| 641 |
#' For example, in R `integer` types, missing values are represented by integer number `-2147483648` |
| 642 |
#' (since machine 'integer' types do not have an inherent 'NA' value) - hence, if one passes `NA`, |
| 643 |
#' which is interpreted as a floating-point NaN by [xgb.ExtMemDMatrix()] and by |
| 644 |
#' [xgb.QuantileDMatrix.from_iterator()], these integer missing values will not be treated as missing. |
| 645 |
#' This should not pose any problem for `numeric` types, since they do have an inheret NaN value. |
| 646 |
#' @return An 'xgb.DMatrix' object, with subclass 'xgb.ExtMemDMatrix', in which the data is not |
| 647 |
#' held internally but accessed through the iterator when needed. |
| 648 |
#' @seealso [xgb.DataIter()], [xgb.DataBatch()], [xgb.QuantileDMatrix.from_iterator()] |
| 649 |
#' @examples |
| 650 |
#' data(mtcars) |
| 651 |
#' |
| 652 |
#' # This custom environment will be passed to the iterator |
| 653 |
#' # functions at each call. It is up to the user to keep |
| 654 |
#' # track of the iteration number in this environment. |
| 655 |
#' iterator_env <- as.environment( |
| 656 |
#' list( |
| 657 |
#' iter = 0, |
| 658 |
#' x = mtcars[, -1], |
| 659 |
#' y = mtcars[, 1] |
| 660 |
#' ) |
| 661 |
#' ) |
| 662 |
#' |
| 663 |
#' # Data is passed in two batches. |
| 664 |
#' # In this example, batches are obtained by subsetting the 'x' variable. |
| 665 |
#' # This is not advantageous to do, since the data is already loaded in memory |
| 666 |
#' # and can be passed in full in one go, but there can be situations in which |
| 667 |
#' # only a subset of the data will fit in the computer's memory, and it can |
| 668 |
#' # be loaded in batches that are accessed one-at-a-time only. |
| 669 |
#' iterator_next <- function(iterator_env) { |
| 670 |
#' curr_iter <- iterator_env[["iter"]] |
| 671 |
#' if (curr_iter >= 2) { |
| 672 |
#' # there are only two batches, so this signals end of the stream |
| 673 |
#' return(NULL) |
| 674 |
#' } |
| 675 |
#' |
| 676 |
#' if (curr_iter == 0) { |
| 677 |
#' x_batch <- iterator_env[["x"]][1:16, ] |
| 678 |
#' y_batch <- iterator_env[["y"]][1:16] |
| 679 |
#' } else { |
| 680 |
#' x_batch <- iterator_env[["x"]][17:32, ] |
| 681 |
#' y_batch <- iterator_env[["y"]][17:32] |
| 682 |
#' } |
| 683 |
#' on.exit({ |
| 684 |
#' iterator_env[["iter"]] <- curr_iter + 1 |
| 685 |
#' }) |
| 686 |
#' |
| 687 |
#' # Function 'xgb.DataBatch' must be called manually |
| 688 |
#' # at each batch with all the appropriate attributes, |
| 689 |
#' # such as feature names and feature types. |
| 690 |
#' return(xgb.DataBatch(data = x_batch, label = y_batch)) |
| 691 |
#' } |
| 692 |
#' |
| 693 |
#' # This moves the iterator back to its beginning |
| 694 |
#' iterator_reset <- function(iterator_env) { |
| 695 |
#' iterator_env[["iter"]] <- 0 |
| 696 |
#' } |
| 697 |
#' |
| 698 |
#' data_iterator <- xgb.DataIter( |
| 699 |
#' env = iterator_env, |
| 700 |
#' f_next = iterator_next, |
| 701 |
#' f_reset = iterator_reset |
| 702 |
#' ) |
| 703 |
#' cache_prefix <- tempdir() |
| 704 |
#' |
| 705 |
#' # DMatrix will be constructed from the iterator's batches |
| 706 |
#' dm <- xgb.ExtMemDMatrix(data_iterator, cache_prefix, nthread = 1) |
| 707 |
#' |
| 708 |
#' # After construction, can be used as a regular DMatrix |
| 709 |
#' params <- xgb.params(nthread = 1, objective = "reg:squarederror") |
| 710 |
#' model <- xgb.train(data = dm, nrounds = 2, params = params) |
| 711 |
#' |
| 712 |
#' # Predictions can also be called on it, and should be the same |
| 713 |
#' # as if the data were passed differently. |
| 714 |
#' pred_dm <- predict(model, dm) |
| 715 |
#' pred_mat <- predict(model, as.matrix(mtcars[, -1])) |
| 716 |
#' @export |
| 717 |
xgb.ExtMemDMatrix <- function( |
| 718 |
data_iterator, |
| 719 |
cache_prefix = tempdir(), |
| 720 |
missing = NA, |
| 721 |
nthread = NULL |
| 722 |
) { |
| 723 |
stopifnot(inherits(data_iterator, "xgb.DataIter")) |
| 724 |
stopifnot(is.character(cache_prefix)) |
| 725 |
|
| 726 |
cache_prefix <- path.expand(cache_prefix) |
| 727 |
nthread <- as.integer(NVL(nthread, -1L)) |
| 728 |
|
| 729 |
# The purpose of this environment is to keep data alive (protected from the |
| 730 |
# garbage collector) after setting the data in the proxy dmatrix. The data |
| 731 |
# held here (under name 'keepalive') should be unset (leaving it unprotected |
| 732 |
# for garbage collection) before the start of each data iteration batch and |
| 733 |
# during each iterator reset. |
| 734 |
env_keep_alive <- new.env() |
| 735 |
env_keep_alive$keepalive <- NULL |
| 736 |
|
| 737 |
proxy_handle <- .make.proxy.handle() |
| 738 |
on.exit({ |
| 739 |
.Call(XGDMatrixFree_R, proxy_handle) |
| 740 |
}) |
| 741 |
iterator_next <- function() { |
| 742 |
return(xgb.ProxyDMatrix(proxy_handle, data_iterator, env_keep_alive)) |
| 743 |
} |
| 744 |
iterator_reset <- function() { |
| 745 |
env_keep_alive$keepalive <- NULL |
| 746 |
return(data_iterator$f_reset(data_iterator$env)) |
| 747 |
} |
| 748 |
calling_env <- environment() |
| 749 |
|
| 750 |
dmat <- .Call( |
| 751 |
XGDMatrixCreateFromCallback_R, |
| 752 |
iterator_next, |
| 753 |
iterator_reset, |
| 754 |
calling_env, |
| 755 |
proxy_handle, |
| 756 |
nthread, |
| 757 |
missing, |
| 758 |
cache_prefix |
| 759 |
) |
| 760 |
|
| 761 |
attributes(dmat) <- list( |
| 762 |
class = c("xgb.DMatrix", "xgb.ExtMemDMatrix"), |
| 763 |
fields = attributes(proxy_handle)$fields |
| 764 |
) |
| 765 |
return(dmat) |
| 766 |
} |
| 767 |
|
| 768 |
|
| 769 |
#' QuantileDMatrix from External Data |
| 770 |
#' |
| 771 |
#' @description |
| 772 |
#' Create an `xgb.QuantileDMatrix` object (exact same class as would be returned by |
| 773 |
#' calling function [xgb.QuantileDMatrix()], with the same advantages and limitations) from |
| 774 |
#' external data supplied by [xgb.DataIter()], potentially passed in batches from |
| 775 |
#' a bigger set that might not fit entirely in memory, same way as [xgb.ExtMemDMatrix()]. |
| 776 |
#' |
| 777 |
#' Note that, while external data will only be loaded through the iterator (thus the full data |
| 778 |
#' might not be held entirely in-memory), the quantized representation of the data will get |
| 779 |
#' created in-memory, being concatenated from multiple calls to the data iterator. The quantized |
| 780 |
#' version is typically lighter than the original data, so there might be cases in which this |
| 781 |
#' representation could potentially fit in memory even if the full data does not. |
| 782 |
#' |
| 783 |
#' For more information, see the guide 'Using XGBoost External Memory Version': |
| 784 |
#' \url{https://xgboost.readthedocs.io/en/stable/tutorials/external_memory.html} |
| 785 |
#' @inheritParams xgb.ExtMemDMatrix |
| 786 |
#' @inheritParams xgb.QuantileDMatrix |
| 787 |
#' @return An 'xgb.DMatrix' object, with subclass 'xgb.QuantileDMatrix'. |
| 788 |
#' @seealso [xgb.DataIter()], [xgb.DataBatch()], [xgb.ExtMemDMatrix()], |
| 789 |
#' [xgb.QuantileDMatrix()] |
| 790 |
#' @export |
| 791 |
xgb.QuantileDMatrix.from_iterator <- function( # nolint |
| 792 |
data_iterator, |
| 793 |
missing = NA, |
| 794 |
nthread = NULL, |
| 795 |
ref = NULL, |
| 796 |
max_bin = NULL |
| 797 |
) { |
| 798 |
stopifnot(inherits(data_iterator, "xgb.DataIter")) |
| 799 |
if (!is.null(ref) && !inherits(ref, "xgb.DMatrix")) { |
| 800 |
stop("'ref' must be an xgb.DMatrix object.") |
| 801 |
} |
| 802 |
|
| 803 |
nthread <- as.integer(NVL(nthread, -1L)) |
| 804 |
|
| 805 |
env_keep_alive <- new.env() |
| 806 |
env_keep_alive$keepalive <- NULL |
| 807 |
proxy_handle <- .make.proxy.handle() |
| 808 |
on.exit({ |
| 809 |
.Call(XGDMatrixFree_R, proxy_handle) |
| 810 |
}) |
| 811 |
iterator_next <- function() { |
| 812 |
return(xgb.ProxyDMatrix(proxy_handle, data_iterator, env_keep_alive)) |
| 813 |
} |
| 814 |
iterator_reset <- function() { |
| 815 |
env_keep_alive$keepalive <- NULL |
| 816 |
return(data_iterator$f_reset(data_iterator$env)) |
| 817 |
} |
| 818 |
calling_env <- environment() |
| 819 |
|
| 820 |
dmat <- .Call( |
| 821 |
XGQuantileDMatrixCreateFromCallback_R, |
| 822 |
iterator_next, |
| 823 |
iterator_reset, |
| 824 |
calling_env, |
| 825 |
proxy_handle, |
| 826 |
nthread, |
| 827 |
missing, |
| 828 |
max_bin, |
| 829 |
ref |
| 830 |
) |
| 831 |
|
| 832 |
attributes(dmat) <- list( |
| 833 |
class = c("xgb.DMatrix", "xgb.QuantileDMatrix"), |
| 834 |
fields = attributes(proxy_handle)$fields |
| 835 |
) |
| 836 |
return(dmat) |
| 837 |
} |
| 838 |
|
| 839 |
#' Check whether DMatrix object has a field |
| 840 |
#' |
| 841 |
#' Checks whether an xgb.DMatrix object has a given field assigned to |
| 842 |
#' it, such as weights, labels, etc. |
| 843 |
#' @param object The DMatrix object to check for the given `info` field. |
| 844 |
#' @param info The field to check for presence or absence in `object`. |
| 845 |
#' @seealso [xgb.DMatrix()], [getinfo.xgb.DMatrix()], [setinfo.xgb.DMatrix()] |
| 846 |
#' @examples |
| 847 |
#' x <- matrix(1:10, nrow = 5) |
| 848 |
#' dm <- xgb.DMatrix(x, nthread = 1) |
| 849 |
#' |
| 850 |
#' # 'dm' so far does not have any fields set |
| 851 |
#' xgb.DMatrix.hasinfo(dm, "label") |
| 852 |
#' |
| 853 |
#' # Fields can be added after construction |
| 854 |
#' setinfo(dm, "label", 1:5) |
| 855 |
#' xgb.DMatrix.hasinfo(dm, "label") |
| 856 |
#' @export |
| 857 |
xgb.DMatrix.hasinfo <- function(object, info) { |
| 858 |
if (!inherits(object, "xgb.DMatrix")) { |
| 859 |
stop("Object is not an 'xgb.DMatrix'.") |
| 860 |
} |
| 861 |
if (.Call(XGCheckNullPtr_R, object)) { |
| 862 |
warning("xgb.DMatrix object is invalid. Must be constructed again.") |
| 863 |
return(FALSE) |
| 864 |
} |
| 865 |
return(NVL(attr(object, "fields")[[info]], FALSE)) |
| 866 |
} |
| 867 |
|
| 868 |
|
| 869 |
#' Dimensions of xgb.DMatrix |
| 870 |
#' |
| 871 |
#' Returns a vector of numbers of rows and of columns in an `xgb.DMatrix`. |
| 872 |
#' |
| 873 |
#' @param x Object of class `xgb.DMatrix` |
| 874 |
#' |
| 875 |
#' @details |
| 876 |
#' Note: since [nrow()] and [ncol()] internally use [dim()], they can also |
| 877 |
#' be directly used with an `xgb.DMatrix` object. |
| 878 |
#' |
| 879 |
#' @examples |
| 880 |
#' data(agaricus.train, package = "xgboost") |
| 881 |
#' |
| 882 |
#' train <- agaricus.train |
| 883 |
#' dtrain <- xgb.DMatrix(train$data, label = train$label, nthread = 2) |
| 884 |
#' |
| 885 |
#' stopifnot(nrow(dtrain) == nrow(train$data)) |
| 886 |
#' stopifnot(ncol(dtrain) == ncol(train$data)) |
| 887 |
#' stopifnot(all(dim(dtrain) == dim(train$data))) |
| 888 |
#' |
| 889 |
#' @export |
| 890 |
dim.xgb.DMatrix <- function(x) { |
| 891 |
c(.Call(XGDMatrixNumRow_R, x), .Call(XGDMatrixNumCol_R, x)) |
| 892 |
} |
| 893 |
|
| 894 |
|
| 895 |
#' Handling of column names of `xgb.DMatrix` |
| 896 |
#' |
| 897 |
#' Only column names are supported for `xgb.DMatrix`, thus setting of |
| 898 |
#' row names would have no effect and returned row names would be `NULL`. |
| 899 |
#' |
| 900 |
#' @param x Object of class `xgb.DMatrix`. |
| 901 |
#' @param value A list of two elements: the first one is ignored |
| 902 |
#' and the second one is column names |
| 903 |
#' |
| 904 |
#' @details |
| 905 |
#' Generic [dimnames()] methods are used by [colnames()]. |
| 906 |
#' Since row names are irrelevant, it is recommended to use [colnames()] directly. |
| 907 |
#' |
| 908 |
#' @examples |
| 909 |
#' data(agaricus.train, package = "xgboost") |
| 910 |
#' |
| 911 |
#' train <- agaricus.train |
| 912 |
#' dtrain <- xgb.DMatrix(train$data, label = train$label, nthread = 2) |
| 913 |
#' dimnames(dtrain) |
| 914 |
#' colnames(dtrain) |
| 915 |
#' colnames(dtrain) <- make.names(1:ncol(train$data)) |
| 916 |
#' print(dtrain, verbose = TRUE) |
| 917 |
#' |
| 918 |
#' @rdname dimnames.xgb.DMatrix |
| 919 |
#' @export |
| 920 |
dimnames.xgb.DMatrix <- function(x) { |
| 921 |
fn <- getinfo(x, "feature_name") |
| 922 |
## row names is null. |
| 923 |
list(NULL, fn) |
| 924 |
} |
| 925 |
|
| 926 |
#' @rdname dimnames.xgb.DMatrix |
| 927 |
#' @export |
| 928 |
`dimnames<-.xgb.DMatrix` <- function(x, value) { |
| 929 |
if (!is.list(value) || length(value) != 2L) |
| 930 |
stop("invalid 'dimnames' given: must be a list of two elements") |
| 931 |
if (!is.null(value[[1L]])) |
| 932 |
stop("xgb.DMatrix does not have rownames") |
| 933 |
if (is.null(value[[2]])) { |
| 934 |
setinfo(x, "feature_name", NULL) |
| 935 |
return(x) |
| 936 |
} |
| 937 |
if (ncol(x) != length(value[[2]])) { |
| 938 |
stop("can't assign ", length(value[[2]]), " colnames to a ", ncol(x), " column xgb.DMatrix") |
| 939 |
} |
| 940 |
setinfo(x, "feature_name", value[[2]]) |
| 941 |
x |
| 942 |
} |
| 943 |
|
| 944 |
|
| 945 |
#' Get or set information of xgb.DMatrix and xgb.Booster objects |
| 946 |
#' |
| 947 |
#' @param object Object of class `xgb.DMatrix` or `xgb.Booster`. |
| 948 |
#' @param name The name of the information field to get (see details). |
| 949 |
#' @return For `getinfo()`, will return the requested field. For `setinfo()`, |
| 950 |
#' will always return value `TRUE` if it succeeds. |
| 951 |
#' @details |
| 952 |
#' The `name` field can be one of the following for `xgb.DMatrix`: |
| 953 |
#' - label |
| 954 |
#' - weight |
| 955 |
#' - base_margin |
| 956 |
#' - label_lower_bound |
| 957 |
#' - label_upper_bound |
| 958 |
#' - group |
| 959 |
#' - feature_type |
| 960 |
#' - feature_name |
| 961 |
#' - nrow |
| 962 |
#' |
| 963 |
#' See the documentation for [xgb.DMatrix()] for more information about these fields. |
| 964 |
#' |
| 965 |
#' For `xgb.Booster`, can be one of the following: |
| 966 |
#' - `feature_type` |
| 967 |
#' - `feature_name` |
| 968 |
#' |
| 969 |
#' Note that, while 'qid' cannot be retrieved, it is possible to get the equivalent 'group' |
| 970 |
#' for a DMatrix that had 'qid' assigned. |
| 971 |
#' |
| 972 |
#' **Important**: when calling [setinfo()], the objects are modified in-place. See |
| 973 |
#' [xgb.copy.Booster()] for an idea of this in-place assignment works. |
| 974 |
#' @examples |
| 975 |
#' data(agaricus.train, package = "xgboost") |
| 976 |
#' |
| 977 |
#' dtrain <- with(agaricus.train, xgb.DMatrix(data, label = label, nthread = 2)) |
| 978 |
#' |
| 979 |
#' labels <- getinfo(dtrain, "label") |
| 980 |
#' setinfo(dtrain, "label", 1 - labels) |
| 981 |
#' |
| 982 |
#' labels2 <- getinfo(dtrain, "label") |
| 983 |
#' stopifnot(all(labels2 == 1 - labels)) |
| 984 |
#' @rdname getinfo |
| 985 |
#' @export |
| 986 |
getinfo <- function(object, name) UseMethod("getinfo") |
| 987 |
|
| 988 |
#' @rdname getinfo |
| 989 |
#' @export |
| 990 |
getinfo.xgb.DMatrix <- function(object, name) { |
| 991 |
allowed_int_fields <- 'group' |
| 992 |
allowed_float_fields <- c( |
| 993 |
'label', 'weight', 'base_margin', |
| 994 |
'label_lower_bound', 'label_upper_bound' |
| 995 |
) |
| 996 |
allowed_str_fields <- c("feature_type", "feature_name") |
| 997 |
allowed_fields <- c(allowed_float_fields, allowed_int_fields, allowed_str_fields, 'nrow') |
| 998 |
|
| 999 |
if (typeof(name) != "character" || |
| 1000 |
length(name) != 1 || |
| 1001 |
!name %in% allowed_fields) { |
| 1002 |
stop("getinfo: name must be one of the following\n", |
| 1003 |
paste(paste0("'", allowed_fields, "'"), collapse = ", ")) |
| 1004 |
} |
| 1005 |
if (name == "nrow") { |
| 1006 |
ret <- nrow(object) |
| 1007 |
} else if (name %in% allowed_str_fields) { |
| 1008 |
ret <- .Call(XGDMatrixGetStrFeatureInfo_R, object, name) |
| 1009 |
} else if (name %in% allowed_float_fields) { |
| 1010 |
ret <- .Call(XGDMatrixGetFloatInfo_R, object, name) |
| 1011 |
if (length(ret) > nrow(object)) { |
| 1012 |
ret <- matrix(ret, nrow = nrow(object), byrow = TRUE) |
| 1013 |
} |
| 1014 |
} else if (name %in% allowed_int_fields) { |
| 1015 |
if (name == "group") { |
| 1016 |
name <- "group_ptr" |
| 1017 |
} |
| 1018 |
ret <- .Call(XGDMatrixGetUIntInfo_R, object, name) |
| 1019 |
if (length(ret) > nrow(object)) { |
| 1020 |
ret <- matrix(ret, nrow = nrow(object), byrow = TRUE) |
| 1021 |
} |
| 1022 |
} |
| 1023 |
if (length(ret) == 0) return(NULL) |
| 1024 |
return(ret) |
| 1025 |
} |
| 1026 |
|
| 1027 |
#' @rdname getinfo |
| 1028 |
#' @param info The specific field of information to set. |
| 1029 |
#' |
| 1030 |
#' @details |
| 1031 |
#' See the documentation for [xgb.DMatrix()] for possible fields that can be set |
| 1032 |
#' (which correspond to arguments in that function). |
| 1033 |
#' |
| 1034 |
#' Note that the following fields are allowed in the construction of an `xgb.DMatrix` |
| 1035 |
#' but **are not** allowed here: |
| 1036 |
#' - data |
| 1037 |
#' - missing |
| 1038 |
#' - silent |
| 1039 |
#' - nthread |
| 1040 |
#' |
| 1041 |
#' @examples |
| 1042 |
#' data(agaricus.train, package = "xgboost") |
| 1043 |
#' |
| 1044 |
#' dtrain <- with(agaricus.train, xgb.DMatrix(data, label = label, nthread = 2)) |
| 1045 |
#' |
| 1046 |
#' labels <- getinfo(dtrain, "label") |
| 1047 |
#' setinfo(dtrain, "label", 1 - labels) |
| 1048 |
#' |
| 1049 |
#' labels2 <- getinfo(dtrain, "label") |
| 1050 |
#' stopifnot(all.equal(labels2, 1 - labels)) |
| 1051 |
#' @export |
| 1052 |
setinfo <- function(object, name, info) UseMethod("setinfo") |
| 1053 |
|
| 1054 |
#' @rdname getinfo |
| 1055 |
#' @export |
| 1056 |
setinfo.xgb.DMatrix <- function(object, name, info) { |
| 1057 |
.internal.setinfo.xgb.DMatrix(object, name, info) |
| 1058 |
attr(object, "fields")[[name]] <- TRUE |
| 1059 |
return(TRUE) |
| 1060 |
} |
| 1061 |
|
| 1062 |
.internal.setinfo.xgb.DMatrix <- function(object, name, info) { |
| 1063 |
if (name == "label") { |
| 1064 |
if (NROW(info) != nrow(object)) |
| 1065 |
stop("The length of labels must equal to the number of rows in the input data") |
| 1066 |
if (is.factor(info)) { |
| 1067 |
stop("'label' must be a numeric variable.") |
| 1068 |
} |
| 1069 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1070 |
return(TRUE) |
| 1071 |
} |
| 1072 |
if (name == "label_lower_bound") { |
| 1073 |
if (NROW(info) != nrow(object)) |
| 1074 |
stop("The length of lower-bound labels must equal to the number of rows in the input data") |
| 1075 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1076 |
return(TRUE) |
| 1077 |
} |
| 1078 |
if (name == "label_upper_bound") { |
| 1079 |
if (NROW(info) != nrow(object)) |
| 1080 |
stop("The length of upper-bound labels must equal to the number of rows in the input data") |
| 1081 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1082 |
return(TRUE) |
| 1083 |
} |
| 1084 |
if (name == "weight") { |
| 1085 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1086 |
return(TRUE) |
| 1087 |
} |
| 1088 |
if (name == "base_margin") { |
| 1089 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1090 |
return(TRUE) |
| 1091 |
} |
| 1092 |
if (name == "group") { |
| 1093 |
if (sum(info) != nrow(object)) |
| 1094 |
stop("The sum of groups must equal to the number of rows in the input data") |
| 1095 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1096 |
return(TRUE) |
| 1097 |
} |
| 1098 |
if (name == "qid") { |
| 1099 |
if (NROW(info) != nrow(object)) |
| 1100 |
stop("The length of qid assignments must equal to the number of rows in the input data") |
| 1101 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1102 |
return(TRUE) |
| 1103 |
} |
| 1104 |
if (name == "feature_weights") { |
| 1105 |
if (NROW(info) != ncol(object)) { |
| 1106 |
stop("The number of feature weights must equal to the number of columns in the input data") |
| 1107 |
} |
| 1108 |
.Call(XGDMatrixSetInfo_R, object, name, info) |
| 1109 |
return(TRUE) |
| 1110 |
} |
| 1111 |
|
| 1112 |
set_feat_info <- function(name) { |
| 1113 |
msg <- sprintf( |
| 1114 |
"The number of %s must equal to the number of columns in the input data. %s vs. %s", |
| 1115 |
name, |
| 1116 |
length(info), |
| 1117 |
ncol(object) |
| 1118 |
) |
| 1119 |
if (!is.null(info)) { |
| 1120 |
info <- as.list(info) |
| 1121 |
if (length(info) != ncol(object)) { |
| 1122 |
stop(msg) |
| 1123 |
} |
| 1124 |
} |
| 1125 |
.Call(XGDMatrixSetStrFeatureInfo_R, object, name, info) |
| 1126 |
} |
| 1127 |
if (name == "feature_name") { |
| 1128 |
set_feat_info("feature_name") |
| 1129 |
return(TRUE) |
| 1130 |
} |
| 1131 |
if (name == "feature_type") { |
| 1132 |
set_feat_info("feature_type") |
| 1133 |
return(TRUE) |
| 1134 |
} |
| 1135 |
stop("setinfo: unknown info name ", name) |
| 1136 |
} |
| 1137 |
|
| 1138 |
#' Get Quantile Cuts from DMatrix |
| 1139 |
#' |
| 1140 |
#' @description |
| 1141 |
#' Get the quantile cuts (a.k.a. borders) from an `xgb.DMatrix` |
| 1142 |
#' that has been quantized for the histogram method (`tree_method = "hist"`). |
| 1143 |
#' |
| 1144 |
#' These cuts are used in order to assign observations to bins - i.e. these are ordered |
| 1145 |
#' boundaries which are used to determine assignment condition `border_low < x < border_high`. |
| 1146 |
#' As such, the first and last bin will be outside of the range of the data, so as to include |
| 1147 |
#' all of the observations there. |
| 1148 |
#' |
| 1149 |
#' If a given column has 'n' bins, then there will be 'n+1' cuts / borders for that column, |
| 1150 |
#' which will be output in sorted order from lowest to highest. |
| 1151 |
#' |
| 1152 |
#' Different columns can have different numbers of bins according to their range. |
| 1153 |
#' @param dmat An `xgb.DMatrix` object, as returned by [xgb.DMatrix()]. |
| 1154 |
#' @param output Output format for the quantile cuts. Possible options are: |
| 1155 |
#' - "list"` will return the output as a list with one entry per column, where |
| 1156 |
#' each column will have a numeric vector with the cuts. The list will be named if |
| 1157 |
#' `dmat` has column names assigned to it. |
| 1158 |
#' - `"arrays"` will return a list with entries `indptr` (base-0 indexing) and |
| 1159 |
#' `data`. Here, the cuts for column 'i' are obtained by slicing 'data' from entries |
| 1160 |
#' ` indptr[i]+1` to `indptr[i+1]`. |
| 1161 |
#' @return The quantile cuts, in the format specified by parameter `output`. |
| 1162 |
#' @examples |
| 1163 |
#' data(mtcars) |
| 1164 |
#' |
| 1165 |
#' y <- mtcars$mpg |
| 1166 |
#' x <- as.matrix(mtcars[, -1]) |
| 1167 |
#' dm <- xgb.DMatrix(x, label = y, nthread = 1) |
| 1168 |
#' |
| 1169 |
#' # DMatrix is not quantized right away, but will be once a hist model is generated |
| 1170 |
#' model <- xgb.train( |
| 1171 |
#' data = dm, |
| 1172 |
#' params = xgb.params(tree_method = "hist", max_bin = 8, nthread = 1), |
| 1173 |
#' nrounds = 3 |
| 1174 |
#' ) |
| 1175 |
#' |
| 1176 |
#' # Now can get the quantile cuts |
| 1177 |
#' xgb.get.DMatrix.qcut(dm) |
| 1178 |
#' @export |
| 1179 |
xgb.get.DMatrix.qcut <- function(dmat, output = c("list", "arrays")) { # nolint |
| 1180 |
stopifnot(inherits(dmat, "xgb.DMatrix")) |
| 1181 |
output <- head(output, 1L) |
| 1182 |
stopifnot(output %in% c("list", "arrays")) |
| 1183 |
res <- .Call(XGDMatrixGetQuantileCut_R, dmat) |
| 1184 |
if (output == "arrays") { |
| 1185 |
return(res) |
| 1186 |
} else { |
| 1187 |
feature_names <- getinfo(dmat, "feature_name") |
| 1188 |
ncols <- length(res$indptr) - 1 |
| 1189 |
out <- lapply( |
| 1190 |
seq(1, ncols), |
| 1191 |
function(col) { |
| 1192 |
st <- res$indptr[col] |
| 1193 |
end <- res$indptr[col + 1] |
| 1194 |
if (end <= st) { |
| 1195 |
return(numeric()) |
| 1196 |
} |
| 1197 |
return(res$data[seq(1 + st, end)]) |
| 1198 |
} |
| 1199 |
) |
| 1200 |
if (NROW(feature_names)) { |
| 1201 |
names(out) <- feature_names |
| 1202 |
} |
| 1203 |
return(out) |
| 1204 |
} |
| 1205 |
} |
| 1206 |
|
| 1207 |
#' Get Number of Non-Missing Entries in DMatrix |
| 1208 |
#' |
| 1209 |
#' @param dmat An `xgb.DMatrix` object, as returned by [xgb.DMatrix()]. |
| 1210 |
#' @return The number of non-missing entries in the DMatrix. |
| 1211 |
#' @export |
| 1212 |
xgb.get.DMatrix.num.non.missing <- function(dmat) { # nolint |
| 1213 |
stopifnot(inherits(dmat, "xgb.DMatrix")) |
| 1214 |
return(.Call(XGDMatrixNumNonMissing_R, dmat)) |
| 1215 |
} |
| 1216 |
|
| 1217 |
#' Get DMatrix Data |
| 1218 |
#' |
| 1219 |
#' @param dmat An `xgb.DMatrix` object, as returned by [xgb.DMatrix()]. |
| 1220 |
#' @return The data held in the DMatrix, as a sparse CSR matrix (class `dgRMatrix` |
| 1221 |
#' from package `Matrix`). If it had feature names, these will be added as column names |
| 1222 |
#' in the output. |
| 1223 |
#' @export |
| 1224 |
xgb.get.DMatrix.data <- function(dmat) { |
| 1225 |
stopifnot(inherits(dmat, "xgb.DMatrix")) |
| 1226 |
res <- .Call(XGDMatrixGetDataAsCSR_R, dmat) |
| 1227 |
out <- methods::new("dgRMatrix") |
| 1228 |
nrows <- as.integer(length(res$indptr) - 1) |
| 1229 |
out@p <- res$indptr |
| 1230 |
out@j <- res$indices |
| 1231 |
out@x <- res$data |
| 1232 |
out@Dim <- as.integer(c(nrows, res$ncols)) |
| 1233 |
|
| 1234 |
feature_names <- getinfo(dmat, "feature_name") |
| 1235 |
dim_names <- list(NULL, NULL) |
| 1236 |
if (NROW(feature_names)) { |
| 1237 |
dim_names[[2L]] <- feature_names |
| 1238 |
} |
| 1239 |
out@Dimnames <- dim_names |
| 1240 |
return(out) |
| 1241 |
} |
| 1242 |
|
| 1243 |
#' Slice DMatrix |
| 1244 |
#' |
| 1245 |
#' Get a new DMatrix containing the specified rows of original xgb.DMatrix object. |
| 1246 |
#' |
| 1247 |
#' @param object Object of class `xgb.DMatrix`. |
| 1248 |
#' @param idxset An integer vector of indices of rows needed (base-1 indexing). |
| 1249 |
#' @param allow_groups Whether to allow slicing an `xgb.DMatrix` with `group` (or |
| 1250 |
#' equivalently `qid`) field. Note that in such case, the result will not have |
| 1251 |
#' the groups anymore - they need to be set manually through [setinfo()]. |
| 1252 |
#' @param colset Currently not used (columns subsetting is not available). |
| 1253 |
#' |
| 1254 |
#' @examples |
| 1255 |
#' data(agaricus.train, package = "xgboost") |
| 1256 |
#' |
| 1257 |
#' dtrain <- with(agaricus.train, xgb.DMatrix(data, label = label, nthread = 2)) |
| 1258 |
#' |
| 1259 |
#' dsub <- xgb.slice.DMatrix(dtrain, 1:42) |
| 1260 |
#' labels1 <- getinfo(dsub, "label") |
| 1261 |
#' |
| 1262 |
#' dsub <- dtrain[1:42, ] |
| 1263 |
#' labels2 <- getinfo(dsub, "label") |
| 1264 |
#' all.equal(labels1, labels2) |
| 1265 |
#' |
| 1266 |
#' @rdname xgb.slice.DMatrix |
| 1267 |
#' @export |
| 1268 |
xgb.slice.DMatrix <- function(object, idxset, allow_groups = FALSE) { |
| 1269 |
if (!inherits(object, "xgb.DMatrix")) { |
| 1270 |
stop("object must be xgb.DMatrix") |
| 1271 |
} |
| 1272 |
ret <- .Call(XGDMatrixSliceDMatrix_R, object, idxset, allow_groups) |
| 1273 |
|
| 1274 |
attr_list <- attributes(object) |
| 1275 |
nr <- nrow(object) |
| 1276 |
len <- sapply(attr_list, NROW) |
| 1277 |
ind <- which(len == nr) |
| 1278 |
if (length(ind) > 0) { |
| 1279 |
nms <- names(attr_list)[ind] |
| 1280 |
for (i in seq_along(ind)) { |
| 1281 |
obj_attr <- attr(object, nms[i]) |
| 1282 |
if (NCOL(obj_attr) > 1) { |
| 1283 |
attr(ret, nms[i]) <- obj_attr[idxset, ] |
| 1284 |
} else { |
| 1285 |
attr(ret, nms[i]) <- obj_attr[idxset] |
| 1286 |
} |
| 1287 |
} |
| 1288 |
} |
| 1289 |
|
| 1290 |
out <- structure(ret, class = "xgb.DMatrix") |
| 1291 |
parent_fields <- as.list(attributes(object)$fields) |
| 1292 |
if (NROW(parent_fields)) { |
| 1293 |
child_fields <- parent_fields[!(names(parent_fields) %in% c("group", "qid"))] |
| 1294 |
child_fields <- as.environment(child_fields) |
| 1295 |
attributes(out)$fields <- child_fields |
| 1296 |
} |
| 1297 |
return(out) |
| 1298 |
} |
| 1299 |
|
| 1300 |
#' @rdname xgb.slice.DMatrix |
| 1301 |
#' @export |
| 1302 |
`[.xgb.DMatrix` <- function(object, idxset, colset = NULL) { |
| 1303 |
xgb.slice.DMatrix(object, idxset) |
| 1304 |
} |
| 1305 |
|
| 1306 |
|
| 1307 |
#' Print xgb.DMatrix |
| 1308 |
#' |
| 1309 |
#' Print information about xgb.DMatrix. |
| 1310 |
#' Currently it displays dimensions and presence of info-fields and colnames. |
| 1311 |
#' |
| 1312 |
#' @param x An xgb.DMatrix object. |
| 1313 |
#' @param verbose Whether to print colnames (when present). |
| 1314 |
#' @param ... Not currently used. |
| 1315 |
#' |
| 1316 |
#' @examples |
| 1317 |
#' data(agaricus.train, package = "xgboost") |
| 1318 |
#' |
| 1319 |
#' dtrain <- with(agaricus.train, xgb.DMatrix(data, label = label, nthread = 2)) |
| 1320 |
#' dtrain |
| 1321 |
#' |
| 1322 |
#' print(dtrain, verbose = TRUE) |
| 1323 |
#' |
| 1324 |
#' @method print xgb.DMatrix |
| 1325 |
#' @export |
| 1326 |
print.xgb.DMatrix <- function(x, verbose = FALSE, ...) { |
| 1327 |
if (.Call(XGCheckNullPtr_R, x)) { |
| 1328 |
cat("INVALID xgb.DMatrix object. Must be constructed anew.\n") |
| 1329 |
return(invisible(x)) |
| 1330 |
} |
| 1331 |
class_print <- if (inherits(x, "xgb.QuantileDMatrix")) { |
| 1332 |
"xgb.QuantileDMatrix" |
| 1333 |
} else if (inherits(x, "xgb.ExtMemDMatrix")) { |
| 1334 |
"xgb.ExtMemDMatrix" |
| 1335 |
} else if (inherits(x, "xgb.ProxyDMatrix")) { |
| 1336 |
"xgb.ProxyDMatrix" |
| 1337 |
} else { |
| 1338 |
"xgb.DMatrix" |
| 1339 |
} |
| 1340 |
|
| 1341 |
cat(class_print, ' dim:', nrow(x), 'x', ncol(x), ' info: ') |
| 1342 |
infos <- names(attributes(x)$fields) |
| 1343 |
infos <- infos[infos != "feature_name"] |
| 1344 |
if (!NROW(infos)) infos <- "NA" |
| 1345 |
infos <- infos[order(infos)] |
| 1346 |
infos <- paste(infos, collapse = ", ") |
| 1347 |
cat(infos) |
| 1348 |
cnames <- colnames(x) |
| 1349 |
cat(' colnames:') |
| 1350 |
if (verbose && !is.null(cnames)) { |
| 1351 |
cat("\n'") |
| 1352 |
cat(cnames, sep = "','") |
| 1353 |
cat("'") |
| 1354 |
} else { |
| 1355 |
if (is.null(cnames)) cat(' no') |
| 1356 |
else cat(' yes') |
| 1357 |
} |
| 1358 |
cat("\n") |
| 1359 |
invisible(x) |
| 1360 |
} |