Debian Codegraph @

man/xgb.train.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/xgb.train.R
3 \name{xgb.train}
4 \alias{xgb.train}
5 \title{Fit XGBoost Model}
6 \usage{
7 xgb.train(
8 params = xgb.params(),
9 data,
10 nrounds,
11 evals = list(),
12 objective = NULL,
13 custom_metric = NULL,
14 verbose = 1,
15 print_every_n = 1L,
16 early_stopping_rounds = NULL,
17 maximize = NULL,
18 save_period = NULL,
19 save_name = "xgboost.model",
20 xgb_model = NULL,
21 callbacks = list(),
22 ...
23 )
24 }
25 \arguments{
26 \item{params}{List of XGBoost parameters which control the model building process.
27 See the \href{https://xgboost.readthedocs.io/en/latest/parameter.html}{online documentation}
28 and the documentation for \code{\link[=xgb.params]{xgb.params()}} for details.
29
30 Should be passed as list with named entries. Parameters that are not specified in this
31 list will use their default values.
32
33 A list of named parameters can be created through the function \code{\link[=xgb.params]{xgb.params()}}, which
34 accepts all valid parameters as function arguments.}
35
36 \item{data}{Training dataset. \code{xgb.train()} accepts only an \code{xgb.DMatrix} as the input.
37
38 Note that there is a function \code{\link[=xgboost]{xgboost()}} which is meant to accept R data objects
39 as inputs, such as data frames and matrices.}
40
41 \item{nrounds}{Max number of boosting iterations.}
42
43 \item{evals}{Named list of \code{xgb.DMatrix} datasets to use for evaluating model performance.
44 Metrics specified in either \code{eval_metric} (under params) or \code{custom_metric} (function
45 argument here) will be computed for each of these datasets during each boosting iteration,
46 and stored in the end as a field named \code{evaluation_log} in the resulting object.
47
48 When either \code{verbose>=1} or \code{\link[=xgb.cb.print.evaluation]{xgb.cb.print.evaluation()}} callback is engaged, the performance
49 results are continuously printed out during the training.
50
51 E.g., specifying \code{evals=list(validation1=mat1, validation2=mat2)} allows to track
52 the performance of each round's model on \code{mat1} and \code{mat2}.}
53
54 \item{objective}{Customized objective function. Should take two arguments: the first one will be the
55 current predictions (either a numeric vector or matrix depending on the number of targets / classes),
56 and the second one will be the \code{data} DMatrix object that is used for training.
57
58 It should return a list with two elements \code{grad} and \code{hess} (in that order), as either
59 numeric vectors or numeric matrices depending on the number of targets / classes (same
60 dimension as the predictions that are passed as first argument).}
61
62 \item{custom_metric}{Customized evaluation function. Just like \code{objective}, should take two arguments,
63 with the first one being the predictions and the second one the \code{data} DMatrix.
64
65 Should return a list with two elements \code{metric} (name that will be displayed for this metric,
66 should be a string / character), and \code{value} (the number that the function calculates, should
67 be a numeric scalar).
68
69 Note that even if passing \code{custom_metric}, objectives also have an associated default metric that
70 will be evaluated in addition to it. In order to disable the built-in metric, one can pass
71 parameter \code{disable_default_eval_metric = TRUE}.}
72
73 \item{verbose}{If 0, xgboost will stay silent. If 1, it will print information about performance.
74 If 2, some additional information will be printed out.
75 Note that setting \code{verbose > 0} automatically engages the
76 \code{xgb.cb.print.evaluation(period=1)} callback function.}
77
78 \item{print_every_n}{When passing \code{verbose>0}, evaluation logs (metrics calculated on the
79 data passed under \code{evals}) will be printed every nth iteration according to the value passed
80 here. The first and last iteration are always included regardless of this 'n'.
81
82 Only has an effect when passing data under \code{evals} and when passing \code{verbose>0}. The parameter
83 is passed to the \code{\link[=xgb.cb.print.evaluation]{xgb.cb.print.evaluation()}} callback.}
84
85 \item{early_stopping_rounds}{Number of boosting rounds after which training will be stopped
86 if there is no improvement in performance (as measured by the evaluatiation metric that is
87 supplied or selected by default for the objective) on the evaluation data passed under
88 \code{evals}.
89
90 Must pass \code{evals} in order to use this functionality. Setting this parameter adds the
91 \code{\link[=xgb.cb.early.stop]{xgb.cb.early.stop()}} callback.
92
93 If \code{NULL}, early stopping will not be used.}
94
95 \item{maximize}{If \code{feval} and \code{early_stopping_rounds} are set, then this parameter must be set as well.
96 When it is \code{TRUE}, it means the larger the evaluation score the better.
97 This parameter is passed to the \code{\link[=xgb.cb.early.stop]{xgb.cb.early.stop()}} callback.}
98
99 \item{save_period}{When not \code{NULL}, model is saved to disk after every \code{save_period} rounds.
100 0 means save at the end. The saving is handled by the \code{\link[=xgb.cb.save.model]{xgb.cb.save.model()}} callback.}
101
102 \item{save_name}{the name or path for periodically saved model file.}
103
104 \item{xgb_model}{A previously built model to continue the training from.
105 Could be either an object of class \code{xgb.Booster}, or its raw data, or the name of a
106 file with a previously saved model.}
107
108 \item{callbacks}{A list of callback functions to perform various task during boosting.
109 See \code{\link[=xgb.Callback]{xgb.Callback()}}. Some of the callbacks are automatically created depending on the
110 parameters' values. User can provide either existing or their own callback methods in order
111 to customize the training process.
112
113 Note that some callbacks might try to leave attributes in the resulting model object,
114 such as an evaluation log (a \code{data.table} object) - be aware that these objects are kept
115 as R attributes, and thus do not get saved when using XGBoost's own serializaters like
116 \code{\link[=xgb.save]{xgb.save()}} (but are kept when using R serializers like \code{\link[=saveRDS]{saveRDS()}}).}
117
118 \item{...}{Not used.
119
120 Some arguments that were part of this function in previous XGBoost versions are currently
121 deprecated or have been renamed. If a deprecated or renamed argument is passed, will throw
122 a warning (by default) and use its current equivalent instead. This warning will become an
123 error if using the \link[=xgboost-options]{'strict mode' option}.
124
125 If some additional argument is passed that is neither a current function argument nor
126 a deprecated or renamed argument, a warning or error will be thrown depending on the
127 'strict mode' option.
128
129 \bold{Important:} \code{...} will be removed in a future version, and all the current
130 deprecation warnings will become errors. Please use only arguments that form part of
131 the function signature.}
132 }
133 \value{
134 An object of class \code{xgb.Booster}.
135 }
136 \description{
137 Fits an XGBoost model to given data in DMatrix format (e.g. as produced by \code{\link[=xgb.DMatrix]{xgb.DMatrix()}}).
138 See the tutorial \href{https://xgboost.readthedocs.io/en/stable/tutorials/model.html}{Introduction to Boosted Trees}
139 for a longer explanation of what XGBoost does, and the rest of the
140 \href{https://xgboost.readthedocs.io/en/latest/tutorials/index.html}{XGBoost Tutorials} for further
141 explanations XGBoost's features and usage.
142
143 Compared to function \code{\link[=xgboost]{xgboost()}} which is a user-friendly function targeted towards interactive
144 usage, \code{xgb.train} is a lower-level interface which allows finer-grained control and exposes
145 further functionalities offered by the core library (such as learning-to-rank objectives), but
146 which works exclusively with XGBoost's own data format ("DMatrices") instead of with regular R
147 objects.
148
149 The syntax of this function closely mimics the same function from the Python package for XGBoost,
150 and is recommended to use for package developers over \code{xgboost()} as it will provide a more
151 stable interface (with fewer breaking changes) and lower overhead from data validations.
152
153 See also the \href{https://xgboost.readthedocs.io/en/latest/R-package/migration_guide.html}{migration guide}
154 if coming from a previous version of XGBoost in the 1.x series.
155 }
156 \details{
157 Compared to \code{\link[=xgboost]{xgboost()}}, the \code{xgb.train()} interface supports advanced features such as
158 \code{evals}, customized objective and evaluation metric functions, among others, with the
159 difference these work \code{xgb.DMatrix} objects and do not follow typical R idioms.
160
161 Parallelization is automatically enabled if OpenMP is present.
162 Number of threads can also be manually specified via the \code{nthread} parameter.
163
164 While in XGBoost language bindings, the default random seed defaults to zero, in R, if a parameter \code{seed}
165 is not manually supplied, it will generate a random seed through R's own random number generator,
166 whose seed in turn is controllable through \code{set.seed}. If \code{seed} is passed, it will override the
167 RNG from R.
168
169 The following callbacks are automatically created when certain parameters are set:
170 \itemize{
171 \item \code{\link[=xgb.cb.print.evaluation]{xgb.cb.print.evaluation()}} is turned on when \code{verbose > 0} and the \code{print_every_n}
172 parameter is passed to it.
173 \item \code{\link[=xgb.cb.evaluation.log]{xgb.cb.evaluation.log()}} is on when \code{evals} is present.
174 \item \code{\link[=xgb.cb.early.stop]{xgb.cb.early.stop()}}: When \code{early_stopping_rounds} is set.
175 \item \code{\link[=xgb.cb.save.model]{xgb.cb.save.model()}}: When \code{save_period > 0} is set.
176 }
177
178 Note that objects of type \code{xgb.Booster} as returned by this function behave a bit differently
179 from typical R objects (it's an 'altrep' list class), and it makes a separation between
180 internal booster attributes (restricted to jsonifyable data), accessed through \code{\link[=xgb.attr]{xgb.attr()}}
181 and shared between interfaces through serialization functions like \code{\link[=xgb.save]{xgb.save()}}; and
182 R-specific attributes (typically the result from a callback), accessed through \code{\link[=attributes]{attributes()}}
183 and \code{\link[=attr]{attr()}}, which are otherwise
184 only used in the R interface, only kept when using R's serializers like \code{\link[=saveRDS]{saveRDS()}}, and
185 not anyhow used by functions like \code{predict.xgb.Booster()}.
186
187 Be aware that one such R attribute that is automatically added is \code{params} - this attribute
188 is assigned from the \code{params} argument to this function, and is only meant to serve as a
189 reference for what went into the booster, but is not used in other methods that take a booster
190 object - so for example, changing the booster's configuration requires calling \verb{xgb.config<-}
191 or \verb{xgb.model.parameters<-}, while simply modifying \verb{attributes(model)$params$<...>} will have no
192 effect elsewhere.
193 }
194 \examples{
195 data(agaricus.train, package = "xgboost")
196 data(agaricus.test, package = "xgboost")
197
198 ## Keep the number of threads to 1 for examples
199 nthread <- 1
200 data.table::setDTthreads(nthread)
201
202 dtrain <- with(
203 agaricus.train, xgb.DMatrix(data, label = label, nthread = nthread)
204 )
205 dtest <- with(
206 agaricus.test, xgb.DMatrix(data, label = label, nthread = nthread)
207 )
208 evals <- list(train = dtrain, eval = dtest)
209
210 ## A simple xgb.train example:
211 param <- xgb.params(
212 max_depth = 2,
213 nthread = nthread,
214 objective = "binary:logistic",
215 eval_metric = "auc"
216 )
217 bst <- xgb.train(param, dtrain, nrounds = 2, evals = evals, verbose = 0)
218
219 ## An xgb.train example where custom objective and evaluation metric are
220 ## used:
221 logregobj <- function(preds, dtrain) {
222 labels <- getinfo(dtrain, "label")
223 preds <- 1/(1 + exp(-preds))
224 grad <- preds - labels
225 hess <- preds * (1 - preds)
226 return(list(grad = grad, hess = hess))
227 }
228 evalerror <- function(preds, dtrain) {
229 labels <- getinfo(dtrain, "label")
230 err <- as.numeric(sum(labels != (preds > 0)))/length(labels)
231 return(list(metric = "error", value = err))
232 }
233
234 # These functions could be used by passing them as 'objective' and
235 # 'eval_metric' parameters in the params list:
236 param <- xgb.params(
237 max_depth = 2,
238 nthread = nthread,
239 objective = logregobj,
240 eval_metric = evalerror
241 )
242 bst <- xgb.train(param, dtrain, nrounds = 2, evals = evals, verbose = 0)
243
244 # ... or as dedicated 'objective' and 'custom_metric' parameters of xgb.train:
245 bst <- xgb.train(
246 within(param, rm("objective", "eval_metric")),
247 dtrain, nrounds = 2, evals = evals,
248 objective = logregobj, custom_metric = evalerror
249 )
250
251
252 ## An xgb.train example of using variable learning rates at each iteration:
253 param <- xgb.params(
254 max_depth = 2,
255 learning_rate = 1,
256 nthread = nthread,
257 objective = "binary:logistic",
258 eval_metric = "auc"
259 )
260 my_learning_rates <- list(learning_rate = c(0.5, 0.1))
261
262 bst <- xgb.train(
263 param,
264 dtrain,
265 nrounds = 2,
266 evals = evals,
267 verbose = 0,
268 callbacks = list(xgb.cb.reset.parameters(my_learning_rates))
269 )
270
271 ## Early stopping:
272 bst <- xgb.train(
273 param, dtrain, nrounds = 25, evals = evals, early_stopping_rounds = 3
274 )
275 }
276 \references{
277 Tianqi Chen and Carlos Guestrin, "XGBoost: A Scalable Tree Boosting System",
278 22nd SIGKDD Conference on Knowledge Discovery and Data Mining, 2016, \url{https://arxiv.org/abs/1603.02754}
279 }
280 \seealso{
281 \code{\link[=xgb.Callback]{xgb.Callback()}}, \code{\link[=predict.xgb.Booster]{predict.xgb.Booster()}}, \code{\link[=xgb.cv]{xgb.cv()}}
282 }