| 1 |
% Generated by roxygen2: do not edit by hand |
| 2 |
% Please edit documentation in R/xgb.Booster.R |
| 3 |
\name{predict.xgb.Booster} |
| 4 |
\alias{predict.xgb.Booster} |
| 5 |
\title{Predict method for XGBoost model} |
| 6 |
\usage{ |
| 7 |
\method{predict}{xgb.Booster}( |
| 8 |
object, |
| 9 |
newdata, |
| 10 |
missing = NA, |
| 11 |
outputmargin = FALSE, |
| 12 |
predleaf = FALSE, |
| 13 |
predcontrib = FALSE, |
| 14 |
approxcontrib = FALSE, |
| 15 |
predinteraction = FALSE, |
| 16 |
training = FALSE, |
| 17 |
iterationrange = NULL, |
| 18 |
strict_shape = FALSE, |
| 19 |
avoid_transpose = FALSE, |
| 20 |
validate_features = FALSE, |
| 21 |
base_margin = NULL, |
| 22 |
... |
| 23 |
) |
| 24 |
} |
| 25 |
\arguments{ |
| 26 |
\item{object}{Object of class \code{xgb.Booster}.} |
| 27 |
|
| 28 |
\item{newdata}{Takes \code{data.frame}, \code{matrix}, \code{dgCMatrix}, \code{dgRMatrix}, \code{dsparseVector}, |
| 29 |
local data file, or \code{xgb.DMatrix}. |
| 30 |
|
| 31 |
For single-row predictions on sparse data, it is recommended to use CSR format. If passing |
| 32 |
a sparse vector, it will take it as a row vector. |
| 33 |
|
| 34 |
Note that, for repeated predictions on the same data, one might want to create a DMatrix to |
| 35 |
pass here instead of passing R types like matrices or data frames, as predictions will be |
| 36 |
faster on DMatrix. |
| 37 |
|
| 38 |
If \code{newdata} is a \code{data.frame}, be aware that: |
| 39 |
\itemize{ |
| 40 |
\item Columns will be converted to numeric if they aren't already, which could potentially make |
| 41 |
the operation slower than in an equivalent \code{matrix} object. |
| 42 |
\item The order of the columns must match with that of the data from which the model was fitted |
| 43 |
(i.e. columns will not be referenced by their names, just by their order in the data), |
| 44 |
unless passing \code{validate_features = TRUE} (which is not the default). |
| 45 |
\item If the model was fitted to data with categorical columns, these columns must be of |
| 46 |
\code{factor} type here, and must use the same encoding (i.e. have the same levels). |
| 47 |
\item If \code{newdata} contains any \code{factor} columns, they will be converted to base-0 |
| 48 |
encoding (same as during DMatrix creation) - hence, one should not pass a \code{factor} |
| 49 |
under a column which during training had a different type. |
| 50 |
\item Any columns with type other than \code{factor} will be interpreted as numeric. |
| 51 |
}} |
| 52 |
|
| 53 |
\item{missing}{Float value that represents missing values in data |
| 54 |
(e.g., 0 or some other extreme value). |
| 55 |
|
| 56 |
This parameter is not used when \code{newdata} is an \code{xgb.DMatrix} - in such cases, |
| 57 |
should pass this as an argument to the DMatrix constructor instead.} |
| 58 |
|
| 59 |
\item{outputmargin}{Whether the prediction should be returned in the form of |
| 60 |
original untransformed sum of predictions from boosting iterations' results. |
| 61 |
E.g., setting \code{outputmargin = TRUE} for logistic regression would return log-odds |
| 62 |
instead of probabilities.} |
| 63 |
|
| 64 |
\item{predleaf}{Whether to predict per-tree leaf indices.} |
| 65 |
|
| 66 |
\item{predcontrib}{Whether to return feature contributions to individual predictions (see Details).} |
| 67 |
|
| 68 |
\item{approxcontrib}{Whether to use a fast approximation for feature contributions (see Details).} |
| 69 |
|
| 70 |
\item{predinteraction}{Whether to return contributions of feature interactions to individual predictions (see Details).} |
| 71 |
|
| 72 |
\item{training}{Whether the prediction result is used for training. For dart booster, |
| 73 |
training predicting will perform dropout.} |
| 74 |
|
| 75 |
\item{iterationrange}{Sequence of rounds/iterations from the model to use for prediction, specified by passing |
| 76 |
a two-dimensional vector with the start and end numbers in the sequence (same format as R's \code{seq} - i.e. |
| 77 |
base-1 indexing, and inclusive of both ends). |
| 78 |
|
| 79 |
For example, passing \code{c(1,20)} will predict using the first twenty iterations, while passing \code{c(1,1)} will |
| 80 |
predict using only the first one. |
| 81 |
|
| 82 |
If passing \code{NULL}, will either stop at the best iteration if the model used early stopping, or use all |
| 83 |
of the iterations (rounds) otherwise. |
| 84 |
|
| 85 |
If passing "all", will use all of the rounds regardless of whether the model had early stopping or not. |
| 86 |
|
| 87 |
Not applicable to \code{gblinear} booster.} |
| 88 |
|
| 89 |
\item{strict_shape}{Whether to always return an array with the same dimensions for the given prediction mode |
| 90 |
regardless of the model type - meaning that, for example, both a multi-class and a binary classification |
| 91 |
model would generate output arrays with the same number of dimensions, with the 'class' dimension having |
| 92 |
size equal to '1' for the binary model. |
| 93 |
|
| 94 |
If passing \code{FALSE} (the default), dimensions will be simplified according to the model type, so that a |
| 95 |
binary classification model for example would not have a redundant dimension for 'class'. |
| 96 |
|
| 97 |
See documentation for the return type for the exact shape of the output arrays for each prediction mode.} |
| 98 |
|
| 99 |
\item{avoid_transpose}{Whether to output the resulting predictions in the same memory layout in which they |
| 100 |
are generated by the core XGBoost library, without transposing them to match the expected output shape. |
| 101 |
|
| 102 |
Internally, XGBoost uses row-major order for the predictions it generates, while R arrays use column-major |
| 103 |
order, hence the result needs to be transposed in order to have the expected shape when represented as |
| 104 |
an R array or matrix, which might be a slow operation. |
| 105 |
|
| 106 |
If passing \code{TRUE}, then the result will have dimensions in reverse order - for example, rows |
| 107 |
will be the last dimensions instead of the first dimension.} |
| 108 |
|
| 109 |
\item{validate_features}{When \code{TRUE}, validate that the Booster's and newdata's |
| 110 |
feature_names match (only applicable when both \code{object} and \code{newdata} have feature names). |
| 111 |
|
| 112 |
If the column names differ and \code{newdata} is not an \code{xgb.DMatrix}, will try to reorder |
| 113 |
the columns in \code{newdata} to match with the booster's. |
| 114 |
|
| 115 |
If the booster has feature types and \code{newdata} is either an \code{xgb.DMatrix} or |
| 116 |
\code{data.frame}, will additionally verify that categorical columns are of the |
| 117 |
correct type in \code{newdata}, throwing an error if they do not match. |
| 118 |
|
| 119 |
If passing \code{FALSE}, it is assumed that the feature names and types are the same, |
| 120 |
and come in the same order as in the training data. |
| 121 |
|
| 122 |
Note that this check might add some sizable latency to the predictions, so it's |
| 123 |
recommended to disable it for performance-sensitive applications.} |
| 124 |
|
| 125 |
\item{base_margin}{Base margin used for boosting from existing model (raw score that gets added to |
| 126 |
all observations independently of the trees in the model). |
| 127 |
|
| 128 |
If supplied, should be either a vector with length equal to the number of rows in \code{newdata} |
| 129 |
(for objectives which produces a single score per observation), or a matrix with number of |
| 130 |
rows matching to the number rows in \code{newdata} and number of columns matching to the number |
| 131 |
of scores estimated by the model (e.g. number of classes for multi-class classification). |
| 132 |
|
| 133 |
Note that, if \code{newdata} is an \code{xgb.DMatrix} object, this argument will |
| 134 |
be ignored as it needs to be added to the DMatrix instead (e.g. by passing it as |
| 135 |
an argument in its constructor, or by calling \code{\link[=setinfo.xgb.DMatrix]{setinfo.xgb.DMatrix()}}.} |
| 136 |
|
| 137 |
\item{...}{Not used.} |
| 138 |
} |
| 139 |
\value{ |
| 140 |
A numeric vector or array, with corresponding dimensions depending on the prediction mode and on |
| 141 |
parameter \code{strict_shape} as follows: |
| 142 |
|
| 143 |
If passing \code{strict_shape=FALSE}:\itemize{ |
| 144 |
\item For regression or binary classification: a vector of length \code{nrows}. |
| 145 |
\item For multi-class and multi-target objectives: a matrix of dimensions \verb{[nrows, ngroups]}. |
| 146 |
|
| 147 |
Note that objective variant \code{multi:softmax} defaults towards predicting most likely class (a vector |
| 148 |
\code{nrows}) instead of per-class probabilities. |
| 149 |
\item For \code{predleaf}: a matrix with one column per tree. |
| 150 |
|
| 151 |
For multi-class / multi-target, they will be arranged so that columns in the output will have |
| 152 |
the leafs from one group followed by leafs of the other group (e.g. order will be \code{group1:feat1}, |
| 153 |
\code{group1:feat2}, ..., \code{group2:feat1}, \code{group2:feat2}, ...). |
| 154 |
|
| 155 |
If there is more than one parallel tree (e.g. random forests), the parallel trees will be the |
| 156 |
last grouping in the resulting order, which will still be 2D. |
| 157 |
\item For \code{predcontrib}: when not multi-class / multi-target, a matrix with dimensions |
| 158 |
\verb{[nrows, nfeats+1]}. The last "+ 1" column corresponds to the baseline value. |
| 159 |
|
| 160 |
For multi-class and multi-target objectives, will be an array with dimensions \verb{[nrows, ngroups, nfeats+1]}. |
| 161 |
|
| 162 |
The contribution values are on the scale of untransformed margin (e.g., for binary classification, |
| 163 |
the values are log-odds deviations from the baseline). |
| 164 |
\item For \code{predinteraction}: when not multi-class / multi-target, the output is a 3D array of |
| 165 |
dimensions \verb{[nrows, nfeats+1, nfeats+1]}. The off-diagonal (in the last two dimensions) |
| 166 |
elements represent different feature interaction contributions. The array is symmetric w.r.t. the last |
| 167 |
two dimensions. The "+ 1" columns corresponds to the baselines. Summing this array along the last |
| 168 |
dimension should produce practically the same result as \code{predcontrib = TRUE}. |
| 169 |
|
| 170 |
For multi-class and multi-target, will be a 4D array with dimensions \verb{[nrows, ngroups, nfeats+1, nfeats+1]} |
| 171 |
} |
| 172 |
|
| 173 |
If passing \code{strict_shape=TRUE}, the result is always a matrix (if 2D) or array (if 3D or higher): |
| 174 |
\itemize{ |
| 175 |
\item For normal predictions, the dimension is \verb{[nrows, ngroups]}. |
| 176 |
\item For \code{predcontrib=TRUE}, the dimension is \verb{[nrows, ngroups, nfeats+1]}. |
| 177 |
\item For \code{predinteraction=TRUE}, the dimension is \verb{[nrows, ngroups, nfeats+1, nfeats+1]}. |
| 178 |
\item For \code{predleaf=TRUE}, the dimension is \verb{[nrows, niter, ngroups, num_parallel_tree]}. |
| 179 |
} |
| 180 |
|
| 181 |
If passing \code{avoid_transpose=TRUE}, then the dimensions in all cases will be in reverse order - for |
| 182 |
example, for \code{predinteraction}, they will be \verb{[nfeats+1, nfeats+1, ngroups, nrows]} |
| 183 |
instead of \verb{[nrows, ngroups, nfeats+1, nfeats+1]}. |
| 184 |
} |
| 185 |
\description{ |
| 186 |
Predict values on data based on XGBoost model. |
| 187 |
} |
| 188 |
\details{ |
| 189 |
Note that \code{iterationrange} would currently do nothing for predictions from "gblinear", |
| 190 |
since "gblinear" doesn't keep its boosting history. |
| 191 |
|
| 192 |
One possible practical applications of the \code{predleaf} option is to use the model |
| 193 |
as a generator of new features which capture non-linearity and interactions, |
| 194 |
e.g., as implemented in \code{\link[=xgb.create.features]{xgb.create.features()}}. |
| 195 |
|
| 196 |
Setting \code{predcontrib = TRUE} allows to calculate contributions of each feature to |
| 197 |
individual predictions. For "gblinear" booster, feature contributions are simply linear terms |
| 198 |
(feature_beta * feature_value). For "gbtree" booster, feature contributions are SHAP |
| 199 |
values (Lundberg 2017) that sum to the difference between the expected output |
| 200 |
of the model and the current prediction (where the hessian weights are used to compute the expectations). |
| 201 |
Setting \code{approxcontrib = TRUE} approximates these values following the idea explained |
| 202 |
in \url{http://blog.datadive.net/interpreting-random-forests/}. |
| 203 |
|
| 204 |
With \code{predinteraction = TRUE}, SHAP values of contributions of interaction of each pair of features |
| 205 |
are computed. Note that this operation might be rather expensive in terms of compute and memory. |
| 206 |
Since it quadratically depends on the number of features, it is recommended to perform selection |
| 207 |
of the most important features first. See below about the format of the returned results. |
| 208 |
|
| 209 |
The \code{predict()} method uses as many threads as defined in \code{xgb.Booster} object (all by default). |
| 210 |
If you want to change their number, assign a new number to \code{nthread} using \code{\link[=xgb.model.parameters<-]{xgb.model.parameters<-()}}. |
| 211 |
Note that converting a matrix to \code{\link[=xgb.DMatrix]{xgb.DMatrix()}} uses multiple threads too. |
| 212 |
} |
| 213 |
\examples{ |
| 214 |
\dontshow{RhpcBLASctl::omp_set_num_threads(1)} |
| 215 |
## binary classification: |
| 216 |
|
| 217 |
data(agaricus.train, package = "xgboost") |
| 218 |
data(agaricus.test, package = "xgboost") |
| 219 |
|
| 220 |
## Keep the number of threads to 2 for examples |
| 221 |
nthread <- 2 |
| 222 |
data.table::setDTthreads(nthread) |
| 223 |
|
| 224 |
train <- agaricus.train |
| 225 |
test <- agaricus.test |
| 226 |
|
| 227 |
bst <- xgb.train( |
| 228 |
data = xgb.DMatrix(train$data, label = train$label, nthread = 1), |
| 229 |
nrounds = 5, |
| 230 |
params = xgb.params( |
| 231 |
max_depth = 2, |
| 232 |
nthread = nthread, |
| 233 |
objective = "binary:logistic" |
| 234 |
) |
| 235 |
) |
| 236 |
|
| 237 |
# use all trees by default |
| 238 |
pred <- predict(bst, test$data) |
| 239 |
# use only the 1st tree |
| 240 |
pred1 <- predict(bst, test$data, iterationrange = c(1, 1)) |
| 241 |
|
| 242 |
# Predicting tree leafs: |
| 243 |
# the result is an nsamples X ntrees matrix |
| 244 |
pred_leaf <- predict(bst, test$data, predleaf = TRUE) |
| 245 |
str(pred_leaf) |
| 246 |
|
| 247 |
# Predicting feature contributions to predictions: |
| 248 |
# the result is an nsamples X (nfeatures + 1) matrix |
| 249 |
pred_contr <- predict(bst, test$data, predcontrib = TRUE) |
| 250 |
str(pred_contr) |
| 251 |
# verify that contributions' sums are equal to log-odds of predictions (up to float precision): |
| 252 |
summary(rowSums(pred_contr) - qlogis(pred)) |
| 253 |
# for the 1st record, let's inspect its features that had non-zero contribution to prediction: |
| 254 |
contr1 <- pred_contr[1,] |
| 255 |
contr1 <- contr1[-length(contr1)] # drop intercept |
| 256 |
contr1 <- contr1[contr1 != 0] # drop non-contributing features |
| 257 |
contr1 <- contr1[order(abs(contr1))] # order by contribution magnitude |
| 258 |
old_mar <- par("mar") |
| 259 |
par(mar = old_mar + c(0,7,0,0)) |
| 260 |
barplot(contr1, horiz = TRUE, las = 2, xlab = "contribution to prediction in log-odds") |
| 261 |
par(mar = old_mar) |
| 262 |
|
| 263 |
|
| 264 |
## multiclass classification in iris dataset: |
| 265 |
|
| 266 |
lb <- as.numeric(iris$Species) - 1 |
| 267 |
num_class <- 3 |
| 268 |
|
| 269 |
set.seed(11) |
| 270 |
|
| 271 |
bst <- xgb.train( |
| 272 |
data = xgb.DMatrix(as.matrix(iris[, -5], nthread = 1), label = lb), |
| 273 |
nrounds = 10, |
| 274 |
params = xgb.params( |
| 275 |
max_depth = 4, |
| 276 |
nthread = 2, |
| 277 |
subsample = 0.5, |
| 278 |
objective = "multi:softprob", |
| 279 |
num_class = num_class |
| 280 |
) |
| 281 |
) |
| 282 |
|
| 283 |
# predict for softmax returns num_class probability numbers per case: |
| 284 |
pred <- predict(bst, as.matrix(iris[, -5])) |
| 285 |
str(pred) |
| 286 |
# convert the probabilities to softmax labels |
| 287 |
pred_labels <- max.col(pred) - 1 |
| 288 |
# the following should result in the same error as seen in the last iteration |
| 289 |
sum(pred_labels != lb) / length(lb) |
| 290 |
|
| 291 |
# compare with predictions from softmax: |
| 292 |
set.seed(11) |
| 293 |
|
| 294 |
bst <- xgb.train( |
| 295 |
data = xgb.DMatrix(as.matrix(iris[, -5], nthread = 1), label = lb), |
| 296 |
nrounds = 10, |
| 297 |
params = xgb.params( |
| 298 |
max_depth = 4, |
| 299 |
nthread = 2, |
| 300 |
subsample = 0.5, |
| 301 |
objective = "multi:softmax", |
| 302 |
num_class = num_class |
| 303 |
) |
| 304 |
) |
| 305 |
|
| 306 |
pred <- predict(bst, as.matrix(iris[, -5])) |
| 307 |
str(pred) |
| 308 |
all.equal(pred, pred_labels) |
| 309 |
# prediction from using only 5 iterations should result |
| 310 |
# in the same error as seen in iteration 5: |
| 311 |
pred5 <- predict(bst, as.matrix(iris[, -5]), iterationrange = c(1, 5)) |
| 312 |
sum(pred5 != lb) / length(lb) |
| 313 |
|
| 314 |
} |
| 315 |
\references{ |
| 316 |
\enumerate{ |
| 317 |
\item Scott M. Lundberg, Su-In Lee, "A Unified Approach to Interpreting Model Predictions", |
| 318 |
NIPS Proceedings 2017, \url{https://arxiv.org/abs/1705.07874} |
| 319 |
\item Scott M. Lundberg, Su-In Lee, "Consistent feature attribution for tree ensembles", |
| 320 |
\url{https://arxiv.org/abs/1706.06060} |
| 321 |
} |
| 322 |
} |
| 323 |
\seealso{ |
| 324 |
\code{\link[=xgb.train]{xgb.train()}} |
| 325 |
} |