% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/xgboost.R
\name{xgboost}
\alias{xgboost}
\title{Fit XGBoost Model}
\usage{
xgboost(
  x,
  y,
  objective = NULL,
  nrounds = 100L,
  max_depth = NULL,
  learning_rate = NULL,
  min_child_weight = NULL,
  min_split_loss = NULL,
  reg_lambda = NULL,
  weights = NULL,
  verbosity = if (is.null(eval_set)) 0L else 1L,
  monitor_training = verbosity > 0,
  eval_set = NULL,
  early_stopping_rounds = NULL,
  print_every_n = 1L,
  eval_metric = NULL,
  nthreads = parallel::detectCores(),
  seed = 0L,
  base_margin = NULL,
  monotone_constraints = NULL,
  interaction_constraints = NULL,
  reg_alpha = NULL,
  max_bin = NULL,
  max_leaves = NULL,
  booster = NULL,
  subsample = NULL,
  sampling_method = NULL,
  feature_weights = NULL,
  colsample_bytree = NULL,
  colsample_bylevel = NULL,
  colsample_bynode = NULL,
  tree_method = NULL,
  max_delta_step = NULL,
  scale_pos_weight = NULL,
  updater = NULL,
  grow_policy = NULL,
  num_parallel_tree = NULL,
  multi_strategy = NULL,
  base_score = NULL,
  seed_per_iteration = NULL,
  device = NULL,
  disable_default_eval_metric = NULL,
  use_rmm = NULL,
  max_cached_hist_node = NULL,
  max_cat_to_onehot = NULL,
  max_cat_threshold = NULL,
  sample_type = NULL,
  normalize_type = NULL,
  rate_drop = NULL,
  one_drop = NULL,
  skip_drop = NULL,
  feature_selector = NULL,
  top_k = NULL,
  tweedie_variance_power = NULL,
  huber_slope = NULL,
  quantile_alpha = NULL,
  aft_loss_distribution = NULL,
  ...
)
}
\arguments{
\item{x}{The features / covariates. Can be passed as:
\itemize{
\item A numeric or integer \code{matrix}.
\item A \code{data.frame}, in which all columns are one of the following types:
\itemize{
\item \code{numeric}
\item \code{integer}
\item \code{logical}
\item \code{factor}
}

Columns of \code{factor} type will be assumed to be categorical, while other column types will
be assumed to be numeric.
\item A sparse matrix from the \code{Matrix} package, either as \code{dgCMatrix} or \code{dgRMatrix} class.
}

Note that categorical features are only supported for \code{data.frame} inputs, and are automatically
determined based on their types. See \code{\link[=xgb.train]{xgb.train()}} with \code{\link[=xgb.DMatrix]{xgb.DMatrix()}} for more flexible
variants that would allow something like categorical features on sparse matrices.}

\item{y}{The response variable. Allowed values are:
\itemize{
\item A numeric or integer vector (for regression tasks).
\item A factor or character vector (for binary and multi-class classification tasks).
\item A logical (boolean) vector (for binary classification tasks).
\item A numeric or integer matrix or \code{data.frame} with numeric/integer columns
(for multi-task regression tasks).
\item A \code{Surv} object from the 'survival' package (for survival tasks).
}

If \code{objective} is \code{NULL}, the right task will be determined automatically based on
the class of \code{y}.

If \code{objective} is not \code{NULL}, it must match with the type of \code{y} - e.g. \code{factor} types of \code{y}
can only be used with classification objectives and vice-versa.

For binary classification, the last factor level of \code{y} will be used as the "positive"
class - that is, the numbers from \code{predict} will reflect the probabilities of belonging to this
class instead of to the first factor level. If \code{y} is a \code{logical} vector, then \code{TRUE} will be
set as the last level.}

\item{objective}{Optimization objective to minimize based on the supplied data, to be passed
by name as a string / character (e.g. \code{reg:absoluteerror}). See the
\href{https://xgboost.readthedocs.io/en/stable/parameter.html#learning-task-parameters}{Learning Task Parameters}
page and the \code{\link[=xgb.params]{xgb.params()}} documentation for more detailed information on allowed values.

If \code{NULL} (the default), will be automatically determined from \code{y} according to the following
logic:
\itemize{
\item If \code{y} is a factor with 2 levels, will use \code{binary:logistic}.
\item If \code{y} is a factor with more than 2 levels, will use \code{multi:softprob} (number of classes
will be determined automatically, should not be passed under \code{params}).
\item If \code{y} is a \code{Surv} object from the \code{survival} package, will use \code{survival:aft} (note that
the only types supported are left / right / interval censored).
\item Otherwise, will use \code{reg:squarederror}.
}

If \code{objective} is not \code{NULL}, it must match with the type of \code{y} - e.g. \code{factor} types of \code{y}
can only be used with classification objectives and vice-versa.

Note that not all possible \code{objective} values supported by the core XGBoost library are allowed
here - for example, objectives which are a variation of another but with a different default
prediction type (e.g. \code{multi:softmax} vs. \code{multi:softprob}) are not allowed, and neither are
ranking objectives, nor custom objectives at the moment.

Supported values are:
\itemize{
\item \code{"reg:squarederror"}: regression with squared loss.
\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.
\item \code{"reg:pseudohubererror"}: regression with Pseudo Huber loss, a twice differentiable alternative to absolute loss.
\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.
\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.
\item \code{"binary:logistic"}: logistic regression for binary classification, output probability
\item \code{"binary:hinge"}: hinge loss for binary classification. This makes predictions of 0 or 1, rather than producing probabilities.
\item \code{"count:poisson"}: Poisson regression for count data, output mean of Poisson distribution.
\code{"max_delta_step"} is set to 0.7 by default in Poisson regression (used to safeguard optimization)
\item \code{"survival:cox"}: Cox regression for right censored survival time data (negative values are considered right censored).

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}).
\item \code{"survival:aft"}: Accelerated failure time model for censored survival time data.
See \href{https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html}{Survival Analysis with Accelerated Failure Time} for details.
\item \code{"multi:softprob"}: multi-class classification throgh multinomial logistic likelihood.
\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}.
\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}.
}

The following values are \bold{NOT} supported by \code{xgboost}, but are supported by \code{\link[=xgb.train]{xgb.train()}}
(see \code{\link[=xgb.params]{xgb.params()}} for details):
\itemize{
\item \code{"reg:logistic"}
\item \code{"binary:logitraw"}
\item \code{"multi:softmax"}
\item \code{"rank:ndcg"}
\item \code{"rank:map"}
\item \code{"rank:pairwise"}
}}

\item{nrounds}{Number of boosting iterations / rounds.

Note that the number of default boosting rounds here is not automatically tuned, and different
problems will have vastly different optimal numbers of boosting rounds.}

\item{max_depth}{(for Tree Booster) (default=6, type=int32)
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.

range: \eqn{[0, \infty)}}

\item{learning_rate}{(alias: \code{eta})
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.
\itemize{
\item range: \eqn{[0,1]}
\item default value: 0.3 for tree-based boosters, 0.5 for linear booster.
}}

\item{min_child_weight}{(for Tree Booster) (default=1)
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.

range: \eqn{[0, \infty)}}

\item{min_split_loss}{(for Tree Booster) (default=0, alias: \code{gamma})
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.

range: \eqn{[0, \infty)}}

\item{reg_lambda}{(alias: \code{lambda})
\itemize{
\item For tree-based boosters:
\itemize{
\item L2 regularization term on weights. Increasing this value will make model more conservative.
\item default: 1
\item range: \eqn{[0, \infty]}
}
\item For linear booster:
\itemize{
\item L2 regularization term on weights. Increasing this value will make model more conservative. Normalised to number of training examples.
\item default: 0
\item range: \eqn{[0, \infty)}
}
}}

\item{weights}{Sample weights for each row in \code{x} and \code{y}. If \code{NULL} (the default), each row
will have the same weight.

If not \code{NULL}, should be passed as a numeric vector with length matching to the number of rows in \code{x}.}

\item{verbosity}{Verbosity of printing messages. Valid values of 0 (silent), 1 (warning),
2 (info), and 3 (debug).}

\item{monitor_training}{Whether to monitor objective optimization progress on the input data.
Note that same 'x' and 'y' data are used for both model fitting and evaluation.}

\item{eval_set}{Subset of the data to use as evaluation set. Can be passed as:
\itemize{
\item A vector of row indices (base-1 numeration) indicating the observations that are to be designed
as evaluation data.
\item A number between zero and one indicating a random fraction of the input data to use as
evaluation data. Note that the selection will be done uniformly at random, regardless of
argument \code{weights}.
}

If passed, this subset of the data will be excluded from the training procedure, and the
evaluation metric(s) supplied under \code{eval_metric} will be calculated on this dataset after each
boosting iteration (pass \code{verbosity>0} to have these metrics printed during training). If
\code{eval_metric} is not passed, a default metric will be selected according to \code{objective}.

If passing a fraction, in classification problems, the evaluation set will be chosen in such a
way that at least one observation of each class will be kept in the training data.

For more elaborate evaluation variants (e.g. custom metrics, multiple evaluation sets, etc.),
one might want to use \code{\link[=xgb.train]{xgb.train()}} instead.}

\item{early_stopping_rounds}{Number of boosting rounds after which training will be stopped
if there is no improvement in performance (as measured by the last metric passed under
\code{eval_metric}, or by the default metric for the objective if \code{eval_metric} is not passed) on the
evaluation data from \code{eval_set}. Must pass \code{eval_set} in order to use this functionality.

If \code{NULL}, early stopping will not be used.}

\item{print_every_n}{When passing \code{verbosity>0} and either \code{monitor_training=TRUE} or \code{eval_set},
evaluation logs (metrics calculated on the training and/or evaluation data) will be printed every
nth iteration according to the value passed here. The first and last iteration are always
included regardless of this 'n'.

Only has an effect when passing \code{verbosity>0}.}

\item{eval_metric}{(default according to objective)
\itemize{
\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.)
\item User can add multiple evaluation metrics.
\item The choices are listed below:
\itemize{
\item \code{"rmse"}: root mean square error
\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.
\item \code{"mae"}: mean absolute error.
\item \code{"mape"}: mean absolute percentage error.
\item \code{"mphe"}: mean Pseudo Huber error. Default metric of \code{"reg:pseudohubererror"} objective.
\item \code{"logloss"}: negative log-likelihood.
\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.
\item \code{"error@t"}: a different than 0.5 binary classification threshold value could be specified by providing a numerical value through 't'.
\item \code{"merror"}: Multiclass classification error rate. It is calculated as \verb{#(wrong cases)/#(all cases)}.
\item \code{"mlogloss"}: \href{https://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html}{Multiclass logloss}.
\item \code{"auc"}: area under the receiver-operating characteristic curve.
Available for classification and learning-to-rank tasks.
\itemize{
\item When used with binary classification, the objective should be \code{"binary:logistic"} or similar functions that work on probability.
\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.
\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.
\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.
\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.
}
\item \code{"aucpr"}: area under the PR curve
Available for classification and learning-to-rank tasks.

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.
\item \code{"pre"}: Precision at \eqn{k}. Supports only learning to rank task.
\item \code{"ndcg"}: normalized discounted cumulative gain
\item \code{"map"}: mean average precision

The \verb{average precision} is defined as:

\eqn{AP@l = \frac{1}{min{(l, N)}}\sum^l_{k=1}P@k \cdot I_{(k)}}

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.
\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.
\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.
\item \code{"poisson-nloglik"}: negative log-likelihood for Poisson regression
\item \code{"gamma-nloglik"}: negative log-likelihood for gamma regression
\item \code{"cox-nloglik"}: negative partial log-likelihood for Cox proportional hazards regression
\item \code{"gamma-deviance"}: residual deviance for gamma regression
\item \code{"tweedie-nloglik"}: negative log-likelihood for Tweedie regression (at a specified value of the \code{tweedie_variance_power} parameter)
\item \code{"aft-nloglik"}: Negative log likelihood of Accelerated Failure Time model.
See \href{https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html}{Survival Analysis with Accelerated Failure Time} for details.
\item \code{"interval-regression-accuracy"}: Fraction of data points whose predicted labels fall in the interval-censored labels.
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.
}
}}

\item{nthreads}{Number of parallel threads to use. If passing zero, will use all CPU threads.}

\item{seed}{Seed to use for random number generation. If passing \code{NULL}, will draw a random
number using R's PRNG system to use as seed.}

\item{base_margin}{Base margin used for boosting from existing model.

If passing it, will start the gradient boosting procedure from the scores that are provided
here - for example, one can pass the raw scores from a previous model, or some per-observation
offset, or similar.

Should be either a numeric vector or numeric matrix (for multi-class and multi-target objectives)
with the same number of rows as \code{x} and number of columns corresponding to number of optimization
targets, and should be in the untransformed scale (for example, for objective \code{binary:logistic},
it should have log-odds, not probabilities; and for objective \code{multi:softprob}, should have
number of columns matching to number of classes in the data).

Note that, if it contains more than one column, then columns will not be matched by name to
the corresponding \code{y} - \code{base_margin} should have the same column order that the model will use
(for example, for objective \code{multi:softprob}, columns of \code{base_margin} will be matched against
\code{levels(y)} by their position, regardless of what \code{colnames(base_margin)} returns).

If \code{NULL}, will start from zero, but note that for most objectives, an intercept is usually
added (controllable through parameter \code{base_score} instead) when \code{base_margin} is not passed.}

\item{monotone_constraints}{Optional monotonicity constraints for features.

Can be passed either as a named list (when \code{x} has column names), or as a vector. If passed
as a vector and \code{x} has column names, will try to match the elements by name.

A value of \code{+1} for a given feature makes the model predictions / scores constrained to be
a monotonically increasing function of that feature (that is, as the value of the feature
increases, the model prediction cannot decrease), while a value of \code{-1} makes it a monotonically
decreasing function. A value of zero imposes no constraint.

The input for \code{monotone_constraints} can be a subset of the columns of \code{x} if named, in which
case the columns that are not referred to in \code{monotone_constraints} will be assumed to have
a value of zero (no constraint imposed on the model for those features).

See the tutorial \href{https://xgboost.readthedocs.io/en/stable/tutorials/monotonic.html}{Monotonic Constraints}
for a more detailed explanation.}

\item{interaction_constraints}{Constraints for interaction representing permitted interactions.
The constraints must be specified in the form of a list of vectors referencing columns in the
data, e.g. \code{list(c(1, 2), c(3, 4, 5))} (with these numbers being column indices, numeration
starting at 1 - i.e. the first sublist references the first and second columns) or
\code{list(c("Sepal.Length", "Sepal.Width"), c("Petal.Length", "Petal.Width"))} (references
columns by names), where each vector is a group of indices of features that are allowed to
interact with each other.

See the tutorial \href{https://xgboost.readthedocs.io/en/stable/tutorials/feature_interaction_constraint.html}{Feature Interaction Constraints}
for more information.}

\item{reg_alpha}{(alias: \code{reg_alpha})
\itemize{
\item L1 regularization term on weights. Increasing this value will make model more conservative.
\item For the linear booster, it's normalised to number of training examples.
\item default: 0
\item range: \eqn{[0, \infty)}
}}

\item{max_bin}{(for Tree Booster) (default=256, type=int32)
\itemize{
\item Only used if \code{tree_method} is set to \code{"hist"} or \code{"approx"}.
\item Maximum number of discrete bins to bucket continuous features.
\item Increasing this number improves the optimality of splits at the cost of higher computation time.
}}

\item{max_leaves}{(for Tree Booster) (default=0, type=int32)
Maximum number of nodes to be added.  Not used by \code{"exact"} tree method.}

\item{booster}{(default= \code{"gbtree"})
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.}

\item{subsample}{(for Tree Booster) (default=1)
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.

range: \eqn{(0,1]}}

\item{sampling_method}{(for Tree Booster) (default= \code{"uniform"})
The method to use to sample the training instances.
\itemize{
\item \code{"uniform"}: each training instance has an equal probability of being selected. Typically set
\code{"subsample"} >= 0.5 for good results.
\item \code{"gradient_based"}: the selection probability for each training instance is proportional to the
\bold{regularized absolute value} of gradients (more specifically, \eqn{\sqrt{g^2+\lambda h^2}}).
\code{"subsample"} may be set to as low as 0.1 without loss of model accuracy. Note that this
sampling method is only supported when \code{"tree_method"} is set to \code{"hist"} and the device is \code{"cuda"}; other tree
methods only support \code{"uniform"} sampling.
}}

\item{feature_weights}{Feature weights for column sampling.

Can be passed either as a vector with length matching to columns of \code{x}, or as a named
list (only if \code{x} has column names) with names matching to columns of 'x'. If it is a
named vector, will try to match the entries to column names of \code{x} by name.

If \code{NULL} (the default), all columns will have the same weight.}

\item{colsample_bytree, colsample_bylevel, colsample_bynode}{(for Tree Booster) (default=1)
This is a family of parameters for subsampling of columns.
\itemize{
\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.
\item \code{"colsample_bytree"} is the subsample ratio of columns when constructing each tree. Subsampling occurs once for every tree constructed.
\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.
\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.
\item \code{"colsample_by*"} parameters work cumulatively. For instance,
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
each split.
}

One can set the \code{"feature_weights"} for DMatrix to
define the probability of each feature being selected when using column sampling.}

\item{tree_method}{(for Tree Booster) (default= \code{"auto"})
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}.

Choices: \code{"auto"}, \code{"exact"}, \code{"approx"}, \code{"hist"}, this is a combination of commonly
used updaters.  For other updaters like \code{"refresh"}, set the parameter \code{updater}
directly.
\itemize{
\item \code{"auto"}: Same as the \code{"hist"} tree method.
\item \code{"exact"}: Exact greedy algorithm.  Enumerates all split candidates.
\item \code{"approx"}: Approximate greedy algorithm using quantile sketch and gradient histogram.
\item \code{"hist"}: Faster histogram optimized approximate greedy algorithm.
}}

\item{max_delta_step}{(for Tree Booster) (default=0)
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.

range: \eqn{[0, \infty)}}

\item{scale_pos_weight}{(for Tree Booster) (default=1)
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}.}

\item{updater}{(for Linear Booster) (default= \code{"shotgun"})
Choice of algorithm to fit linear model
\itemize{
\item \code{"shotgun"}: Parallel coordinate descent algorithm based on shotgun algorithm. Uses 'hogwild' parallelism and therefore produces a nondeterministic solution on each run.
\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.
}}

\item{grow_policy}{(for Tree Booster) (default= \code{"depthwise"})
\itemize{
\item Controls a way new nodes are added to the tree.
\item Currently supported only if \code{tree_method} is set to \code{"hist"} or \code{"approx"}.
\item Choices: \code{"depthwise"}, \code{"lossguide"}
\itemize{
\item \code{"depthwise"}: split at nodes closest to the root.
\item \code{"lossguide"}: split at nodes with highest loss change.
}
}}

\item{num_parallel_tree}{(for Tree Booster) (default=1)
Number of parallel trees constructed during each iteration. This option is used to support boosted random forest.}

\item{multi_strategy}{(for Tree Booster) (default = \code{"one_output_per_tree"})
The strategy used for training multi-target models, including multi-target regression
and multi-class classification. See \href{https://xgboost.readthedocs.io/en/latest/tutorials/multioutput.html}{Multiple Outputs} for more information.
\itemize{
\item \code{"one_output_per_tree"}: One model for each target.
\item \code{"multi_output_tree"}:  Use multi-target trees.
}

Version added: 2.0.0

Note: This parameter is working-in-progress.}

\item{base_score}{\itemize{
\item The initial prediction score of all instances, global bias
\item The parameter is automatically estimated for selected objectives before training. To
disable the estimation, specify a real number argument.
\item If \code{base_margin} is supplied, \code{base_score} will not be added.
\item For sufficient number of iterations, changing this value will not have too much effect.
}}

\item{seed_per_iteration}{(default= \code{FALSE})
Seed PRNG determnisticly via iterator number.}

\item{device}{(default= \code{"cpu"})
Device for XGBoost to run. User can set it to one of the following values:
\itemize{
\item \code{"cpu"}: Use CPU.
\item \code{"cuda"}: Use a GPU (CUDA device).
\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).
\item \code{"gpu"}: Default GPU device selection from the list of available and supported devices. Only \code{"cuda"} devices are supported currently.
\item \code{"gpu:<ordinal>"}: Default GPU device selection from the list of available and supported devices. Only \code{"cuda"} devices are supported currently.
}

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.

Version added: 2.0.0

Note: if XGBoost was installed from CRAN, it won't have GPU support enabled, thus only \code{"cpu"} will be available.
To get GPU support, the R package for XGBoost must be installed from source or from the GitHub releases - see
\href{https://xgboost.readthedocs.io/en/latest/install.html#r}{instructions}.}

\item{disable_default_eval_metric}{(default= \code{FALSE})
Flag to disable default metric. Set to 1 or \code{TRUE} to disable.}

\item{use_rmm}{Whether to use RAPIDS Memory Manager (RMM) to allocate cache GPU
memory. The primary memory is always allocated on the RMM pool when XGBoost is built
(compiled) with the RMM plugin enabled. Valid values are \code{TRUE} and \code{FALSE}. See
\href{https://xgboost.readthedocs.io/en/latest/python/rmm-examples/index.html}{Using XGBoost with RAPIDS Memory Manager (RMM) plugin} for details.}

\item{max_cached_hist_node}{(for Non-Exact Tree Methods) (default = 65536)
Maximum number of cached nodes for histogram. This can be used with the \code{"hist"} and the
\code{"approx"} tree methods.

Version added: 2.0.0
\itemize{
\item For most of the cases this parameter should not be set except for growing deep
trees. After 3.0, this parameter affects GPU algorithms as well.
}}

\item{max_cat_to_onehot}{(for Non-Exact Tree Methods)
A threshold for deciding whether XGBoost should use one-hot encoding based split for
categorical data.  When number of categories is lesser than the threshold then one-hot
encoding is chosen, otherwise the categories will be partitioned into children nodes.

Version added: 1.6.0}

\item{max_cat_threshold}{(for Non-Exact Tree Methods)
Maximum number of categories considered for each split. Used only by partition-based
splits for preventing over-fitting.

Version added: 1.7.0}

\item{sample_type}{(for Dart Booster) (default= \code{"uniform"})
Type of sampling algorithm.
\itemize{
\item \code{"uniform"}: dropped trees are selected uniformly.
\item \code{"weighted"}: dropped trees are selected in proportion to weight.
}}

\item{normalize_type}{(for Dart Booster) (default= \code{"tree"})
Type of normalization algorithm.
\itemize{
\item \code{"tree"}: new trees have the same weight of each of dropped trees.
\itemize{
\item Weight of new trees are \code{1 / (k + learning_rate)}.
\item Dropped trees are scaled by a factor of \code{k / (k + learning_rate)}.
}
\item \code{"forest"}: new trees have the same weight of sum of dropped trees (forest).
\itemize{
\item Weight of new trees are \code{1 / (1 + learning_rate)}.
\item Dropped trees are scaled by a factor of \code{1 / (1 + learning_rate)}.
}
}}

\item{rate_drop}{(for Dart Booster) (default=0.0)
Dropout rate (a fraction of previous trees to drop during the dropout).

range: \eqn{[0.0, 1.0]}}

\item{one_drop}{(for Dart Booster) (default=0)
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).}

\item{skip_drop}{(for Dart Booster) (default=0.0)
Probability of skipping the dropout procedure during a boosting iteration.
\itemize{
\item If a dropout is skipped, new trees are added in the same manner as \code{"gbtree"}.
\item Note that non-zero \code{skip_drop} has higher priority than \code{rate_drop} or \code{one_drop}.
}

range: \eqn{[0.0, 1.0]}}

\item{feature_selector}{(for Linear Booster) (default= \code{"cyclic"})
Feature selection and ordering method
\itemize{
\item \code{"cyclic"}: Deterministic selection by cycling through features one at a time.
\item \code{"shuffle"}: Similar to \code{"cyclic"} but with random feature shuffling prior to each update.
\item \code{"random"}: A random (with replacement) coordinate selector.
\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)}.
\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.
}}

\item{top_k}{(for Linear Booster) (default=0)
The number of top features to select in \code{greedy} and \code{thrifty} feature selector. The value of 0 means using all the features.}

\item{tweedie_variance_power}{(for Tweedie Regression (\code{"objective=reg:tweedie"})) (default=1.5)
\itemize{
\item Parameter that controls the variance of the Tweedie distribution \code{var(y) ~ E(y)^tweedie_variance_power}
\item range: \eqn{(1,2)}
\item Set closer to 2 to shift towards a gamma distribution
\item Set closer to 1 to shift towards a Poisson distribution.
}}

\item{huber_slope}{(for using Pseudo-Huber (\verb{"reg:pseudohubererror}")) (default = 1.0)
A parameter used for Pseudo-Huber loss to define the \eqn{\delta} term.}

\item{quantile_alpha}{(for using Quantile Loss (\code{"reg:quantileerror"}))
A scalar or a list of targeted quantiles (passed as a numeric vector).

Version added: 2.0.0}

\item{aft_loss_distribution}{(for using AFT Survival Loss (\code{"survival:aft"}) and Negative Log Likelihood of AFT metric (\code{"aft-nloglik"}))
Probability Density Function, \code{"normal"}, \code{"logistic"}, or \code{"extreme"}.}

\item{...}{Not used.

Some arguments that were part of this function in previous XGBoost versions are currently
deprecated or have been renamed. If a deprecated or renamed argument is passed, will throw
a warning (by default) and use its current equivalent instead. This warning will become an
error if using the \link[=xgboost-options]{'strict mode' option}.

If some additional argument is passed that is neither a current function argument nor
a deprecated or renamed argument, a warning or error will be thrown depending on the
'strict mode' option.

\bold{Important:} \code{...} will be removed in a future version, and all the current
deprecation warnings will become errors. Please use only arguments that form part of
the function signature.}
}
\value{
A model object, inheriting from both \code{xgboost} and \code{xgb.Booster}. Compared to the regular
\code{xgb.Booster} model class produced by \code{\link[=xgb.train]{xgb.train()}}, this \code{xgboost} class will have an
additional attribute \code{metadata} containing information which is used for formatting prediction
outputs, such as class names for classification problems.
}
\description{
Fits an XGBoost model (boosted decision tree ensemble) to given x/y data.

See the tutorial \href{https://xgboost.readthedocs.io/en/stable/tutorials/model.html}{Introduction to Boosted Trees}
for a longer explanation of what XGBoost does, and the rest of the
\href{https://xgboost.readthedocs.io/en/latest/tutorials/index.html}{XGBoost Tutorials} for further
explanations XGBoost's features and usage.

This function is intended to provide a user-friendly interface for XGBoost that follows
R's conventions for model fitting and predictions, but which doesn't expose all of the
possible functionalities of the core XGBoost library.

See \code{\link[=xgb.train]{xgb.train()}} for a more flexible low-level alternative which is similar across different
language bindings of XGBoost and which exposes additional functionalities such as training on
external memory data and learning-to-rank objectives.

See also the \href{https://xgboost.readthedocs.io/en/latest/R-package/migration_guide.html}{migration guide}
if coming from a previous version of XGBoost in the 1.x series.

By default, most of the parameters here have a value of \code{NULL}, which signals XGBoost to use its
default value. Default values are automatically determined by the XGBoost core library, and are
subject to change over XGBoost library versions. Some of them might differ according to the
booster type (e.g. defaults for regularization are different for linear and tree-based boosters).
See \code{\link[=xgb.params]{xgb.params()}} and the \href{https://xgboost.readthedocs.io/en/latest/parameter.html}{online documentation}
for more details about parameters - but note that some of the parameters are not supported in
the \code{xgboost()} interface.
}
\details{
For package authors using 'xgboost' as a dependency, it is highly recommended to use
\code{\link[=xgb.train]{xgb.train()}} in package code instead of \code{\link[=xgboost]{xgboost()}}, since it has a more stable interface
and performs fewer data conversions and copies along the way.
}
\examples{
data(mtcars)

# Fit a small regression model on the mtcars data
model_regression <- xgboost(mtcars[, -1], mtcars$mpg, nthreads = 1, nrounds = 3)
predict(model_regression, mtcars, validate_features = TRUE)

# Task objective is determined automatically according to the type of 'y'
data(iris)
model_classif <- xgboost(iris[, -5], iris$Species, nthreads = 1, nrounds = 5)
predict(model_classif, iris[1:10,])
predict(model_classif, iris[1:10,], type = "class")

# Can nevertheless choose a non-default objective if needed
model_poisson <- xgboost(
  mtcars[, -1], mtcars$mpg,
  objective = "count:poisson",
  nthreads = 1,
  nrounds = 3
)

# Can calculate evaluation metrics during boosting rounds
data(ToothGrowth)
xgboost(
  ToothGrowth[, c("len", "dose")],
  ToothGrowth$supp,
  eval_metric = c("auc", "logloss"),
  eval_set = 0.2,
  monitor_training = TRUE,
  verbosity = 1,
  nthreads = 1,
  nrounds = 3
)
}
\references{
\itemize{
\item Chen, Tianqi, and Carlos Guestrin. "Xgboost: A scalable tree boosting system."
Proceedings of the 22nd acm sigkdd international conference on knowledge discovery and
data mining. 2016.
\item \url{https://xgboost.readthedocs.io/en/stable/}
}
}
