| 1 |
# Construct an internal XGBoost Booster and get its current number of rounds. |
| 2 |
# internal utility function |
| 3 |
# Note: the number of rounds in the C booster gets reset to zero when changing |
| 4 |
# key booster parameters like 'process_type=update', but in some cases, when |
| 5 |
# replacing previous iterations, it needs to make a check that the new number |
| 6 |
# of iterations doesn't exceed the previous ones, hence it keeps track of the |
| 7 |
# current number of iterations before resetting the parameters in order to |
| 8 |
# perform the check later on. |
| 9 |
xgb.Booster <- function(params, cachelist, modelfile) { |
| 10 |
if (typeof(cachelist) != "list" || |
| 11 |
!all(vapply(cachelist, inherits, logical(1), what = 'xgb.DMatrix'))) { |
| 12 |
stop("cachelist must be a list of xgb.DMatrix objects") |
| 13 |
} |
| 14 |
## Load existing model, dispatch for on disk model file and in memory buffer |
| 15 |
if (!is.null(modelfile)) { |
| 16 |
if (is.character(modelfile)) { |
| 17 |
## A filename |
| 18 |
bst <- .Call(XGBoosterCreate_R, cachelist) |
| 19 |
modelfile <- path.expand(modelfile) |
| 20 |
.Call(XGBoosterLoadModel_R, xgb.get.handle(bst), enc2utf8(modelfile[1])) |
| 21 |
niter <- xgb.get.num.boosted.rounds(bst) |
| 22 |
if (length(params) > 0) { |
| 23 |
xgb.model.parameters(bst) <- params |
| 24 |
} |
| 25 |
return(list(bst = bst, niter = niter)) |
| 26 |
} else if (is.raw(modelfile)) { |
| 27 |
## A memory buffer |
| 28 |
bst <- xgb.load.raw(modelfile) |
| 29 |
niter <- xgb.get.num.boosted.rounds(bst) |
| 30 |
xgb.model.parameters(bst) <- params |
| 31 |
return(list(bst = bst, niter = niter)) |
| 32 |
} else if (inherits(modelfile, "xgb.Booster")) { |
| 33 |
## A booster object |
| 34 |
bst <- .Call(XGDuplicate_R, modelfile) |
| 35 |
niter <- xgb.get.num.boosted.rounds(bst) |
| 36 |
xgb.model.parameters(bst) <- params |
| 37 |
return(list(bst = bst, niter = niter)) |
| 38 |
} else { |
| 39 |
stop("modelfile must be either character filename, or raw booster dump, or xgb.Booster object") |
| 40 |
} |
| 41 |
} |
| 42 |
## Create new model |
| 43 |
bst <- .Call(XGBoosterCreate_R, cachelist) |
| 44 |
if (length(params) > 0) { |
| 45 |
xgb.model.parameters(bst) <- params |
| 46 |
} |
| 47 |
return(list(bst = bst, niter = 0L)) |
| 48 |
} |
| 49 |
|
| 50 |
# Check whether xgb.Booster handle is null |
| 51 |
# internal utility function |
| 52 |
is.null.handle <- function(handle) { |
| 53 |
if (is.null(handle)) return(TRUE) |
| 54 |
|
| 55 |
if (!inherits(handle, "externalptr")) |
| 56 |
stop("argument type must be 'externalptr'") |
| 57 |
|
| 58 |
return(.Call(XGCheckNullPtr_R, handle)) |
| 59 |
} |
| 60 |
|
| 61 |
# Return a verified to be valid handle out of xgb.Booster |
| 62 |
# internal utility function |
| 63 |
xgb.get.handle <- function(object) { |
| 64 |
if (inherits(object, "xgb.Booster")) { |
| 65 |
handle <- object$ptr |
| 66 |
if (is.null(handle) || !inherits(handle, "externalptr")) { |
| 67 |
stop("'xgb.Booster' object is corrupted or is from an incompatible XGBoost version.") |
| 68 |
} |
| 69 |
} else { |
| 70 |
stop("argument must be an 'xgb.Booster' object.") |
| 71 |
} |
| 72 |
if (is.null.handle(handle)) { |
| 73 |
stop("invalid 'xgb.Booster' (blank 'externalptr').") |
| 74 |
} |
| 75 |
return(handle) |
| 76 |
} |
| 77 |
|
| 78 |
#' Predict method for XGBoost model |
| 79 |
#' |
| 80 |
#' Predict values on data based on XGBoost model. |
| 81 |
#' |
| 82 |
#' @param object Object of class `xgb.Booster`. |
| 83 |
#' @param newdata Takes `data.frame`, `matrix`, `dgCMatrix`, `dgRMatrix`, `dsparseVector`, |
| 84 |
#' local data file, or `xgb.DMatrix`. |
| 85 |
#' |
| 86 |
#' For single-row predictions on sparse data, it is recommended to use CSR format. If passing |
| 87 |
#' a sparse vector, it will take it as a row vector. |
| 88 |
#' |
| 89 |
#' Note that, for repeated predictions on the same data, one might want to create a DMatrix to |
| 90 |
#' pass here instead of passing R types like matrices or data frames, as predictions will be |
| 91 |
#' faster on DMatrix. |
| 92 |
#' |
| 93 |
#' If `newdata` is a `data.frame`, be aware that: |
| 94 |
#' - Columns will be converted to numeric if they aren't already, which could potentially make |
| 95 |
#' the operation slower than in an equivalent `matrix` object. |
| 96 |
#' - The order of the columns must match with that of the data from which the model was fitted |
| 97 |
#' (i.e. columns will not be referenced by their names, just by their order in the data), |
| 98 |
#' unless passing `validate_features = TRUE` (which is not the default). |
| 99 |
#' - If the model was fitted to data with categorical columns, these columns must be of |
| 100 |
#' `factor` type here, and must use the same encoding (i.e. have the same levels). |
| 101 |
#' - If `newdata` contains any `factor` columns, they will be converted to base-0 |
| 102 |
#' encoding (same as during DMatrix creation) - hence, one should not pass a `factor` |
| 103 |
#' under a column which during training had a different type. |
| 104 |
#' - Any columns with type other than `factor` will be interpreted as numeric. |
| 105 |
#' @param missing Float value that represents missing values in data |
| 106 |
#' (e.g., 0 or some other extreme value). |
| 107 |
#' |
| 108 |
#' This parameter is not used when `newdata` is an `xgb.DMatrix` - in such cases, |
| 109 |
#' should pass this as an argument to the DMatrix constructor instead. |
| 110 |
#' @param outputmargin Whether the prediction should be returned in the form of |
| 111 |
#' original untransformed sum of predictions from boosting iterations' results. |
| 112 |
#' E.g., setting `outputmargin = TRUE` for logistic regression would return log-odds |
| 113 |
#' instead of probabilities. |
| 114 |
#' @param predleaf Whether to predict per-tree leaf indices. |
| 115 |
#' @param predcontrib Whether to return feature contributions to individual predictions (see Details). |
| 116 |
#' @param approxcontrib Whether to use a fast approximation for feature contributions (see Details). |
| 117 |
#' @param predinteraction Whether to return contributions of feature interactions to individual predictions (see Details). |
| 118 |
#' @param training Whether the prediction result is used for training. For dart booster, |
| 119 |
#' training predicting will perform dropout. |
| 120 |
#' @param iterationrange Sequence of rounds/iterations from the model to use for prediction, specified by passing |
| 121 |
#' a two-dimensional vector with the start and end numbers in the sequence (same format as R's `seq` - i.e. |
| 122 |
#' base-1 indexing, and inclusive of both ends). |
| 123 |
#' |
| 124 |
#' For example, passing `c(1,20)` will predict using the first twenty iterations, while passing `c(1,1)` will |
| 125 |
#' predict using only the first one. |
| 126 |
#' |
| 127 |
#' If passing `NULL`, will either stop at the best iteration if the model used early stopping, or use all |
| 128 |
#' of the iterations (rounds) otherwise. |
| 129 |
#' |
| 130 |
#' If passing "all", will use all of the rounds regardless of whether the model had early stopping or not. |
| 131 |
#' |
| 132 |
#' Not applicable to `gblinear` booster. |
| 133 |
#' @param strict_shape Whether to always return an array with the same dimensions for the given prediction mode |
| 134 |
#' regardless of the model type - meaning that, for example, both a multi-class and a binary classification |
| 135 |
#' model would generate output arrays with the same number of dimensions, with the 'class' dimension having |
| 136 |
#' size equal to '1' for the binary model. |
| 137 |
#' |
| 138 |
#' If passing `FALSE` (the default), dimensions will be simplified according to the model type, so that a |
| 139 |
#' binary classification model for example would not have a redundant dimension for 'class'. |
| 140 |
#' |
| 141 |
#' See documentation for the return type for the exact shape of the output arrays for each prediction mode. |
| 142 |
#' @param avoid_transpose Whether to output the resulting predictions in the same memory layout in which they |
| 143 |
#' are generated by the core XGBoost library, without transposing them to match the expected output shape. |
| 144 |
#' |
| 145 |
#' Internally, XGBoost uses row-major order for the predictions it generates, while R arrays use column-major |
| 146 |
#' order, hence the result needs to be transposed in order to have the expected shape when represented as |
| 147 |
#' an R array or matrix, which might be a slow operation. |
| 148 |
#' |
| 149 |
#' If passing `TRUE`, then the result will have dimensions in reverse order - for example, rows |
| 150 |
#' will be the last dimensions instead of the first dimension. |
| 151 |
#' @param base_margin Base margin used for boosting from existing model (raw score that gets added to |
| 152 |
#' all observations independently of the trees in the model). |
| 153 |
#' |
| 154 |
#' If supplied, should be either a vector with length equal to the number of rows in `newdata` |
| 155 |
#' (for objectives which produces a single score per observation), or a matrix with number of |
| 156 |
#' rows matching to the number rows in `newdata` and number of columns matching to the number |
| 157 |
#' of scores estimated by the model (e.g. number of classes for multi-class classification). |
| 158 |
#' |
| 159 |
#' Note that, if `newdata` is an `xgb.DMatrix` object, this argument will |
| 160 |
#' be ignored as it needs to be added to the DMatrix instead (e.g. by passing it as |
| 161 |
#' an argument in its constructor, or by calling [setinfo.xgb.DMatrix()]. |
| 162 |
#' @param validate_features When `TRUE`, validate that the Booster's and newdata's |
| 163 |
#' feature_names match (only applicable when both `object` and `newdata` have feature names). |
| 164 |
#' |
| 165 |
#' If the column names differ and `newdata` is not an `xgb.DMatrix`, will try to reorder |
| 166 |
#' the columns in `newdata` to match with the booster's. |
| 167 |
#' |
| 168 |
#' If the booster has feature types and `newdata` is either an `xgb.DMatrix` or |
| 169 |
#' `data.frame`, will additionally verify that categorical columns are of the |
| 170 |
#' correct type in `newdata`, throwing an error if they do not match. |
| 171 |
#' |
| 172 |
#' If passing `FALSE`, it is assumed that the feature names and types are the same, |
| 173 |
#' and come in the same order as in the training data. |
| 174 |
#' |
| 175 |
#' Note that this check might add some sizable latency to the predictions, so it's |
| 176 |
#' recommended to disable it for performance-sensitive applications. |
| 177 |
#' @param ... Not used. |
| 178 |
#' |
| 179 |
#' @details |
| 180 |
#' Note that `iterationrange` would currently do nothing for predictions from "gblinear", |
| 181 |
#' since "gblinear" doesn't keep its boosting history. |
| 182 |
#' |
| 183 |
#' One possible practical applications of the `predleaf` option is to use the model |
| 184 |
#' as a generator of new features which capture non-linearity and interactions, |
| 185 |
#' e.g., as implemented in [xgb.create.features()]. |
| 186 |
#' |
| 187 |
#' Setting `predcontrib = TRUE` allows to calculate contributions of each feature to |
| 188 |
#' individual predictions. For "gblinear" booster, feature contributions are simply linear terms |
| 189 |
#' (feature_beta * feature_value). For "gbtree" booster, feature contributions are SHAP |
| 190 |
#' values (Lundberg 2017) that sum to the difference between the expected output |
| 191 |
#' of the model and the current prediction (where the hessian weights are used to compute the expectations). |
| 192 |
#' Setting `approxcontrib = TRUE` approximates these values following the idea explained |
| 193 |
#' in \url{http://blog.datadive.net/interpreting-random-forests/}. |
| 194 |
#' |
| 195 |
#' With `predinteraction = TRUE`, SHAP values of contributions of interaction of each pair of features |
| 196 |
#' are computed. Note that this operation might be rather expensive in terms of compute and memory. |
| 197 |
#' Since it quadratically depends on the number of features, it is recommended to perform selection |
| 198 |
#' of the most important features first. See below about the format of the returned results. |
| 199 |
#' |
| 200 |
#' The `predict()` method uses as many threads as defined in `xgb.Booster` object (all by default). |
| 201 |
#' If you want to change their number, assign a new number to `nthread` using [xgb.model.parameters<-()]. |
| 202 |
#' Note that converting a matrix to [xgb.DMatrix()] uses multiple threads too. |
| 203 |
#' |
| 204 |
#' @return |
| 205 |
#' A numeric vector or array, with corresponding dimensions depending on the prediction mode and on |
| 206 |
#' parameter `strict_shape` as follows: |
| 207 |
#' |
| 208 |
#' If passing `strict_shape=FALSE`:\itemize{ |
| 209 |
#' \item For regression or binary classification: a vector of length `nrows`. |
| 210 |
#' \item For multi-class and multi-target objectives: a matrix of dimensions `[nrows, ngroups]`. |
| 211 |
#' |
| 212 |
#' Note that objective variant `multi:softmax` defaults towards predicting most likely class (a vector |
| 213 |
#' `nrows`) instead of per-class probabilities. |
| 214 |
#' \item For `predleaf`: a matrix with one column per tree. |
| 215 |
#' |
| 216 |
#' For multi-class / multi-target, they will be arranged so that columns in the output will have |
| 217 |
#' the leafs from one group followed by leafs of the other group (e.g. order will be `group1:feat1`, |
| 218 |
#' `group1:feat2`, ..., `group2:feat1`, `group2:feat2`, ...). |
| 219 |
#' |
| 220 |
#' If there is more than one parallel tree (e.g. random forests), the parallel trees will be the |
| 221 |
#' last grouping in the resulting order, which will still be 2D. |
| 222 |
#' \item For `predcontrib`: when not multi-class / multi-target, a matrix with dimensions |
| 223 |
#' `[nrows, nfeats+1]`. The last "+ 1" column corresponds to the baseline value. |
| 224 |
#' |
| 225 |
#' For multi-class and multi-target objectives, will be an array with dimensions `[nrows, ngroups, nfeats+1]`. |
| 226 |
#' |
| 227 |
#' The contribution values are on the scale of untransformed margin (e.g., for binary classification, |
| 228 |
#' the values are log-odds deviations from the baseline). |
| 229 |
#' \item For `predinteraction`: when not multi-class / multi-target, the output is a 3D array of |
| 230 |
#' dimensions `[nrows, nfeats+1, nfeats+1]`. The off-diagonal (in the last two dimensions) |
| 231 |
#' elements represent different feature interaction contributions. The array is symmetric w.r.t. the last |
| 232 |
#' two dimensions. The "+ 1" columns corresponds to the baselines. Summing this array along the last |
| 233 |
#' dimension should produce practically the same result as `predcontrib = TRUE`. |
| 234 |
#' |
| 235 |
#' For multi-class and multi-target, will be a 4D array with dimensions `[nrows, ngroups, nfeats+1, nfeats+1]` |
| 236 |
#' } |
| 237 |
#' |
| 238 |
#' If passing `strict_shape=TRUE`, the result is always a matrix (if 2D) or array (if 3D or higher): |
| 239 |
#' - For normal predictions, the dimension is `[nrows, ngroups]`. |
| 240 |
#' - For `predcontrib=TRUE`, the dimension is `[nrows, ngroups, nfeats+1]`. |
| 241 |
#' - For `predinteraction=TRUE`, the dimension is `[nrows, ngroups, nfeats+1, nfeats+1]`. |
| 242 |
#' - For `predleaf=TRUE`, the dimension is `[nrows, niter, ngroups, num_parallel_tree]`. |
| 243 |
#' |
| 244 |
#' If passing `avoid_transpose=TRUE`, then the dimensions in all cases will be in reverse order - for |
| 245 |
#' example, for `predinteraction`, they will be `[nfeats+1, nfeats+1, ngroups, nrows]` |
| 246 |
#' instead of `[nrows, ngroups, nfeats+1, nfeats+1]`. |
| 247 |
#' @seealso [xgb.train()] |
| 248 |
#' @references |
| 249 |
#' 1. Scott M. Lundberg, Su-In Lee, "A Unified Approach to Interpreting Model Predictions", |
| 250 |
#' NIPS Proceedings 2017, \url{https://arxiv.org/abs/1705.07874} |
| 251 |
#' 2. Scott M. Lundberg, Su-In Lee, "Consistent feature attribution for tree ensembles", |
| 252 |
#' \url{https://arxiv.org/abs/1706.06060} |
| 253 |
#' |
| 254 |
#' @examples |
| 255 |
#' \dontshow{RhpcBLASctl::omp_set_num_threads(1)} |
| 256 |
#' ## binary classification: |
| 257 |
#' |
| 258 |
#' data(agaricus.train, package = "xgboost") |
| 259 |
#' data(agaricus.test, package = "xgboost") |
| 260 |
#' |
| 261 |
#' ## Keep the number of threads to 2 for examples |
| 262 |
#' nthread <- 2 |
| 263 |
#' data.table::setDTthreads(nthread) |
| 264 |
#' |
| 265 |
#' train <- agaricus.train |
| 266 |
#' test <- agaricus.test |
| 267 |
#' |
| 268 |
#' bst <- xgb.train( |
| 269 |
#' data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 270 |
#' nrounds = 5, |
| 271 |
#' params = xgb.params( |
| 272 |
#' max_depth = 2, |
| 273 |
#' nthread = nthread, |
| 274 |
#' objective = "binary:logistic" |
| 275 |
#' ) |
| 276 |
#' ) |
| 277 |
#' |
| 278 |
#' # use all trees by default |
| 279 |
#' pred <- predict(bst, test$data) |
| 280 |
#' # use only the 1st tree |
| 281 |
#' pred1 <- predict(bst, test$data, iterationrange = c(1, 1)) |
| 282 |
#' |
| 283 |
#' # Predicting tree leafs: |
| 284 |
#' # the result is an nsamples X ntrees matrix |
| 285 |
#' pred_leaf <- predict(bst, test$data, predleaf = TRUE) |
| 286 |
#' str(pred_leaf) |
| 287 |
#' |
| 288 |
#' # Predicting feature contributions to predictions: |
| 289 |
#' # the result is an nsamples X (nfeatures + 1) matrix |
| 290 |
#' pred_contr <- predict(bst, test$data, predcontrib = TRUE) |
| 291 |
#' str(pred_contr) |
| 292 |
#' # verify that contributions' sums are equal to log-odds of predictions (up to float precision): |
| 293 |
#' summary(rowSums(pred_contr) - qlogis(pred)) |
| 294 |
#' # for the 1st record, let's inspect its features that had non-zero contribution to prediction: |
| 295 |
#' contr1 <- pred_contr[1,] |
| 296 |
#' contr1 <- contr1[-length(contr1)] # drop intercept |
| 297 |
#' contr1 <- contr1[contr1 != 0] # drop non-contributing features |
| 298 |
#' contr1 <- contr1[order(abs(contr1))] # order by contribution magnitude |
| 299 |
#' old_mar <- par("mar") |
| 300 |
#' par(mar = old_mar + c(0,7,0,0)) |
| 301 |
#' barplot(contr1, horiz = TRUE, las = 2, xlab = "contribution to prediction in log-odds") |
| 302 |
#' par(mar = old_mar) |
| 303 |
#' |
| 304 |
#' |
| 305 |
#' ## multiclass classification in iris dataset: |
| 306 |
#' |
| 307 |
#' lb <- as.numeric(iris$Species) - 1 |
| 308 |
#' num_class <- 3 |
| 309 |
#' |
| 310 |
#' set.seed(11) |
| 311 |
#' |
| 312 |
#' bst <- xgb.train( |
| 313 |
#' data = xgb.DMatrix(as.matrix(iris[, -5], nthread = 1), label = lb), |
| 314 |
#' nrounds = 10, |
| 315 |
#' params = xgb.params( |
| 316 |
#' max_depth = 4, |
| 317 |
#' nthread = 2, |
| 318 |
#' subsample = 0.5, |
| 319 |
#' objective = "multi:softprob", |
| 320 |
#' num_class = num_class |
| 321 |
#' ) |
| 322 |
#' ) |
| 323 |
#' |
| 324 |
#' # predict for softmax returns num_class probability numbers per case: |
| 325 |
#' pred <- predict(bst, as.matrix(iris[, -5])) |
| 326 |
#' str(pred) |
| 327 |
#' # convert the probabilities to softmax labels |
| 328 |
#' pred_labels <- max.col(pred) - 1 |
| 329 |
#' # the following should result in the same error as seen in the last iteration |
| 330 |
#' sum(pred_labels != lb) / length(lb) |
| 331 |
#' |
| 332 |
#' # compare with predictions from softmax: |
| 333 |
#' set.seed(11) |
| 334 |
#' |
| 335 |
#' bst <- xgb.train( |
| 336 |
#' data = xgb.DMatrix(as.matrix(iris[, -5], nthread = 1), label = lb), |
| 337 |
#' nrounds = 10, |
| 338 |
#' params = xgb.params( |
| 339 |
#' max_depth = 4, |
| 340 |
#' nthread = 2, |
| 341 |
#' subsample = 0.5, |
| 342 |
#' objective = "multi:softmax", |
| 343 |
#' num_class = num_class |
| 344 |
#' ) |
| 345 |
#' ) |
| 346 |
#' |
| 347 |
#' pred <- predict(bst, as.matrix(iris[, -5])) |
| 348 |
#' str(pred) |
| 349 |
#' all.equal(pred, pred_labels) |
| 350 |
#' # prediction from using only 5 iterations should result |
| 351 |
#' # in the same error as seen in iteration 5: |
| 352 |
#' pred5 <- predict(bst, as.matrix(iris[, -5]), iterationrange = c(1, 5)) |
| 353 |
#' sum(pred5 != lb) / length(lb) |
| 354 |
#' |
| 355 |
#' @export |
| 356 |
predict.xgb.Booster <- function(object, newdata, missing = NA, outputmargin = FALSE, |
| 357 |
predleaf = FALSE, predcontrib = FALSE, approxcontrib = FALSE, predinteraction = FALSE, |
| 358 |
training = FALSE, iterationrange = NULL, strict_shape = FALSE, avoid_transpose = FALSE, |
| 359 |
validate_features = FALSE, base_margin = NULL, ...) { |
| 360 |
check.deprecation(deprecated_predict_params, match.call(), ..., allow_unrecognized = TRUE) |
| 361 |
if (validate_features) { |
| 362 |
newdata <- validate.features(object, newdata) |
| 363 |
} |
| 364 |
is_dmatrix <- inherits(newdata, "xgb.DMatrix") |
| 365 |
if (is_dmatrix && !is.null(base_margin)) { |
| 366 |
stop( |
| 367 |
"'base_margin' is not supported when passing 'xgb.DMatrix' as input.", |
| 368 |
" Should be passed as argument to 'xgb.DMatrix' constructor." |
| 369 |
) |
| 370 |
} |
| 371 |
if (is_dmatrix) { |
| 372 |
rnames <- NULL |
| 373 |
} else { |
| 374 |
rnames <- row.names(newdata) |
| 375 |
} |
| 376 |
|
| 377 |
use_as_df <- FALSE |
| 378 |
use_as_dense_matrix <- FALSE |
| 379 |
use_as_csr_matrix <- FALSE |
| 380 |
n_row <- NULL |
| 381 |
if (!is_dmatrix) { |
| 382 |
|
| 383 |
inplace_predict_supported <- !predcontrib && !predinteraction && !predleaf |
| 384 |
if (inplace_predict_supported) { |
| 385 |
booster_type <- xgb.booster_type(object) |
| 386 |
if (booster_type == "gblinear" || (booster_type == "dart" && training)) { |
| 387 |
inplace_predict_supported <- FALSE |
| 388 |
} |
| 389 |
} |
| 390 |
if (inplace_predict_supported) { |
| 391 |
|
| 392 |
if (is.matrix(newdata)) { |
| 393 |
use_as_dense_matrix <- TRUE |
| 394 |
} else if (is.data.frame(newdata)) { |
| 395 |
# note: since here it turns it into a non-data-frame list, |
| 396 |
# needs to keep track of the number of rows it had for later |
| 397 |
n_row <- nrow(newdata) |
| 398 |
newdata <- lapply( |
| 399 |
newdata, |
| 400 |
function(x) { |
| 401 |
if (is.factor(x)) { |
| 402 |
return(as.numeric(x) - 1) |
| 403 |
} else { |
| 404 |
return(as.numeric(x)) |
| 405 |
} |
| 406 |
} |
| 407 |
) |
| 408 |
use_as_df <- TRUE |
| 409 |
} else if (inherits(newdata, "dgRMatrix")) { |
| 410 |
use_as_csr_matrix <- TRUE |
| 411 |
csr_data <- list(newdata@p, newdata@j, newdata@x, ncol(newdata)) |
| 412 |
} else if (inherits(newdata, "dsparseVector")) { |
| 413 |
use_as_csr_matrix <- TRUE |
| 414 |
n_row <- 1L |
| 415 |
i <- newdata@i - 1L |
| 416 |
if (storage.mode(i) != "integer") { |
| 417 |
storage.mode(i) <- "integer" |
| 418 |
} |
| 419 |
csr_data <- list(c(0L, length(i)), i, newdata@x, length(newdata)) |
| 420 |
} |
| 421 |
|
| 422 |
} |
| 423 |
|
| 424 |
} # if (!is_dmatrix) |
| 425 |
|
| 426 |
if (!is_dmatrix && !use_as_dense_matrix && !use_as_csr_matrix && !use_as_df) { |
| 427 |
nthread <- xgb.nthread(object) |
| 428 |
newdata <- xgb.DMatrix( |
| 429 |
newdata, |
| 430 |
missing = missing, |
| 431 |
base_margin = base_margin, |
| 432 |
nthread = NVL(nthread, -1) |
| 433 |
) |
| 434 |
is_dmatrix <- TRUE |
| 435 |
} |
| 436 |
|
| 437 |
if (is.null(n_row)) { |
| 438 |
n_row <- nrow(newdata) |
| 439 |
} |
| 440 |
|
| 441 |
|
| 442 |
if (!is.null(iterationrange)) { |
| 443 |
if (is.character(iterationrange)) { |
| 444 |
stopifnot(iterationrange == "all") |
| 445 |
iterationrange <- c(0, 0) |
| 446 |
} else { |
| 447 |
iterationrange[1] <- iterationrange[1] - 1 # base-0 indexing |
| 448 |
} |
| 449 |
} else { |
| 450 |
## no limit is supplied, use best |
| 451 |
best_iteration <- xgb.best_iteration(object) |
| 452 |
if (is.null(best_iteration)) { |
| 453 |
iterationrange <- c(0, 0) |
| 454 |
} else { |
| 455 |
iterationrange <- c(0, as.integer(best_iteration) + 1L) |
| 456 |
} |
| 457 |
} |
| 458 |
## Handle the 0 length values. |
| 459 |
box <- function(val) { |
| 460 |
if (length(val) == 0) { |
| 461 |
cval <- vector(, 1) |
| 462 |
cval[0] <- val |
| 463 |
return(cval) |
| 464 |
} |
| 465 |
return(val) |
| 466 |
} |
| 467 |
|
| 468 |
args <- list( |
| 469 |
training = box(training), |
| 470 |
strict_shape = as.logical(strict_shape), |
| 471 |
iteration_begin = box(as.integer(iterationrange[1])), |
| 472 |
iteration_end = box(as.integer(iterationrange[2])), |
| 473 |
type = box(as.integer(0)) |
| 474 |
) |
| 475 |
|
| 476 |
set_type <- function(type) { |
| 477 |
if (args$type != 0) { |
| 478 |
stop("One type of prediction at a time.") |
| 479 |
} |
| 480 |
return(box(as.integer(type))) |
| 481 |
} |
| 482 |
if (outputmargin) { |
| 483 |
args$type <- set_type(1) |
| 484 |
} |
| 485 |
if (predcontrib) { |
| 486 |
args$type <- set_type(if (approxcontrib) 3 else 2) |
| 487 |
} |
| 488 |
if (predinteraction) { |
| 489 |
args$type <- set_type(if (approxcontrib) 5 else 4) |
| 490 |
} |
| 491 |
if (predleaf) { |
| 492 |
args$type <- set_type(6) |
| 493 |
} |
| 494 |
|
| 495 |
json_conf <- jsonlite::toJSON(args, auto_unbox = TRUE) |
| 496 |
if (is_dmatrix) { |
| 497 |
arr <- .Call( |
| 498 |
XGBoosterPredictFromDMatrix_R, xgb.get.handle(object), newdata, json_conf |
| 499 |
) |
| 500 |
} else if (use_as_dense_matrix) { |
| 501 |
arr <- .Call( |
| 502 |
XGBoosterPredictFromDense_R, xgb.get.handle(object), newdata, missing, json_conf, base_margin |
| 503 |
) |
| 504 |
} else if (use_as_csr_matrix) { |
| 505 |
arr <- .Call( |
| 506 |
XGBoosterPredictFromCSR_R, xgb.get.handle(object), csr_data, missing, json_conf, base_margin |
| 507 |
) |
| 508 |
} else if (use_as_df) { |
| 509 |
arr <- .Call( |
| 510 |
XGBoosterPredictFromColumnar_R, xgb.get.handle(object), newdata, missing, json_conf, base_margin |
| 511 |
) |
| 512 |
} |
| 513 |
|
| 514 |
## Needed regardless of whether strict shape is being used. |
| 515 |
if ((predcontrib || predinteraction) && !is.null(colnames(newdata))) { |
| 516 |
cnames <- c(colnames(newdata), "(Intercept)") |
| 517 |
dim_names <- vector(mode = "list", length = length(dim(arr))) |
| 518 |
dim_names[[1L]] <- cnames |
| 519 |
if (predinteraction) dim_names[[2L]] <- cnames |
| 520 |
.Call(XGSetArrayDimNamesInplace_R, arr, dim_names) |
| 521 |
} |
| 522 |
|
| 523 |
if (NROW(rnames)) { |
| 524 |
if (is.null(dim(arr))) { |
| 525 |
.Call(XGSetVectorNamesInplace_R, arr, rnames) |
| 526 |
} else { |
| 527 |
dim_names <- dimnames(arr) |
| 528 |
if (is.null(dim_names)) { |
| 529 |
dim_names <- vector(mode = "list", length = length(dim(arr))) |
| 530 |
} |
| 531 |
dim_names[[length(dim_names)]] <- rnames |
| 532 |
.Call(XGSetArrayDimNamesInplace_R, arr, dim_names) |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
if (!avoid_transpose && is.array(arr)) { |
| 537 |
arr <- aperm(arr) |
| 538 |
} |
| 539 |
|
| 540 |
return(arr) |
| 541 |
} |
| 542 |
|
| 543 |
validate.features <- function(bst, newdata) { |
| 544 |
if (is.character(newdata)) { |
| 545 |
# this will be encountered when passing file paths |
| 546 |
return(newdata) |
| 547 |
} |
| 548 |
if (inherits(newdata, "sparseVector")) { |
| 549 |
# in this case, newdata won't have metadata |
| 550 |
return(newdata) |
| 551 |
} |
| 552 |
if (is.vector(newdata)) { |
| 553 |
newdata <- as.matrix(newdata) |
| 554 |
} |
| 555 |
|
| 556 |
booster_names <- getinfo(bst, "feature_name") |
| 557 |
checked_names <- FALSE |
| 558 |
if (NROW(booster_names)) { |
| 559 |
|
| 560 |
try_reorder <- FALSE |
| 561 |
if (inherits(newdata, "xgb.DMatrix")) { |
| 562 |
curr_names <- getinfo(newdata, "feature_name") |
| 563 |
} else { |
| 564 |
curr_names <- colnames(newdata) |
| 565 |
try_reorder <- TRUE |
| 566 |
} |
| 567 |
|
| 568 |
if (NROW(curr_names)) { |
| 569 |
checked_names <- TRUE |
| 570 |
|
| 571 |
if (length(curr_names) != length(booster_names) || any(curr_names != booster_names)) { |
| 572 |
|
| 573 |
if (!try_reorder) { |
| 574 |
stop("Feature names in 'newdata' do not match with booster's.") |
| 575 |
} else { |
| 576 |
if (inherits(newdata, "data.table")) { |
| 577 |
newdata <- newdata[, booster_names, with = FALSE] |
| 578 |
} else { |
| 579 |
newdata <- newdata[, booster_names, drop = FALSE] |
| 580 |
} |
| 581 |
} |
| 582 |
|
| 583 |
} |
| 584 |
|
| 585 |
} # if (NROW(curr_names)) { |
| 586 |
|
| 587 |
} # if (NROW(booster_names)) { |
| 588 |
|
| 589 |
if (inherits(newdata, c("data.frame", "xgb.DMatrix"))) { |
| 590 |
|
| 591 |
booster_types <- getinfo(bst, "feature_type") |
| 592 |
if (!NROW(booster_types)) { |
| 593 |
# Note: types in the booster are optional. Other interfaces |
| 594 |
# might not even save it as booster attributes for example, |
| 595 |
# even if the model uses categorical features. |
| 596 |
return(newdata) |
| 597 |
} |
| 598 |
if (inherits(newdata, "xgb.DMatrix")) { |
| 599 |
curr_types <- getinfo(newdata, "feature_type") |
| 600 |
if (length(curr_types) != length(booster_types) || any(curr_types != booster_types)) { |
| 601 |
stop("Feature types in 'newdata' do not match with booster's.") |
| 602 |
} |
| 603 |
} |
| 604 |
if (inherits(newdata, "data.frame")) { |
| 605 |
is_factor <- sapply(newdata, is.factor) |
| 606 |
if (any(is_factor != (booster_types == "c"))) { |
| 607 |
stop( |
| 608 |
paste0( |
| 609 |
"Feature types in 'newdata' do not match with booster's for same columns (by ", |
| 610 |
ifelse(checked_names, "name", "position"), |
| 611 |
")." |
| 612 |
) |
| 613 |
) |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
} |
| 618 |
|
| 619 |
return(newdata) |
| 620 |
} |
| 621 |
|
| 622 |
|
| 623 |
#' Accessors for serializable attributes of a model |
| 624 |
#' |
| 625 |
#' These methods allow to manipulate the key-value attribute strings of an XGBoost model. |
| 626 |
#' |
| 627 |
#' @details |
| 628 |
#' The primary purpose of XGBoost model attributes is to store some meta data about the model. |
| 629 |
#' Note that they are a separate concept from the object attributes in R. |
| 630 |
#' Specifically, they refer to key-value strings that can be attached to an XGBoost model, |
| 631 |
#' stored together with the model's binary representation, and accessed later |
| 632 |
#' (from R or any other interface). |
| 633 |
#' In contrast, any R attribute assigned to an R object of `xgb.Booster` class |
| 634 |
#' would not be saved by [xgb.save()] because an XGBoost model is an external memory object |
| 635 |
#' and its serialization is handled externally. |
| 636 |
#' Also, setting an attribute that has the same name as one of XGBoost's parameters wouldn't |
| 637 |
#' change the value of that parameter for a model. |
| 638 |
#' Use [xgb.model.parameters<-()] to set or change model parameters. |
| 639 |
#' |
| 640 |
#' The `xgb.attributes<-` setter either updates the existing or adds one or several attributes, |
| 641 |
#' but it doesn't delete the other existing attributes. |
| 642 |
#' |
| 643 |
#' Important: since this modifies the booster's C object, semantics for assignment here |
| 644 |
#' will differ from R's, as any object reference to the same booster will be modified |
| 645 |
#' too, while assignment of R attributes through `attributes(model)$<attr> <- <value>` |
| 646 |
#' will follow the usual copy-on-write R semantics (see [xgb.copy.Booster()] for an |
| 647 |
#' example of these behaviors). |
| 648 |
#' |
| 649 |
#' @param object Object of class `xgb.Booster`. **Will be modified in-place** when assigning to it. |
| 650 |
#' @param name A non-empty character string specifying which attribute is to be accessed. |
| 651 |
#' @param value For `xgb.attr<-`, a value of an attribute; for `xgb.attributes<-`, |
| 652 |
#' it is a list (or an object coercible to a list) with the names of attributes to set |
| 653 |
#' and the elements corresponding to attribute values. |
| 654 |
#' Non-character values are converted to character. |
| 655 |
#' When an attribute value is not a scalar, only the first index is used. |
| 656 |
#' Use `NULL` to remove an attribute. |
| 657 |
#' @return |
| 658 |
#' - `xgb.attr()` returns either a string value of an attribute |
| 659 |
#' or `NULL` if an attribute wasn't stored in a model. |
| 660 |
#' - `xgb.attributes()` returns a list of all attributes stored in a model |
| 661 |
#' or `NULL` if a model has no stored attributes. |
| 662 |
#' |
| 663 |
#' @examples |
| 664 |
#' data(agaricus.train, package = "xgboost") |
| 665 |
#' train <- agaricus.train |
| 666 |
#' |
| 667 |
#' bst <- xgb.train( |
| 668 |
#' data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 669 |
#' nrounds = 2, |
| 670 |
#' params = xgb.params( |
| 671 |
#' max_depth = 2, |
| 672 |
#' nthread = 2, |
| 673 |
#' objective = "binary:logistic" |
| 674 |
#' ) |
| 675 |
#' ) |
| 676 |
#' |
| 677 |
#' xgb.attr(bst, "my_attribute") <- "my attribute value" |
| 678 |
#' print(xgb.attr(bst, "my_attribute")) |
| 679 |
#' xgb.attributes(bst) <- list(a = 123, b = "abc") |
| 680 |
#' |
| 681 |
#' fname <- file.path(tempdir(), "xgb.ubj") |
| 682 |
#' xgb.save(bst, fname) |
| 683 |
#' bst1 <- xgb.load(fname) |
| 684 |
#' print(xgb.attr(bst1, "my_attribute")) |
| 685 |
#' print(xgb.attributes(bst1)) |
| 686 |
#' |
| 687 |
#' # deletion: |
| 688 |
#' xgb.attr(bst1, "my_attribute") <- NULL |
| 689 |
#' print(xgb.attributes(bst1)) |
| 690 |
#' xgb.attributes(bst1) <- list(a = NULL, b = NULL) |
| 691 |
#' print(xgb.attributes(bst1)) |
| 692 |
#' |
| 693 |
#' @rdname xgb.attr |
| 694 |
#' @export |
| 695 |
xgb.attr <- function(object, name) { |
| 696 |
if (is.null(name) || nchar(as.character(name[1])) == 0) stop("invalid attribute name") |
| 697 |
handle <- xgb.get.handle(object) |
| 698 |
out <- .Call(XGBoosterGetAttr_R, handle, as.character(name[1])) |
| 699 |
if (!NROW(out) || !nchar(out)) { |
| 700 |
return(NULL) |
| 701 |
} |
| 702 |
if (!is.null(out)) { |
| 703 |
if (name %in% c("best_iteration", "best_score")) { |
| 704 |
out <- as.numeric(out) |
| 705 |
} |
| 706 |
} |
| 707 |
return(out) |
| 708 |
} |
| 709 |
|
| 710 |
#' @rdname xgb.attr |
| 711 |
#' @export |
| 712 |
`xgb.attr<-` <- function(object, name, value) { |
| 713 |
name <- as.character(name[1]) |
| 714 |
if (!NROW(name) || !nchar(name)) stop("invalid attribute name") |
| 715 |
handle <- xgb.get.handle(object) |
| 716 |
|
| 717 |
if (!is.null(value)) { |
| 718 |
# Coerce the elements to be scalar strings. |
| 719 |
# Q: should we warn user about non-scalar elements? |
| 720 |
if (is.numeric(value[1])) { |
| 721 |
value <- format(value[1], digits = 17) |
| 722 |
} else { |
| 723 |
value <- as.character(value[1]) |
| 724 |
} |
| 725 |
} |
| 726 |
.Call(XGBoosterSetAttr_R, handle, name, value) |
| 727 |
return(object) |
| 728 |
} |
| 729 |
|
| 730 |
#' @rdname xgb.attr |
| 731 |
#' @export |
| 732 |
xgb.attributes <- function(object) { |
| 733 |
handle <- xgb.get.handle(object) |
| 734 |
attr_names <- .Call(XGBoosterGetAttrNames_R, handle) |
| 735 |
if (!NROW(attr_names)) return(list()) |
| 736 |
out <- lapply(attr_names, function(name) xgb.attr(object, name)) |
| 737 |
names(out) <- attr_names |
| 738 |
return(out) |
| 739 |
} |
| 740 |
|
| 741 |
#' @rdname xgb.attr |
| 742 |
#' @export |
| 743 |
`xgb.attributes<-` <- function(object, value) { |
| 744 |
a <- as.list(value) |
| 745 |
if (is.null(names(a)) || any(nchar(names(a)) == 0)) { |
| 746 |
stop("attribute names cannot be empty strings") |
| 747 |
} |
| 748 |
for (i in seq_along(a)) { |
| 749 |
xgb.attr(object, names(a[i])) <- a[[i]] |
| 750 |
} |
| 751 |
return(object) |
| 752 |
} |
| 753 |
|
| 754 |
#' Accessors for model parameters as JSON string |
| 755 |
#' |
| 756 |
#' @details |
| 757 |
#' Note that assignment is performed in-place on the booster C object, which unlike assignment |
| 758 |
#' of R attributes, doesn't follow typical copy-on-write semantics for assignment - i.e. all references |
| 759 |
#' to the same booster will also get updated. |
| 760 |
#' |
| 761 |
#' See [xgb.copy.Booster()] for an example of this behavior. |
| 762 |
#' |
| 763 |
#' @param object Object of class `xgb.Booster`.**Will be modified in-place** when assigning to it. |
| 764 |
#' @param value A list. |
| 765 |
#' @return Parameters as a list. |
| 766 |
#' @examples |
| 767 |
#' data(agaricus.train, package = "xgboost") |
| 768 |
#' |
| 769 |
#' ## Keep the number of threads to 1 for examples |
| 770 |
#' nthread <- 1 |
| 771 |
#' data.table::setDTthreads(nthread) |
| 772 |
#' train <- agaricus.train |
| 773 |
#' |
| 774 |
#' bst <- xgb.train( |
| 775 |
#' data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 776 |
#' nrounds = 2, |
| 777 |
#' params = xgb.params( |
| 778 |
#' max_depth = 2, |
| 779 |
#' nthread = nthread, |
| 780 |
#' objective = "binary:logistic" |
| 781 |
#' ) |
| 782 |
#' ) |
| 783 |
#' |
| 784 |
#' config <- xgb.config(bst) |
| 785 |
#' |
| 786 |
#' @rdname xgb.config |
| 787 |
#' @export |
| 788 |
xgb.config <- function(object) { |
| 789 |
handle <- xgb.get.handle(object) |
| 790 |
return(jsonlite::fromJSON(.Call(XGBoosterSaveJsonConfig_R, handle))) |
| 791 |
} |
| 792 |
|
| 793 |
#' @rdname xgb.config |
| 794 |
#' @export |
| 795 |
`xgb.config<-` <- function(object, value) { |
| 796 |
handle <- xgb.get.handle(object) |
| 797 |
.Call( |
| 798 |
XGBoosterLoadJsonConfig_R, |
| 799 |
handle, |
| 800 |
jsonlite::toJSON(value, auto_unbox = TRUE, null = "null") |
| 801 |
) |
| 802 |
return(object) |
| 803 |
} |
| 804 |
|
| 805 |
#' Accessors for model parameters |
| 806 |
#' |
| 807 |
#' Only the setter for XGBoost parameters is currently implemented. |
| 808 |
#' |
| 809 |
#' @details |
| 810 |
#' Just like [xgb.attr()], this function will make in-place modifications |
| 811 |
#' on the booster object which do not follow typical R assignment semantics - that is, |
| 812 |
#' all references to the same booster will also be updated, unlike assingment of R |
| 813 |
#' attributes which follow copy-on-write semantics. |
| 814 |
#' |
| 815 |
#' See [xgb.copy.Booster()] for an example of this behavior. |
| 816 |
#' |
| 817 |
#' Be aware that setting parameters of a fitted booster related to training continuation / updates |
| 818 |
#' will reset its number of rounds indicator to zero. |
| 819 |
#' @param object Object of class `xgb.Booster`. **Will be modified in-place**. |
| 820 |
#' @param value A list (or an object coercible to a list) with the names of parameters to set |
| 821 |
#' and the elements corresponding to parameter values. |
| 822 |
#' @return The same booster `object`, which gets modified in-place. |
| 823 |
#' @examples |
| 824 |
#' data(agaricus.train, package = "xgboost") |
| 825 |
#' |
| 826 |
#' train <- agaricus.train |
| 827 |
#' |
| 828 |
#' bst <- xgb.train( |
| 829 |
#' data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 830 |
#' nrounds = 2, |
| 831 |
#' params = xgb.params( |
| 832 |
#' max_depth = 2, |
| 833 |
#' learning_rate = 1, |
| 834 |
#' nthread = 2, |
| 835 |
#' objective = "binary:logistic" |
| 836 |
#' ) |
| 837 |
#' ) |
| 838 |
#' |
| 839 |
#' xgb.model.parameters(bst) <- list(learning_rate = 0.1) |
| 840 |
#' |
| 841 |
#' @rdname xgb.model.parameters |
| 842 |
#' @export |
| 843 |
`xgb.model.parameters<-` <- function(object, value) { |
| 844 |
if (length(value) == 0) return(object) |
| 845 |
p <- as.list(value) |
| 846 |
if (is.null(names(p)) || any(nchar(names(p)) == 0)) { |
| 847 |
stop("parameter names cannot be empty strings") |
| 848 |
} |
| 849 |
names(p) <- gsub(".", "_", names(p), fixed = TRUE) |
| 850 |
p <- lapply(p, function(x) { |
| 851 |
if (is.vector(x) && length(x) == 1) { |
| 852 |
return(as.character(x)[1]) |
| 853 |
} else { |
| 854 |
return(jsonlite::toJSON(x, auto_unbox = TRUE)) |
| 855 |
} |
| 856 |
}) |
| 857 |
handle <- xgb.get.handle(object) |
| 858 |
for (i in seq_along(p)) { |
| 859 |
.Call(XGBoosterSetParam_R, handle, names(p[i]), p[[i]]) |
| 860 |
} |
| 861 |
return(object) |
| 862 |
} |
| 863 |
|
| 864 |
#' @rdname getinfo |
| 865 |
#' @export |
| 866 |
getinfo.xgb.Booster <- function(object, name) { |
| 867 |
name <- as.character(head(name, 1L)) |
| 868 |
allowed_fields <- c("feature_name", "feature_type") |
| 869 |
if (!(name %in% allowed_fields)) { |
| 870 |
stop("getinfo: name must be one of the following: ", paste(allowed_fields, collapse = ", ")) |
| 871 |
} |
| 872 |
handle <- xgb.get.handle(object) |
| 873 |
out <- .Call( |
| 874 |
XGBoosterGetStrFeatureInfo_R, |
| 875 |
handle, |
| 876 |
name |
| 877 |
) |
| 878 |
if (!NROW(out)) { |
| 879 |
return(NULL) |
| 880 |
} |
| 881 |
return(out) |
| 882 |
} |
| 883 |
|
| 884 |
#' @rdname getinfo |
| 885 |
#' @export |
| 886 |
setinfo.xgb.Booster <- function(object, name, info) { |
| 887 |
name <- as.character(head(name, 1L)) |
| 888 |
allowed_fields <- c("feature_name", "feature_type") |
| 889 |
if (!(name %in% allowed_fields)) { |
| 890 |
stop("setinfo: unknown info name ", name) |
| 891 |
} |
| 892 |
info <- as.character(info) |
| 893 |
handle <- xgb.get.handle(object) |
| 894 |
.Call( |
| 895 |
XGBoosterSetStrFeatureInfo_R, |
| 896 |
handle, |
| 897 |
name, |
| 898 |
info |
| 899 |
) |
| 900 |
return(TRUE) |
| 901 |
} |
| 902 |
|
| 903 |
#' Get number of boosting in a fitted booster |
| 904 |
#' |
| 905 |
#' @param model,x A fitted `xgb.Booster` model. |
| 906 |
#' @return The number of rounds saved in the model as an integer. |
| 907 |
#' @details Note that setting booster parameters related to training |
| 908 |
#' continuation / updates through [xgb.model.parameters<-()] will reset the |
| 909 |
#' number of rounds to zero. |
| 910 |
#' @export |
| 911 |
#' @rdname xgb.get.num.boosted.rounds |
| 912 |
xgb.get.num.boosted.rounds <- function(model) { |
| 913 |
return(.Call(XGBoosterBoostedRounds_R, xgb.get.handle(model))) |
| 914 |
} |
| 915 |
|
| 916 |
#' @rdname xgb.get.num.boosted.rounds |
| 917 |
#' @export |
| 918 |
length.xgb.Booster <- function(x) { |
| 919 |
return(xgb.get.num.boosted.rounds(x)) |
| 920 |
} |
| 921 |
|
| 922 |
#' Slice Booster by Rounds |
| 923 |
#' |
| 924 |
#' Creates a new booster including only a selected range of rounds / iterations |
| 925 |
#' from an existing booster, as given by the sequence `seq(start, end, step)`. |
| 926 |
#' |
| 927 |
#' @details |
| 928 |
#' Note that any R attributes that the booster might have, will not be copied into |
| 929 |
#' the resulting object. |
| 930 |
#' |
| 931 |
#' @param model,x A fitted `xgb.Booster` object, which is to be sliced by taking only a subset |
| 932 |
#' of its rounds / iterations. |
| 933 |
#' @param start Start of the slice (base-1 and inclusive, like R's [seq()]). |
| 934 |
#' @param end End of the slice (base-1 and inclusive, like R's [seq()]). |
| 935 |
#' Passing a value of zero here is equivalent to passing the full number of rounds in the |
| 936 |
#' booster object. |
| 937 |
#' @param step Step size of the slice. Passing '1' will take every round in the sequence defined by |
| 938 |
#' `(start, end)`, while passing '2' will take every second value, and so on. |
| 939 |
#' @return A sliced booster object containing only the requested rounds. |
| 940 |
#' @examples |
| 941 |
#' data(mtcars) |
| 942 |
#' |
| 943 |
#' y <- mtcars$mpg |
| 944 |
#' x <- as.matrix(mtcars[, -1]) |
| 945 |
#' |
| 946 |
#' dm <- xgb.DMatrix(x, label = y, nthread = 1) |
| 947 |
#' model <- xgb.train(data = dm, params = xgb.params(nthread = 1), nrounds = 5) |
| 948 |
#' model_slice <- xgb.slice.Booster(model, 1, 3) |
| 949 |
#' # Prediction for first three rounds |
| 950 |
#' predict(model, x, predleaf = TRUE)[, 1:3] |
| 951 |
#' |
| 952 |
#' # The new model has only those rounds, so |
| 953 |
#' # a full prediction from it is equivalent |
| 954 |
#' predict(model_slice, x, predleaf = TRUE) |
| 955 |
#' @export |
| 956 |
#' @rdname xgb.slice.Booster |
| 957 |
xgb.slice.Booster <- function(model, start, end = xgb.get.num.boosted.rounds(model), step = 1L) { |
| 958 |
# This makes the slice mimic the behavior of R's 'seq', |
| 959 |
# which truncates on the end of the slice when the step |
| 960 |
# doesn't reach it. |
| 961 |
if (end > start && step > 1) { |
| 962 |
d <- (end - start + 1) / step |
| 963 |
if (d != floor(d)) { |
| 964 |
end <- start + step * ceiling(d) - 1 |
| 965 |
} |
| 966 |
} |
| 967 |
return( |
| 968 |
.Call( |
| 969 |
XGBoosterSlice_R, |
| 970 |
xgb.get.handle(model), |
| 971 |
start - 1, |
| 972 |
end, |
| 973 |
step |
| 974 |
) |
| 975 |
) |
| 976 |
} |
| 977 |
|
| 978 |
#' @export |
| 979 |
#' @rdname xgb.slice.Booster |
| 980 |
#' @param i The indices - must be an increasing sequence as generated by e.g. `seq(...)`. |
| 981 |
`[.xgb.Booster` <- function(x, i) { |
| 982 |
if (missing(i)) { |
| 983 |
return(xgb.slice.Booster(x, 1, 0)) |
| 984 |
} |
| 985 |
if (length(i) == 1) { |
| 986 |
return(xgb.slice.Booster(x, i, i)) |
| 987 |
} |
| 988 |
steps <- diff(i) |
| 989 |
if (any(steps < 0)) { |
| 990 |
stop("Can only slice booster with ascending sequences.") |
| 991 |
} |
| 992 |
if (length(unique(steps)) > 1) { |
| 993 |
stop("Can only slice booster with fixed-step sequences.") |
| 994 |
} |
| 995 |
return(xgb.slice.Booster(x, i[1L], i[length(i)], steps[1L])) |
| 996 |
} |
| 997 |
|
| 998 |
#' Get Features Names from Booster |
| 999 |
#' |
| 1000 |
#' @description |
| 1001 |
#' Returns the feature / variable / column names from a fitted |
| 1002 |
#' booster object, which are set automatically during the call to [xgb.train()] |
| 1003 |
#' from the DMatrix names, or which can be set manually through [setinfo()]. |
| 1004 |
#' |
| 1005 |
#' If the object doesn't have feature names, will return `NULL`. |
| 1006 |
#' |
| 1007 |
#' It is equivalent to calling `getinfo(object, "feature_name")`. |
| 1008 |
#' @param object An `xgb.Booster` object. |
| 1009 |
#' @param ... Not used. |
| 1010 |
#' @export |
| 1011 |
variable.names.xgb.Booster <- function(object, ...) { |
| 1012 |
return(getinfo(object, "feature_name")) |
| 1013 |
} |
| 1014 |
|
| 1015 |
xgb.nthread <- function(bst) { |
| 1016 |
config <- xgb.config(bst) |
| 1017 |
out <- strtoi(config$learner$generic_param$nthread) |
| 1018 |
return(out) |
| 1019 |
} |
| 1020 |
|
| 1021 |
xgb.booster_type <- function(bst) { |
| 1022 |
config <- xgb.config(bst) |
| 1023 |
out <- config$learner$learner_train_param$booster |
| 1024 |
return(out) |
| 1025 |
} |
| 1026 |
|
| 1027 |
xgb.num_class <- function(bst) { |
| 1028 |
config <- xgb.config(bst) |
| 1029 |
out <- strtoi(config$learner$learner_model_param$num_class) |
| 1030 |
return(out) |
| 1031 |
} |
| 1032 |
|
| 1033 |
xgb.feature_names <- function(bst) { |
| 1034 |
return(getinfo(bst, "feature_name")) |
| 1035 |
} |
| 1036 |
|
| 1037 |
xgb.feature_types <- function(bst) { |
| 1038 |
return(getinfo(bst, "feature_type")) |
| 1039 |
} |
| 1040 |
|
| 1041 |
xgb.num_feature <- function(bst) { |
| 1042 |
handle <- xgb.get.handle(bst) |
| 1043 |
return(.Call(XGBoosterGetNumFeature_R, handle)) |
| 1044 |
} |
| 1045 |
|
| 1046 |
xgb.best_iteration <- function(bst) { |
| 1047 |
out <- xgb.attr(bst, "best_iteration") |
| 1048 |
if (!NROW(out) || !nchar(out)) { |
| 1049 |
out <- NULL |
| 1050 |
} |
| 1051 |
return(out) |
| 1052 |
} |
| 1053 |
|
| 1054 |
xgb.has_categ_features <- function(bst) { |
| 1055 |
return("c" %in% xgb.feature_types(bst)) |
| 1056 |
} |
| 1057 |
|
| 1058 |
#' Extract coefficients from linear booster |
| 1059 |
#' |
| 1060 |
#' @description |
| 1061 |
#' Extracts the coefficients from a 'gblinear' booster object, |
| 1062 |
#' as produced by [xgb.train()] when using parameter `booster="gblinear"`. |
| 1063 |
#' |
| 1064 |
#' Note: this function will error out if passing a booster model |
| 1065 |
#' which is not of "gblinear" type. |
| 1066 |
#' |
| 1067 |
#' @param object A fitted booster of 'gblinear' type. |
| 1068 |
#' @param ... Not used. |
| 1069 |
#' @return The extracted coefficients: |
| 1070 |
#' - If there is only one coefficient per column in the data, will be returned as a |
| 1071 |
#' vector, potentially containing the feature names if available, with the intercept |
| 1072 |
#' as first column. |
| 1073 |
#' - If there is more than one coefficient per column in the data (e.g. when using |
| 1074 |
#' `objective="multi:softmax"`), will be returned as a matrix with dimensions equal |
| 1075 |
#' to `[num_features, num_cols]`, with the intercepts as first row. Note that the column |
| 1076 |
#' (classes in multi-class classification) dimension will not be named. |
| 1077 |
#' |
| 1078 |
#' The intercept returned here will include the 'base_score' parameter (unlike the 'bias' |
| 1079 |
#' or the last coefficient in the model dump, which doesn't have 'base_score' added to it), |
| 1080 |
#' hence one should get the same values from calling `predict(..., outputmargin = TRUE)` and |
| 1081 |
#' from performing a matrix multiplication with `model.matrix(~., ...)`. |
| 1082 |
#' |
| 1083 |
#' Be aware that the coefficients are obtained by first converting them to strings and |
| 1084 |
#' back, so there will always be some very small lose of precision compared to the actual |
| 1085 |
#' coefficients as used by [predict.xgb.Booster]. |
| 1086 |
#' @examples |
| 1087 |
#' library(xgboost) |
| 1088 |
#' |
| 1089 |
#' data(mtcars) |
| 1090 |
#' |
| 1091 |
#' y <- mtcars[, 1] |
| 1092 |
#' x <- as.matrix(mtcars[, -1]) |
| 1093 |
#' |
| 1094 |
#' dm <- xgb.DMatrix(data = x, label = y, nthread = 1) |
| 1095 |
#' params <- xgb.params(booster = "gblinear", nthread = 1) |
| 1096 |
#' model <- xgb.train(data = dm, params = params, nrounds = 2) |
| 1097 |
#' coef(model) |
| 1098 |
#' @export |
| 1099 |
coef.xgb.Booster <- function(object, ...) { |
| 1100 |
return(.internal.coef.xgb.Booster(object, add_names = TRUE)) |
| 1101 |
} |
| 1102 |
|
| 1103 |
.internal.coef.xgb.Booster <- function(object, add_names = TRUE) { |
| 1104 |
booster_type <- xgb.booster_type(object) |
| 1105 |
if (booster_type != "gblinear") { |
| 1106 |
stop("Coefficients are not defined for Booster type ", booster_type) |
| 1107 |
} |
| 1108 |
model_json <- jsonlite::fromJSON( |
| 1109 |
rawToChar(xgb.save.raw(object, raw_format = "json")) |
| 1110 |
) |
| 1111 |
num_feature <- as.numeric(model_json$learner$learner_model_param$num_feature) |
| 1112 |
|
| 1113 |
weights <- model_json$learner$gradient_booster$model$weights |
| 1114 |
n_cols <- length(weights) / (num_feature + 1) |
| 1115 |
if (n_cols != floor(n_cols) || n_cols < 1) { |
| 1116 |
stop("Internal error: could not determine shape of coefficients.") |
| 1117 |
} |
| 1118 |
sep <- num_feature * n_cols |
| 1119 |
coefs <- weights[seq(1, sep)] |
| 1120 |
intercepts <- weights[seq(sep + 1, length(weights))] |
| 1121 |
base_score <- jsonlite::fromJSON( |
| 1122 |
model_json$learner$learner_model_param$base_score |
| 1123 |
) |
| 1124 |
intercepts <- intercepts + as.numeric(base_score) |
| 1125 |
|
| 1126 |
if (add_names) { |
| 1127 |
feature_names <- xgb.feature_names(object) |
| 1128 |
if (!NROW(feature_names)) { |
| 1129 |
# This mimics the default naming in R which names columns as "V1..N" |
| 1130 |
# when names are needed but not available |
| 1131 |
feature_names <- paste0("V", seq(1L, num_feature)) |
| 1132 |
} |
| 1133 |
feature_names <- c("(Intercept)", feature_names) |
| 1134 |
} |
| 1135 |
if (n_cols == 1L) { |
| 1136 |
out <- c(intercepts, coefs) |
| 1137 |
if (add_names) { |
| 1138 |
.Call(XGSetVectorNamesInplace_R, out, feature_names) |
| 1139 |
} |
| 1140 |
} else { |
| 1141 |
coefs <- matrix(coefs, nrow = num_feature, byrow = TRUE) |
| 1142 |
dim(intercepts) <- c(1L, n_cols) |
| 1143 |
out <- rbind(intercepts, coefs) |
| 1144 |
out_names <- vector(mode = "list", length = 2) |
| 1145 |
if (add_names) { |
| 1146 |
out_names[[1L]] <- feature_names |
| 1147 |
} |
| 1148 |
if (inherits(object, "xgboost")) { |
| 1149 |
metadata <- attributes(object)$metadata |
| 1150 |
if (NROW(metadata$y_levels)) { |
| 1151 |
out_names[[2L]] <- metadata$y_levels |
| 1152 |
} else if (NROW(metadata$y_names)) { |
| 1153 |
out_names[[2L]] <- metadata$y_names |
| 1154 |
} |
| 1155 |
} |
| 1156 |
.Call(XGSetArrayDimNamesInplace_R, out, out_names) |
| 1157 |
} |
| 1158 |
return(out) |
| 1159 |
} |
| 1160 |
|
| 1161 |
#' Deep-copies a Booster Object |
| 1162 |
#' |
| 1163 |
#' Creates a deep copy of an 'xgb.Booster' object, such that the |
| 1164 |
#' C object pointer contained will be a different object, and hence functions |
| 1165 |
#' like [xgb.attr()] will not affect the object from which it was copied. |
| 1166 |
#' |
| 1167 |
#' @param model An 'xgb.Booster' object. |
| 1168 |
#' @return A deep copy of `model` - it will be identical in every way, but C-level |
| 1169 |
#' functions called on that copy will not affect the `model` variable. |
| 1170 |
#' @examples |
| 1171 |
#' library(xgboost) |
| 1172 |
#' |
| 1173 |
#' data(mtcars) |
| 1174 |
#' |
| 1175 |
#' y <- mtcars$mpg |
| 1176 |
#' x <- mtcars[, -1] |
| 1177 |
#' |
| 1178 |
#' dm <- xgb.DMatrix(x, label = y, nthread = 1) |
| 1179 |
#' |
| 1180 |
#' model <- xgb.train( |
| 1181 |
#' data = dm, |
| 1182 |
#' params = xgb.params(nthread = 1), |
| 1183 |
#' nrounds = 3 |
| 1184 |
#' ) |
| 1185 |
#' |
| 1186 |
#' # Set an arbitrary attribute kept at the C level |
| 1187 |
#' xgb.attr(model, "my_attr") <- 100 |
| 1188 |
#' print(xgb.attr(model, "my_attr")) |
| 1189 |
#' |
| 1190 |
#' # Just assigning to a new variable will not create |
| 1191 |
#' # a deep copy - C object pointer is shared, and in-place |
| 1192 |
#' # modifications will affect both objects |
| 1193 |
#' model_shallow_copy <- model |
| 1194 |
#' xgb.attr(model_shallow_copy, "my_attr") <- 333 |
| 1195 |
#' # 'model' was also affected by this change: |
| 1196 |
#' print(xgb.attr(model, "my_attr")) |
| 1197 |
#' |
| 1198 |
#' model_deep_copy <- xgb.copy.Booster(model) |
| 1199 |
#' xgb.attr(model_deep_copy, "my_attr") <- 444 |
| 1200 |
#' # 'model' was NOT affected by this change |
| 1201 |
#' # (keeps previous value that was assigned before) |
| 1202 |
#' print(xgb.attr(model, "my_attr")) |
| 1203 |
#' |
| 1204 |
#' # Verify that the new object was actually modified |
| 1205 |
#' print(xgb.attr(model_deep_copy, "my_attr")) |
| 1206 |
#' @export |
| 1207 |
xgb.copy.Booster <- function(model) { |
| 1208 |
if (!inherits(model, "xgb.Booster")) { |
| 1209 |
stop("'model' must be an 'xgb.Booster' object.") |
| 1210 |
} |
| 1211 |
return(.Call(XGDuplicate_R, model)) |
| 1212 |
} |
| 1213 |
|
| 1214 |
xgb.reset.Booster <- function(model) { |
| 1215 |
if (!inherits(model, "xgb.Booster")) { |
| 1216 |
stop("'model' must be an 'xgb.Booster' object.") |
| 1217 |
} |
| 1218 |
.Call(XGBoosterReset_R, xgb.get.handle(model)) |
| 1219 |
return(model) |
| 1220 |
} |
| 1221 |
|
| 1222 |
#' Check if two boosters share the same C object |
| 1223 |
#' |
| 1224 |
#' Checks whether two booster objects refer to the same underlying C object. |
| 1225 |
#' |
| 1226 |
#' @details |
| 1227 |
#' As booster objects (as returned by e.g. [xgb.train()]) contain an R 'externalptr' |
| 1228 |
#' object, they don't follow typical copy-on-write semantics of other R objects - that is, if |
| 1229 |
#' one assigns a booster to a different variable and modifies that new variable through in-place |
| 1230 |
#' methods like [xgb.attr<-()], the modification will be applied to both the old and the new |
| 1231 |
#' variable, unlike typical R assignments which would only modify the latter. |
| 1232 |
#' |
| 1233 |
#' This function allows checking whether two booster objects share the same 'externalptr', |
| 1234 |
#' regardless of the R attributes that they might have. |
| 1235 |
#' |
| 1236 |
#' In order to duplicate a booster in such a way that the copy wouldn't share the same |
| 1237 |
#' 'externalptr', one can use function [xgb.copy.Booster()]. |
| 1238 |
#' @param obj1 Booster model to compare with `obj2`. |
| 1239 |
#' @param obj2 Booster model to compare with `obj1`. |
| 1240 |
#' @return Either `TRUE` or `FALSE` according to whether the two boosters share the |
| 1241 |
#' underlying C object. |
| 1242 |
#' @seealso [xgb.copy.Booster()] |
| 1243 |
#' @examples |
| 1244 |
#' library(xgboost) |
| 1245 |
#' |
| 1246 |
#' data(mtcars) |
| 1247 |
#' |
| 1248 |
#' y <- mtcars$mpg |
| 1249 |
#' x <- as.matrix(mtcars[, -1]) |
| 1250 |
#' |
| 1251 |
#' model <- xgb.train( |
| 1252 |
#' params = xgb.params(nthread = 1), |
| 1253 |
#' data = xgb.DMatrix(x, label = y, nthread = 1), |
| 1254 |
#' nrounds = 3 |
| 1255 |
#' ) |
| 1256 |
#' |
| 1257 |
#' model_shallow_copy <- model |
| 1258 |
#' xgb.is.same.Booster(model, model_shallow_copy) # same C object |
| 1259 |
#' |
| 1260 |
#' model_deep_copy <- xgb.copy.Booster(model) |
| 1261 |
#' xgb.is.same.Booster(model, model_deep_copy) # different C objects |
| 1262 |
#' |
| 1263 |
#' # In-place assignments modify all references, |
| 1264 |
#' # but not full/deep copies of the booster |
| 1265 |
#' xgb.attr(model_shallow_copy, "my_attr") <- 111 |
| 1266 |
#' xgb.attr(model, "my_attr") # gets modified |
| 1267 |
#' xgb.attr(model_deep_copy, "my_attr") # doesn't get modified |
| 1268 |
#' @export |
| 1269 |
xgb.is.same.Booster <- function(obj1, obj2) { |
| 1270 |
if (!inherits(obj1, "xgb.Booster") || !inherits(obj2, "xgb.Booster")) { |
| 1271 |
stop("'xgb.is.same.Booster' is only applicable to 'xgb.Booster' objects.") |
| 1272 |
} |
| 1273 |
return( |
| 1274 |
.Call( |
| 1275 |
XGPointerEqComparison_R, |
| 1276 |
xgb.get.handle(obj1), |
| 1277 |
xgb.get.handle(obj2) |
| 1278 |
) |
| 1279 |
) |
| 1280 |
} |
| 1281 |
|
| 1282 |
#' @title Print xgb.Booster |
| 1283 |
#' @description Print information about `xgb.Booster`. |
| 1284 |
#' @param x An `xgb.Booster` object. |
| 1285 |
#' @param ... Not used. |
| 1286 |
#' @return The same `x` object, returned invisibly |
| 1287 |
#' @examples |
| 1288 |
#' data(agaricus.train, package = "xgboost") |
| 1289 |
#' train <- agaricus.train |
| 1290 |
#' |
| 1291 |
#' bst <- xgb.train( |
| 1292 |
#' data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 1293 |
#' nrounds = 2, |
| 1294 |
#' params = xgb.params( |
| 1295 |
#' max_depth = 2, |
| 1296 |
#' nthread = 2, |
| 1297 |
#' objective = "binary:logistic" |
| 1298 |
#' ) |
| 1299 |
#' ) |
| 1300 |
#' |
| 1301 |
#' attr(bst, "myattr") <- "memo" |
| 1302 |
#' |
| 1303 |
#' print(bst) |
| 1304 |
#' @method print xgb.Booster |
| 1305 |
#' @export |
| 1306 |
print.xgb.Booster <- function(x, ...) { |
| 1307 |
# this lets it error out when the object comes from an earlier R XGBoost version |
| 1308 |
handle <- xgb.get.handle(x) |
| 1309 |
cat('##### xgb.Booster\n') |
| 1310 |
|
| 1311 |
R_attrs <- attributes(x) |
| 1312 |
if (!is.null(R_attrs$call)) { |
| 1313 |
cat('call:\n ') |
| 1314 |
print(R_attrs$call) |
| 1315 |
} |
| 1316 |
|
| 1317 |
cat('# of features:', xgb.num_feature(x), '\n') |
| 1318 |
cat('# of rounds: ', xgb.get.num.boosted.rounds(x), '\n') |
| 1319 |
|
| 1320 |
attr_names <- .Call(XGBoosterGetAttrNames_R, handle) |
| 1321 |
if (NROW(attr_names)) { |
| 1322 |
cat('xgb.attributes:\n') |
| 1323 |
cat(" ", paste(attr_names, collapse = ", "), "\n") |
| 1324 |
} |
| 1325 |
|
| 1326 |
additional_attr <- setdiff(names(R_attrs), .reserved_cb_names) |
| 1327 |
if (NROW(additional_attr)) { |
| 1328 |
cat("callbacks:\n ", paste(additional_attr, collapse = ", "), "\n") |
| 1329 |
} |
| 1330 |
|
| 1331 |
if (!is.null(R_attrs$evaluation_log)) { |
| 1332 |
cat('evaluation_log:\n') |
| 1333 |
print(R_attrs$evaluation_log, row.names = FALSE, topn = 2) |
| 1334 |
} |
| 1335 |
|
| 1336 |
return(invisible(x)) |
| 1337 |
} |