Debian Codegraph @

man/xgboost.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/xgboost.R
3 \name{xgboost}
4 \alias{xgboost}
5 \title{Fit XGBoost Model}
6 \usage{
7 xgboost(
8 x,
9 y,
10 objective = NULL,
11 nrounds = 100L,
12 max_depth = NULL,
13 learning_rate = NULL,
14 min_child_weight = NULL,
15 min_split_loss = NULL,
16 reg_lambda = NULL,
17 weights = NULL,
18 verbosity = if (is.null(eval_set)) 0L else 1L,
19 monitor_training = verbosity > 0,
20 eval_set = NULL,
21 early_stopping_rounds = NULL,
22 print_every_n = 1L,
23 eval_metric = NULL,
24 nthreads = parallel::detectCores(),
25 seed = 0L,
26 base_margin = NULL,
27 monotone_constraints = NULL,
28 interaction_constraints = NULL,
29 reg_alpha = NULL,
30 max_bin = NULL,
31 max_leaves = NULL,
32 booster = NULL,
33 subsample = NULL,
34 sampling_method = NULL,
35 feature_weights = NULL,
36 colsample_bytree = NULL,
37 colsample_bylevel = NULL,
38 colsample_bynode = NULL,
39 tree_method = NULL,
40 max_delta_step = NULL,
41 scale_pos_weight = NULL,
42 updater = NULL,
43 grow_policy = NULL,
44 num_parallel_tree = NULL,
45 multi_strategy = NULL,
46 base_score = NULL,
47 seed_per_iteration = NULL,
48 device = NULL,
49 disable_default_eval_metric = NULL,
50 use_rmm = NULL,
51 max_cached_hist_node = NULL,
52 max_cat_to_onehot = NULL,
53 max_cat_threshold = NULL,
54 sample_type = NULL,
55 normalize_type = NULL,
56 rate_drop = NULL,
57 one_drop = NULL,
58 skip_drop = NULL,
59 feature_selector = NULL,
60 top_k = NULL,
61 tweedie_variance_power = NULL,
62 huber_slope = NULL,
63 quantile_alpha = NULL,
64 aft_loss_distribution = NULL,
65 ...
66 )
67 }
68 \arguments{
69 \item{x}{The features / covariates. Can be passed as:
70 \itemize{
71 \item A numeric or integer \code{matrix}.
72 \item A \code{data.frame}, in which all columns are one of the following types:
73 \itemize{
74 \item \code{numeric}
75 \item \code{integer}
76 \item \code{logical}
77 \item \code{factor}
78 }
79
80 Columns of \code{factor} type will be assumed to be categorical, while other column types will
81 be assumed to be numeric.
82 \item A sparse matrix from the \code{Matrix} package, either as \code{dgCMatrix} or \code{dgRMatrix} class.
83 }
84
85 Note that categorical features are only supported for \code{data.frame} inputs, and are automatically
86 determined based on their types. See \code{\link[=xgb.train]{xgb.train()}} with \code{\link[=xgb.DMatrix]{xgb.DMatrix()}} for more flexible
87 variants that would allow something like categorical features on sparse matrices.}
88
89 \item{y}{The response variable. Allowed values are:
90 \itemize{
91 \item A numeric or integer vector (for regression tasks).
92 \item A factor or character vector (for binary and multi-class classification tasks).
93 \item A logical (boolean) vector (for binary classification tasks).
94 \item A numeric or integer matrix or \code{data.frame} with numeric/integer columns
95 (for multi-task regression tasks).
96 \item A \code{Surv} object from the 'survival' package (for survival tasks).
97 }
98
99 If \code{objective} is \code{NULL}, the right task will be determined automatically based on
100 the class of \code{y}.
101
102 If \code{objective} is not \code{NULL}, it must match with the type of \code{y} - e.g. \code{factor} types of \code{y}
103 can only be used with classification objectives and vice-versa.
104
105 For binary classification, the last factor level of \code{y} will be used as the "positive"
106 class - that is, the numbers from \code{predict} will reflect the probabilities of belonging to this
107 class instead of to the first factor level. If \code{y} is a \code{logical} vector, then \code{TRUE} will be
108 set as the last level.}
109
110 \item{objective}{Optimization objective to minimize based on the supplied data, to be passed
111 by name as a string / character (e.g. \code{reg:absoluteerror}). See the
112 \href{https://xgboost.readthedocs.io/en/stable/parameter.html#learning-task-parameters}{Learning Task Parameters}
113 page and the \code{\link[=xgb.params]{xgb.params()}} documentation for more detailed information on allowed values.
114
115 If \code{NULL} (the default), will be automatically determined from \code{y} according to the following
116 logic:
117 \itemize{
118 \item If \code{y} is a factor with 2 levels, will use \code{binary:logistic}.
119 \item If \code{y} is a factor with more than 2 levels, will use \code{multi:softprob} (number of classes
120 will be determined automatically, should not be passed under \code{params}).
121 \item If \code{y} is a \code{Surv} object from the \code{survival} package, will use \code{survival:aft} (note that
122 the only types supported are left / right / interval censored).
123 \item Otherwise, will use \code{reg:squarederror}.
124 }
125
126 If \code{objective} is not \code{NULL}, it must match with the type of \code{y} - e.g. \code{factor} types of \code{y}
127 can only be used with classification objectives and vice-versa.
128
129 Note that not all possible \code{objective} values supported by the core XGBoost library are allowed
130 here - for example, objectives which are a variation of another but with a different default
131 prediction type (e.g. \code{multi:softmax} vs. \code{multi:softprob}) are not allowed, and neither are
132 ranking objectives, nor custom objectives at the moment.
133
134 Supported values are:
135 \itemize{
136 \item \code{"reg:squarederror"}: regression with squared loss.
137 \item \code{"reg:squaredlogerror"}: regression with squared log loss \eqn{\frac{1}{2}[log(pred + 1) - log(label + 1)]^2}. All input labels are required to be greater than -1. Also, see metric \code{rmsle} for possible issue with this objective.
138 \item \code{"reg:pseudohubererror"}: regression with Pseudo Huber loss, a twice differentiable alternative to absolute loss.
139 \item \code{"reg:absoluteerror"}: Regression with L1 error. When tree model is used, leaf value is refreshed after tree construction. If used in distributed training, the leaf value is calculated as the mean value from all workers, which is not guaranteed to be optimal.
140 \item \code{"reg:quantileerror"}: Quantile loss, also known as "pinball loss". See later sections for its parameter and \href{https://xgboost.readthedocs.io/en/latest/python/examples/quantile_regression.html#sphx-glr-python-examples-quantile-regression-py}{Quantile Regression} for a worked example.
141 \item \code{"binary:logistic"}: logistic regression for binary classification, output probability
142 \item \code{"binary:hinge"}: hinge loss for binary classification. This makes predictions of 0 or 1, rather than producing probabilities.
143 \item \code{"count:poisson"}: Poisson regression for count data, output mean of Poisson distribution.
144 \code{"max_delta_step"} is set to 0.7 by default in Poisson regression (used to safeguard optimization)
145 \item \code{"survival:cox"}: Cox regression for right censored survival time data (negative values are considered right censored).
146
147 Note that predictions are returned on the hazard ratio scale (i.e., as HR = exp(marginal_prediction) in the proportional hazard function \code{h(t) = h0(t) * HR}).
148 \item \code{"survival:aft"}: Accelerated failure time model for censored survival time data.
149 See \href{https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html}{Survival Analysis with Accelerated Failure Time} for details.
150 \item \code{"multi:softprob"}: multi-class classification throgh multinomial logistic likelihood.
151 \item \code{"reg:gamma"}: gamma regression with log-link. Output is a mean of gamma distribution. It might be useful, e.g., for modeling insurance claims severity, or for any outcome that might be \href{https://en.wikipedia.org/wiki/Gamma_distribution#Occurrence_and_applications}{gamma-distributed}.
152 \item \code{"reg:tweedie"}: Tweedie regression with log-link. It might be useful, e.g., for modeling total loss in insurance, or for any outcome that might be \href{https://en.wikipedia.org/wiki/Tweedie_distribution#Occurrence_and_applications}{Tweedie-distributed}.
153 }
154
155 The following values are \bold{NOT} supported by \code{xgboost}, but are supported by \code{\link[=xgb.train]{xgb.train()}}
156 (see \code{\link[=xgb.params]{xgb.params()}} for details):
157 \itemize{
158 \item \code{"reg:logistic"}
159 \item \code{"binary:logitraw"}
160 \item \code{"multi:softmax"}
161 \item \code{"rank:ndcg"}
162 \item \code{"rank:map"}
163 \item \code{"rank:pairwise"}
164 }}
165
166 \item{nrounds}{Number of boosting iterations / rounds.
167
168 Note that the number of default boosting rounds here is not automatically tuned, and different
169 problems will have vastly different optimal numbers of boosting rounds.}
170
171 \item{max_depth}{(for Tree Booster) (default=6, type=int32)
172 Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit. 0 indicates no limit on depth. Beware that XGBoost aggressively consumes memory when training a deep tree. \code{"exact"} tree method requires non-zero value.
173
174 range: \eqn{[0, \infty)}}
175
176 \item{learning_rate}{(alias: \code{eta})
177 Step size shrinkage used in update to prevent overfitting. After each boosting step, we can directly get the weights of new features, and \code{learning_rate} shrinks the feature weights to make the boosting process more conservative.
178 \itemize{
179 \item range: \eqn{[0,1]}
180 \item default value: 0.3 for tree-based boosters, 0.5 for linear booster.
181 }}
182
183 \item{min_child_weight}{(for Tree Booster) (default=1)
184 Minimum sum of instance weight (hessian) needed in a child. If the tree partition step results in a leaf node with the sum of instance weight less than \code{min_child_weight}, then the building process will give up further partitioning. In linear regression task, this simply corresponds to minimum number of instances needed to be in each node. The larger \code{min_child_weight} is, the more conservative the algorithm will be.
185
186 range: \eqn{[0, \infty)}}
187
188 \item{min_split_loss}{(for Tree Booster) (default=0, alias: \code{gamma})
189 Minimum loss reduction required to make a further partition on a leaf node of the tree. The larger \code{min_split_loss} is, the more conservative the algorithm will be. Note that a tree where no splits were made might still contain a single terminal node with a non-zero score.
190
191 range: \eqn{[0, \infty)}}
192
193 \item{reg_lambda}{(alias: \code{lambda})
194 \itemize{
195 \item For tree-based boosters:
196 \itemize{
197 \item L2 regularization term on weights. Increasing this value will make model more conservative.
198 \item default: 1
199 \item range: \eqn{[0, \infty]}
200 }
201 \item For linear booster:
202 \itemize{
203 \item L2 regularization term on weights. Increasing this value will make model more conservative. Normalised to number of training examples.
204 \item default: 0
205 \item range: \eqn{[0, \infty)}
206 }
207 }}
208
209 \item{weights}{Sample weights for each row in \code{x} and \code{y}. If \code{NULL} (the default), each row
210 will have the same weight.
211
212 If not \code{NULL}, should be passed as a numeric vector with length matching to the number of rows in \code{x}.}
213
214 \item{verbosity}{Verbosity of printing messages. Valid values of 0 (silent), 1 (warning),
215 2 (info), and 3 (debug).}
216
217 \item{monitor_training}{Whether to monitor objective optimization progress on the input data.
218 Note that same 'x' and 'y' data are used for both model fitting and evaluation.}
219
220 \item{eval_set}{Subset of the data to use as evaluation set. Can be passed as:
221 \itemize{
222 \item A vector of row indices (base-1 numeration) indicating the observations that are to be designed
223 as evaluation data.
224 \item A number between zero and one indicating a random fraction of the input data to use as
225 evaluation data. Note that the selection will be done uniformly at random, regardless of
226 argument \code{weights}.
227 }
228
229 If passed, this subset of the data will be excluded from the training procedure, and the
230 evaluation metric(s) supplied under \code{eval_metric} will be calculated on this dataset after each
231 boosting iteration (pass \code{verbosity>0} to have these metrics printed during training). If
232 \code{eval_metric} is not passed, a default metric will be selected according to \code{objective}.
233
234 If passing a fraction, in classification problems, the evaluation set will be chosen in such a
235 way that at least one observation of each class will be kept in the training data.
236
237 For more elaborate evaluation variants (e.g. custom metrics, multiple evaluation sets, etc.),
238 one might want to use \code{\link[=xgb.train]{xgb.train()}} instead.}
239
240 \item{early_stopping_rounds}{Number of boosting rounds after which training will be stopped
241 if there is no improvement in performance (as measured by the last metric passed under
242 \code{eval_metric}, or by the default metric for the objective if \code{eval_metric} is not passed) on the
243 evaluation data from \code{eval_set}. Must pass \code{eval_set} in order to use this functionality.
244
245 If \code{NULL}, early stopping will not be used.}
246
247 \item{print_every_n}{When passing \code{verbosity>0} and either \code{monitor_training=TRUE} or \code{eval_set},
248 evaluation logs (metrics calculated on the training and/or evaluation data) will be printed every
249 nth iteration according to the value passed here. The first and last iteration are always
250 included regardless of this 'n'.
251
252 Only has an effect when passing \code{verbosity>0}.}
253
254 \item{eval_metric}{(default according to objective)
255 \itemize{
256 \item Evaluation metrics for validation data, a default metric will be assigned according to objective (rmse for regression, and logloss for classification, \verb{mean average precision} for \code{rank:map}, etc.)
257 \item User can add multiple evaluation metrics.
258 \item The choices are listed below:
259 \itemize{
260 \item \code{"rmse"}: root mean square error
261 \item \code{"rmsle"}: root mean square log error: \eqn{\sqrt{\frac{1}{N}[log(pred + 1) - log(label + 1)]^2}}. Default metric of \code{"reg:squaredlogerror"} objective. This metric reduces errors generated by outliers in dataset. But because \code{log} function is employed, \code{"rmsle"} might output \code{nan} when prediction value is less than -1. See \code{"reg:squaredlogerror"} for other requirements.
262 \item \code{"mae"}: mean absolute error.
263 \item \code{"mape"}: mean absolute percentage error.
264 \item \code{"mphe"}: mean Pseudo Huber error. Default metric of \code{"reg:pseudohubererror"} objective.
265 \item \code{"logloss"}: negative log-likelihood.
266 \item \code{"error"}: Binary classification error rate. It is calculated as \verb{#(wrong cases)/#(all cases)}. For the predictions, the evaluation will regard the instances with prediction value larger than 0.5 as positive instances, and the others as negative instances.
267 \item \code{"error@t"}: a different than 0.5 binary classification threshold value could be specified by providing a numerical value through 't'.
268 \item \code{"merror"}: Multiclass classification error rate. It is calculated as \verb{#(wrong cases)/#(all cases)}.
269 \item \code{"mlogloss"}: \href{https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html}{Multiclass logloss}.
270 \item \code{"auc"}: area under the receiver-operating characteristic curve.
271 Available for classification and learning-to-rank tasks.
272 \itemize{
273 \item When used with binary classification, the objective should be \code{"binary:logistic"} or similar functions that work on probability.
274 \item When used with multi-class classification, objective should be \code{"multi:softprob"} instead of \code{"multi:softmax"}, as the latter doesn't output probability. Also the AUC is calculated by 1-vs-rest with reference class weighted by class prevalence.
275 \item When used with LTR task, the AUC is computed by comparing pairs of documents to count correctly sorted pairs. This corresponds to pairwise learning to rank. The implementation has some issues with average AUC around groups and distributed workers not being well-defined.
276 \item On a single machine the AUC calculation is exact. In a distributed environment the AUC is a weighted average over the AUC of training rows on each node - therefore, distributed AUC is an approximation sensitive to the distribution of data across workers. Use another metric in distributed environments if precision and reproducibility are important.
277 \item When input dataset contains only negative or positive samples, the output is \code{NaN}. The behavior is implementation defined, for instance, \code{scikit-learn} returns \eqn{0.5} instead.
278 }
279 \item \code{"aucpr"}: area under the PR curve
280 Available for classification and learning-to-rank tasks.
281
282 After XGBoost 1.6, both of the requirements and restrictions for using \code{"aucpr"} in classification problem are similar to \code{"auc"}. For ranking task, only binary relevance label \eqn{y \in [0, 1]} is supported. Different from \code{"map"} (mean average precision), \code{"aucpr"} calculates the \emph{interpolated} area under precision recall curve using continuous interpolation.
283 \item \code{"pre"}: Precision at \eqn{k}. Supports only learning to rank task.
284 \item \code{"ndcg"}: normalized discounted cumulative gain
285 \item \code{"map"}: mean average precision
286
287 The \verb{average precision} is defined as:
288
289 \eqn{AP@l = \frac{1}{min{(l, N)}}\sum^l_{k=1}P@k \cdot I_{(k)}}
290
291 where \eqn{I_{(k)}} is an indicator function that equals to \eqn{1} when the document at \eqn{k} is relevant and \eqn{0} otherwise. The \eqn{P@k} is the precision at \eqn{k}, and \eqn{N} is the total number of relevant documents. Lastly, the \verb{mean average precision} is defined as the weighted average across all queries.
292 \item \code{"ndcg@n"}, \code{"map@n"}, \code{"pre@n"}: \eqn{n} can be assigned as an integer to cut off the top positions in the lists for evaluation.
293 \item \code{"ndcg-"}, \code{"map-"}, \code{"ndcg@n-"}, \code{"map@n-"}: In XGBoost, the NDCG and MAP evaluate the score of a list without any positive samples as \eqn{1}. By appending "-" to the evaluation metric name, we can ask XGBoost to evaluate these scores as \eqn{0} to be consistent under some conditions.
294 \item \code{"poisson-nloglik"}: negative log-likelihood for Poisson regression
295 \item \code{"gamma-nloglik"}: negative log-likelihood for gamma regression
296 \item \code{"cox-nloglik"}: negative partial log-likelihood for Cox proportional hazards regression
297 \item \code{"gamma-deviance"}: residual deviance for gamma regression
298 \item \code{"tweedie-nloglik"}: negative log-likelihood for Tweedie regression (at a specified value of the \code{tweedie_variance_power} parameter)
299 \item \code{"aft-nloglik"}: Negative log likelihood of Accelerated Failure Time model.
300 See \href{https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html}{Survival Analysis with Accelerated Failure Time} for details.
301 \item \code{"interval-regression-accuracy"}: Fraction of data points whose predicted labels fall in the interval-censored labels.
302 Only applicable for interval-censored data. See \href{https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html}{Survival Analysis with Accelerated Failure Time} for details.
303 }
304 }}
305
306 \item{nthreads}{Number of parallel threads to use. If passing zero, will use all CPU threads.}
307
308 \item{seed}{Seed to use for random number generation. If passing \code{NULL}, will draw a random
309 number using R's PRNG system to use as seed.}
310
311 \item{base_margin}{Base margin used for boosting from existing model.
312
313 If passing it, will start the gradient boosting procedure from the scores that are provided
314 here - for example, one can pass the raw scores from a previous model, or some per-observation
315 offset, or similar.
316
317 Should be either a numeric vector or numeric matrix (for multi-class and multi-target objectives)
318 with the same number of rows as \code{x} and number of columns corresponding to number of optimization
319 targets, and should be in the untransformed scale (for example, for objective \code{binary:logistic},
320 it should have log-odds, not probabilities; and for objective \code{multi:softprob}, should have
321 number of columns matching to number of classes in the data).
322
323 Note that, if it contains more than one column, then columns will not be matched by name to
324 the corresponding \code{y} - \code{base_margin} should have the same column order that the model will use
325 (for example, for objective \code{multi:softprob}, columns of \code{base_margin} will be matched against
326 \code{levels(y)} by their position, regardless of what \code{colnames(base_margin)} returns).
327
328 If \code{NULL}, will start from zero, but note that for most objectives, an intercept is usually
329 added (controllable through parameter \code{base_score} instead) when \code{base_margin} is not passed.}
330
331 \item{monotone_constraints}{Optional monotonicity constraints for features.
332
333 Can be passed either as a named list (when \code{x} has column names), or as a vector. If passed
334 as a vector and \code{x} has column names, will try to match the elements by name.
335
336 A value of \code{+1} for a given feature makes the model predictions / scores constrained to be
337 a monotonically increasing function of that feature (that is, as the value of the feature
338 increases, the model prediction cannot decrease), while a value of \code{-1} makes it a monotonically
339 decreasing function. A value of zero imposes no constraint.
340
341 The input for \code{monotone_constraints} can be a subset of the columns of \code{x} if named, in which
342 case the columns that are not referred to in \code{monotone_constraints} will be assumed to have
343 a value of zero (no constraint imposed on the model for those features).
344
345 See the tutorial \href{https://xgboost.readthedocs.io/en/stable/tutorials/monotonic.html}{Monotonic Constraints}
346 for a more detailed explanation.}
347
348 \item{interaction_constraints}{Constraints for interaction representing permitted interactions.
349 The constraints must be specified in the form of a list of vectors referencing columns in the
350 data, e.g. \code{list(c(1, 2), c(3, 4, 5))} (with these numbers being column indices, numeration
351 starting at 1 - i.e. the first sublist references the first and second columns) or
352 \code{list(c("Sepal.Length", "Sepal.Width"), c("Petal.Length", "Petal.Width"))} (references
353 columns by names), where each vector is a group of indices of features that are allowed to
354 interact with each other.
355
356 See the tutorial \href{https://xgboost.readthedocs.io/en/stable/tutorials/feature_interaction_constraint.html}{Feature Interaction Constraints}
357 for more information.}
358
359 \item{reg_alpha}{(alias: \code{reg_alpha})
360 \itemize{
361 \item L1 regularization term on weights. Increasing this value will make model more conservative.
362 \item For the linear booster, it's normalised to number of training examples.
363 \item default: 0
364 \item range: \eqn{[0, \infty)}
365 }}
366
367 \item{max_bin}{(for Tree Booster) (default=256, type=int32)
368 \itemize{
369 \item Only used if \code{tree_method} is set to \code{"hist"} or \code{"approx"}.
370 \item Maximum number of discrete bins to bucket continuous features.
371 \item Increasing this number improves the optimality of splits at the cost of higher computation time.
372 }}
373
374 \item{max_leaves}{(for Tree Booster) (default=0, type=int32)
375 Maximum number of nodes to be added. Not used by \code{"exact"} tree method.}
376
377 \item{booster}{(default= \code{"gbtree"})
378 Which booster to use. Can be \code{"gbtree"}, \code{"gblinear"} or \code{"dart"}; \code{"gbtree"} and \code{"dart"} use tree based models while \code{"gblinear"} uses linear functions.}
379
380 \item{subsample}{(for Tree Booster) (default=1)
381 Subsample ratio of the training instances. Setting it to 0.5 means that XGBoost would randomly sample half of the training data prior to growing trees. and this will prevent overfitting. Subsampling will occur once in every boosting iteration.
382
383 range: \eqn{(0,1]}}
384
385 \item{sampling_method}{(for Tree Booster) (default= \code{"uniform"})
386 The method to use to sample the training instances.
387 \itemize{
388 \item \code{"uniform"}: each training instance has an equal probability of being selected. Typically set
389 \code{"subsample"} >= 0.5 for good results.
390 \item \code{"gradient_based"}: the selection probability for each training instance is proportional to the
391 \bold{regularized absolute value} of gradients (more specifically, \eqn{\sqrt{g^2+\lambda h^2}}).
392 \code{"subsample"} may be set to as low as 0.1 without loss of model accuracy. Note that this
393 sampling method is only supported when \code{"tree_method"} is set to \code{"hist"}; other tree
394 methods only support \code{"uniform"} sampling.
395 }}
396
397 \item{feature_weights}{Feature weights for column sampling.
398
399 Can be passed either as a vector with length matching to columns of \code{x}, or as a named
400 list (only if \code{x} has column names) with names matching to columns of 'x'. If it is a
401 named vector, will try to match the entries to column names of \code{x} by name.
402
403 If \code{NULL} (the default), all columns will have the same weight.}
404
405 \item{colsample_bytree, colsample_bylevel, colsample_bynode}{(for Tree Booster) (default=1)
406 This is a family of parameters for subsampling of columns.
407 \itemize{
408 \item All \code{"colsample_by*"} parameters have a range of \eqn{(0, 1]}, the default value of 1, and specify the fraction of columns to be subsampled.
409 \item \code{"colsample_bytree"} is the subsample ratio of columns when constructing each tree. Subsampling occurs once for every tree constructed.
410 \item \code{"colsample_bylevel"} is the subsample ratio of columns for each level. Subsampling occurs once for every new depth level reached in a tree. Columns are subsampled from the set of columns chosen for the current tree.
411 \item \code{"colsample_bynode"} is the subsample ratio of columns for each node (split). Subsampling occurs once every time a new split is evaluated. Columns are subsampled from the set of columns chosen for the current level. This is not supported by the exact tree method.
412 \item \code{"colsample_by*"} parameters work cumulatively. For instance,
413 the combination \verb{\{'colsample_bytree'=0.5, 'colsample_bylevel'=0.5, 'colsample_bynode'=0.5\}} with 64 features will leave 8 features to choose from at
414 each split.
415 }
416
417 One can set the \code{"feature_weights"} for DMatrix to
418 define the probability of each feature being selected when using column sampling.}
419
420 \item{tree_method}{(for Tree Booster) (default= \code{"auto"})
421 The tree construction algorithm used in XGBoost. See description in the \href{https://arxiv.org/abs/1603.02754}{reference paper} and \href{https://xgboost.readthedocs.io/en/latest/treemethod.html}{Tree Methods}.
422
423 Choices: \code{"auto"}, \code{"exact"}, \code{"approx"}, \code{"hist"}, this is a combination of commonly
424 used updaters. For other updaters like \code{"refresh"}, set the parameter \code{updater}
425 directly.
426 \itemize{
427 \item \code{"auto"}: Same as the \code{"hist"} tree method.
428 \item \code{"exact"}: Exact greedy algorithm. Enumerates all split candidates.
429 \item \code{"approx"}: Approximate greedy algorithm using quantile sketch and gradient histogram.
430 \item \code{"hist"}: Faster histogram optimized approximate greedy algorithm.
431 }}
432
433 \item{max_delta_step}{(for Tree Booster) (default=0)
434 Maximum delta step we allow each leaf output to be. If the value is set to 0, it means there is no constraint. If it is set to a positive value, it can help making the update step more conservative. Usually this parameter is not needed, but it might help in logistic regression when class is extremely imbalanced. Set it to value of 1-10 might help control the update.
435
436 range: \eqn{[0, \infty)}}
437
438 \item{scale_pos_weight}{(for Tree Booster) (default=1)
439 Control the balance of positive and negative weights, useful for unbalanced classes. A typical value to consider: \verb{sum(negative instances) / sum(positive instances)}. See \href{https://xgboost.readthedocs.io/en/latest/tutorials/param_tuning.html}{Parameters Tuning} for more discussion. Also, see Higgs Kaggle competition demo for examples: \href{https://github.com/dmlc/xgboost/blob/master/demo/kaggle-higgs/higgs-train.R}{R}, \href{https://github.com/dmlc/xgboost/blob/master/demo/kaggle-higgs/higgs-numpy.py}{py1}, \href{https://github.com/dmlc/xgboost/blob/master/demo/kaggle-higgs/higgs-cv.py}{py2}, \href{https://github.com/dmlc/xgboost/blob/master/demo/guide-python/cross_validation.py}{py3}.}
440
441 \item{updater}{(for Linear Booster) (default= \code{"shotgun"})
442 Choice of algorithm to fit linear model
443 \itemize{
444 \item \code{"shotgun"}: Parallel coordinate descent algorithm based on shotgun algorithm. Uses 'hogwild' parallelism and therefore produces a nondeterministic solution on each run.
445 \item \code{"coord_descent"}: Ordinary coordinate descent algorithm. Also multithreaded but still produces a deterministic solution. When the \code{device} parameter is set to \code{"cuda"} or \code{"gpu"}, a GPU variant would be used.
446 }}
447
448 \item{grow_policy}{(for Tree Booster) (default= \code{"depthwise"})
449 \itemize{
450 \item Controls a way new nodes are added to the tree.
451 \item Currently supported only if \code{tree_method} is set to \code{"hist"} or \code{"approx"}.
452 \item Choices: \code{"depthwise"}, \code{"lossguide"}
453 \itemize{
454 \item \code{"depthwise"}: split at nodes closest to the root.
455 \item \code{"lossguide"}: split at nodes with highest loss change.
456 }
457 }}
458
459 \item{num_parallel_tree}{(for Tree Booster) (default=1)
460 Number of parallel trees constructed during each iteration. This option is used to support boosted random forest.}
461
462 \item{multi_strategy}{(for Tree Booster) (default = \code{"one_output_per_tree"})
463 The strategy used for training multi-target models, including multi-target regression
464 and multi-class classification. See \href{https://xgboost.readthedocs.io/en/latest/tutorials/multioutput.html}{Multiple Outputs} for more information.
465 \itemize{
466 \item \code{"one_output_per_tree"}: One model for each target.
467 \item \code{"multi_output_tree"}: Use multi-target trees.
468 }
469
470 Version added: 2.0.0
471
472 Note: This parameter is working-in-progress.}
473
474 \item{base_score}{\itemize{
475 \item The initial prediction score of all instances, global bias
476 \item The parameter is automatically estimated for selected objectives before training. To
477 disable the estimation, specify a real number argument.
478 \item If \code{base_margin} is supplied, \code{base_score} will not be added.
479 \item For sufficient number of iterations, changing this value will not have too much effect.
480 }}
481
482 \item{seed_per_iteration}{(default= \code{FALSE})
483 Seed PRNG determnisticly via iterator number.}
484
485 \item{device}{(default= \code{"cpu"})
486 Device for XGBoost to run. User can set it to one of the following values:
487 \itemize{
488 \item \code{"cpu"}: Use CPU.
489 \item \code{"cuda"}: Use a GPU (CUDA device).
490 \item \code{"cuda:<ordinal>"}: \verb{<ordinal>} is an integer that specifies the ordinal of the GPU (which GPU do you want to use if you have more than one devices).
491 \item \code{"gpu"}: Default GPU device selection from the list of available and supported devices. Only \code{"cuda"} devices are supported currently.
492 \item \code{"gpu:<ordinal>"}: Default GPU device selection from the list of available and supported devices. Only \code{"cuda"} devices are supported currently.
493 }
494
495 For more information about GPU acceleration, see \href{https://xgboost.readthedocs.io/en/latest/gpu/index.html}{XGBoost GPU Support}. In distributed environments, ordinal selection is handled by distributed frameworks instead of XGBoost. As a result, using \code{"cuda:<ordinal>"} will result in an error. Use \code{"cuda"} instead.
496
497 Version added: 2.0.0
498
499 Note: if XGBoost was installed from CRAN, it won't have GPU support enabled, thus only \code{"cpu"} will be available.
500 To get GPU support, the R package for XGBoost must be installed from source or from the GitHub releases - see
501 \href{https://xgboost.readthedocs.io/en/latest/install.html#r}{instructions}.}
502
503 \item{disable_default_eval_metric}{(default= \code{FALSE})
504 Flag to disable default metric. Set to 1 or \code{TRUE} to disable.}
505
506 \item{use_rmm}{Whether to use RAPIDS Memory Manager (RMM) to allocate cache GPU
507 memory. The primary memory is always allocated on the RMM pool when XGBoost is built
508 (compiled) with the RMM plugin enabled. Valid values are \code{TRUE} and \code{FALSE}. See
509 \href{https://xgboost.readthedocs.io/en/latest/python/rmm-examples/index.html}{Using XGBoost with RAPIDS Memory Manager (RMM) plugin} for details.}
510
511 \item{max_cached_hist_node}{(for Non-Exact Tree Methods) (default = 65536)
512 Maximum number of cached nodes for histogram. This can be used with the \code{"hist"} and the
513 \code{"approx"} tree methods.
514
515 Version added: 2.0.0
516 \itemize{
517 \item For most of the cases this parameter should not be set except for growing deep
518 trees. After 3.0, this parameter affects GPU algorithms as well.
519 }}
520
521 \item{max_cat_to_onehot}{(for Non-Exact Tree Methods)
522 A threshold for deciding whether XGBoost should use one-hot encoding based split for
523 categorical data. When number of categories is lesser than the threshold then one-hot
524 encoding is chosen, otherwise the categories will be partitioned into children nodes.
525
526 Version added: 1.6.0}
527
528 \item{max_cat_threshold}{(for Non-Exact Tree Methods)
529 Maximum number of categories considered for each split. Used only by partition-based
530 splits for preventing over-fitting.
531
532 Version added: 1.7.0}
533
534 \item{sample_type}{(for Dart Booster) (default= \code{"uniform"})
535 Type of sampling algorithm.
536 \itemize{
537 \item \code{"uniform"}: dropped trees are selected uniformly.
538 \item \code{"weighted"}: dropped trees are selected in proportion to weight.
539 }}
540
541 \item{normalize_type}{(for Dart Booster) (default= \code{"tree"})
542 Type of normalization algorithm.
543 \itemize{
544 \item \code{"tree"}: new trees have the same weight of each of dropped trees.
545 \itemize{
546 \item Weight of new trees are \code{1 / (k + learning_rate)}.
547 \item Dropped trees are scaled by a factor of \code{k / (k + learning_rate)}.
548 }
549 \item \code{"forest"}: new trees have the same weight of sum of dropped trees (forest).
550 \itemize{
551 \item Weight of new trees are \code{1 / (1 + learning_rate)}.
552 \item Dropped trees are scaled by a factor of \code{1 / (1 + learning_rate)}.
553 }
554 }}
555
556 \item{rate_drop}{(for Dart Booster) (default=0.0)
557 Dropout rate (a fraction of previous trees to drop during the dropout).
558
559 range: \eqn{[0.0, 1.0]}}
560
561 \item{one_drop}{(for Dart Booster) (default=0)
562 When this flag is enabled, at least one tree is always dropped during the dropout (allows Binomial-plus-one or epsilon-dropout from the original DART paper).}
563
564 \item{skip_drop}{(for Dart Booster) (default=0.0)
565 Probability of skipping the dropout procedure during a boosting iteration.
566 \itemize{
567 \item If a dropout is skipped, new trees are added in the same manner as \code{"gbtree"}.
568 \item Note that non-zero \code{skip_drop} has higher priority than \code{rate_drop} or \code{one_drop}.
569 }
570
571 range: \eqn{[0.0, 1.0]}}
572
573 \item{feature_selector}{(for Linear Booster) (default= \code{"cyclic"})
574 Feature selection and ordering method
575 \itemize{
576 \item \code{"cyclic"}: Deterministic selection by cycling through features one at a time.
577 \item \code{"shuffle"}: Similar to \code{"cyclic"} but with random feature shuffling prior to each update.
578 \item \code{"random"}: A random (with replacement) coordinate selector.
579 \item \code{"greedy"}: Select coordinate with the greatest gradient magnitude. It has \code{O(num_feature^2)} complexity. It is fully deterministic. It allows restricting the selection to \code{top_k} features per group with the largest magnitude of univariate weight change, by setting the \code{top_k} parameter. Doing so would reduce the complexity to \code{O(num_feature*top_k)}.
580 \item \code{"thrifty"}: Thrifty, approximately-greedy feature selector. Prior to cyclic updates, reorders features in descending magnitude of their univariate weight changes. This operation is multithreaded and is a linear complexity approximation of the quadratic greedy selection. It allows restricting the selection to \code{top_k} features per group with the largest magnitude of univariate weight change, by setting the \code{top_k} parameter.
581 }}
582
583 \item{top_k}{(for Linear Booster) (default=0)
584 The number of top features to select in \code{greedy} and \code{thrifty} feature selector. The value of 0 means using all the features.}
585
586 \item{tweedie_variance_power}{(for Tweedie Regression (\code{"objective=reg:tweedie"})) (default=1.5)
587 \itemize{
588 \item Parameter that controls the variance of the Tweedie distribution \code{var(y) ~ E(y)^tweedie_variance_power}
589 \item range: \eqn{(1,2)}
590 \item Set closer to 2 to shift towards a gamma distribution
591 \item Set closer to 1 to shift towards a Poisson distribution.
592 }}
593
594 \item{huber_slope}{(for using Pseudo-Huber (\verb{"reg:pseudohubererror}")) (default = 1.0)
595 A parameter used for Pseudo-Huber loss to define the \eqn{\delta} term.}
596
597 \item{quantile_alpha}{(for using Quantile Loss (\code{"reg:quantileerror"}))
598 A scalar or a list of targeted quantiles (passed as a numeric vector).
599
600 Version added: 2.0.0}
601
602 \item{aft_loss_distribution}{(when using AFT Survival Loss (\code{"survival:aft"}) and Negative Log Likelihood of AFT metric (\code{"aft-nloglik"}))
603 Probability Density Function, \code{"normal"}, \code{"logistic"}, or \code{"extreme"}.}
604
605 \item{...}{Not used.
606
607 Some arguments that were part of this function in previous XGBoost versions are currently
608 deprecated or have been renamed. If a deprecated or renamed argument is passed, will throw
609 a warning (by default) and use its current equivalent instead. This warning will become an
610 error if using the \link[=xgboost-options]{'strict mode' option}.
611
612 If some additional argument is passed that is neither a current function argument nor
613 a deprecated or renamed argument, a warning or error will be thrown depending on the
614 'strict mode' option.
615
616 \bold{Important:} \code{...} will be removed in a future version, and all the current
617 deprecation warnings will become errors. Please use only arguments that form part of
618 the function signature.}
619 }
620 \value{
621 A model object, inheriting from both \code{xgboost} and \code{xgb.Booster}. Compared to the regular
622 \code{xgb.Booster} model class produced by \code{\link[=xgb.train]{xgb.train()}}, this \code{xgboost} class will have an
623 additional attribute \code{metadata} containing information which is used for formatting prediction
624 outputs, such as class names for classification problems.
625 }
626 \description{
627 Fits an XGBoost model (boosted decision tree ensemble) to given x/y data.
628
629 See the tutorial \href{https://xgboost.readthedocs.io/en/stable/tutorials/model.html}{Introduction to Boosted Trees}
630 for a longer explanation of what XGBoost does, and the rest of the
631 \href{https://xgboost.readthedocs.io/en/latest/tutorials/index.html}{XGBoost Tutorials} for further
632 explanations XGBoost's features and usage.
633
634 This function is intended to provide a user-friendly interface for XGBoost that follows
635 R's conventions for model fitting and predictions, but which doesn't expose all of the
636 possible functionalities of the core XGBoost library.
637
638 See \code{\link[=xgb.train]{xgb.train()}} for a more flexible low-level alternative which is similar across different
639 language bindings of XGBoost and which exposes additional functionalities such as training on
640 external memory data and learning-to-rank objectives.
641
642 See also the \href{https://xgboost.readthedocs.io/en/latest/R-package/migration_guide.html}{migration guide}
643 if coming from a previous version of XGBoost in the 1.x series.
644
645 By default, most of the parameters here have a value of \code{NULL}, which signals XGBoost to use its
646 default value. Default values are automatically determined by the XGBoost core library, and are
647 subject to change over XGBoost library versions. Some of them might differ according to the
648 booster type (e.g. defaults for regularization are different for linear and tree-based boosters).
649 See \code{\link[=xgb.params]{xgb.params()}} and the \href{https://xgboost.readthedocs.io/en/latest/parameter.html}{online documentation}
650 for more details about parameters - but note that some of the parameters are not supported in
651 the \code{xgboost()} interface.
652 }
653 \details{
654 For package authors using 'xgboost' as a dependency, it is highly recommended to use
655 \code{\link[=xgb.train]{xgb.train()}} in package code instead of \code{\link[=xgboost]{xgboost()}}, since it has a more stable interface
656 and performs fewer data conversions and copies along the way.
657 }
658 \examples{
659 data(mtcars)
660
661 # Fit a small regression model on the mtcars data
662 model_regression <- xgboost(mtcars[, -1], mtcars$mpg, nthreads = 1, nrounds = 3)
663 predict(model_regression, mtcars, validate_features = TRUE)
664
665 # Task objective is determined automatically according to the type of 'y'
666 data(iris)
667 model_classif <- xgboost(iris[, -5], iris$Species, nthreads = 1, nrounds = 5)
668 predict(model_classif, iris[1:10,])
669 predict(model_classif, iris[1:10,], type = "class")
670
671 # Can nevertheless choose a non-default objective if needed
672 model_poisson <- xgboost(
673 mtcars[, -1], mtcars$mpg,
674 objective = "count:poisson",
675 nthreads = 1,
676 nrounds = 3
677 )
678
679 # Can calculate evaluation metrics during boosting rounds
680 data(ToothGrowth)
681 xgboost(
682 ToothGrowth[, c("len", "dose")],
683 ToothGrowth$supp,
684 eval_metric = c("auc", "logloss"),
685 eval_set = 0.2,
686 monitor_training = TRUE,
687 verbosity = 1,
688 nthreads = 1,
689 nrounds = 3
690 )
691 }
692 \references{
693 \itemize{
694 \item Chen, Tianqi, and Carlos Guestrin. "Xgboost: A scalable tree boosting system."
695 Proceedings of the 22nd acm sigkdd international conference on knowledge discovery and
696 data mining. 2016.
697 \item \url{https://xgboost.readthedocs.io/en/stable/}
698 }
699 }