Debian Codegraph @

man/xgb.Callback.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/callbacks.R
3 \name{xgb.Callback}
4 \alias{xgb.Callback}
5 \title{XGBoost Callback Constructor}
6 \usage{
7 xgb.Callback(
8 cb_name = "custom_callback",
9 env = new.env(),
10 f_before_training = function(env, model, data, evals, begin_iteration, end_iteration)
11 NULL,
12 f_before_iter = function(env, model, data, evals, iteration) NULL,
13 f_after_iter = function(env, model, data, evals, iteration, iter_feval) NULL,
14 f_after_training = function(env, model, data, evals, iteration, final_feval,
15 prev_cb_res) NULL
16 )
17 }
18 \arguments{
19 \item{cb_name}{Name for the callback.
20
21 If the callback produces some non-NULL result (from executing the function passed under
22 \code{f_after_training}), that result will be added as an R attribute to the resulting booster
23 (or as a named element in the result of CV), with the attribute name specified here.
24
25 Names of callbacks must be unique - i.e. there cannot be two callbacks with the same name.}
26
27 \item{env}{An environment object that will be passed to the different functions in the callback.
28 Note that this environment will not be shared with other callbacks.}
29
30 \item{f_before_training}{A function that will be executed before the training has started.
31
32 If passing \code{NULL} for this or for the other function inputs, then no function will be executed.
33
34 If passing a function, it will be called with parameters supplied as non-named arguments
35 matching the function signatures that are shown in the default value for each function argument.}
36
37 \item{f_before_iter}{A function that will be executed before each boosting round.
38
39 This function can signal whether the training should be finalized or not, by outputting
40 a value that evaluates to \code{TRUE} - i.e. if the output from the function provided here at
41 a given round is \code{TRUE}, then training will be stopped before the current iteration happens.
42
43 Return values of \code{NULL} will be interpreted as \code{FALSE}.}
44
45 \item{f_after_iter}{A function that will be executed after each boosting round.
46
47 This function can signal whether the training should be finalized or not, by outputting
48 a value that evaluates to \code{TRUE} - i.e. if the output from the function provided here at
49 a given round is \code{TRUE}, then training will be stopped at that round.
50
51 Return values of \code{NULL} will be interpreted as \code{FALSE}.}
52
53 \item{f_after_training}{A function that will be executed after training is finished.
54
55 This function can optionally output something non-NULL, which will become part of the R
56 attributes of the booster (assuming one passes \code{keep_extra_attributes=TRUE} to \code{\link[=xgb.train]{xgb.train()}})
57 under the name supplied for parameter \code{cb_name} imn the case of \code{\link[=xgb.train]{xgb.train()}}; or a part
58 of the named elements in the result of \code{\link[=xgb.cv]{xgb.cv()}}.}
59 }
60 \value{
61 An \code{xgb.Callback} object, which can be passed to \code{\link[=xgb.train]{xgb.train()}} or \code{\link[=xgb.cv]{xgb.cv()}}.
62 }
63 \description{
64 Constructor for defining the structure of callback functions that can be executed
65 at different stages of model training (before / after training, before / after each boosting
66 iteration).
67 }
68 \details{
69 Arguments that will be passed to the supplied functions are as follows:
70 \itemize{
71 \item env The same environment that is passed under argument \code{env}.
72
73 It may be modified by the functions in order to e.g. keep tracking of what happens
74 across iterations or similar.
75
76 This environment is only used by the functions supplied to the callback, and will
77 not be kept after the model fitting function terminates (see parameter \code{f_after_training}).
78 \item model The booster object when using \code{\link[=xgb.train]{xgb.train()}}, or the folds when using \code{\link[=xgb.cv]{xgb.cv()}}.
79
80 For \code{\link[=xgb.cv]{xgb.cv()}}, folds are a list with a structure as follows:
81 \itemize{
82 \item \code{dtrain}: The training data for the fold (as an \code{xgb.DMatrix} object).
83 \item \code{bst}: Rhe \code{xgb.Booster} object for the fold.
84 \item \code{evals}: A list containing two DMatrices, with names \code{train} and \code{test}
85 (\code{test} is the held-out data for the fold).
86 \item \code{index}: The indices of the hold-out data for that fold (base-1 indexing),
87 from which the \code{test} entry in \code{evals} was obtained.
88 }
89
90 This object should \strong{not} be in-place modified in ways that conflict with the
91 training (e.g. resetting the parameters for a training update in a way that resets
92 the number of rounds to zero in order to overwrite rounds).
93
94 Note that any R attributes that are assigned to the booster during the callback functions,
95 will not be kept thereafter as the booster object variable is not re-assigned during
96 training. It is however possible to set C-level attributes of the booster through
97 \code{\link[=xgb.attr]{xgb.attr()}} or \code{\link[=xgb.attributes]{xgb.attributes()}}, which should remain available for the rest
98 of the iterations and after the training is done.
99
100 For keeping variables across iterations, it's recommended to use \code{env} instead.
101 \item data The data to which the model is being fit, as an \code{xgb.DMatrix} object.
102
103 Note that, for \code{\link[=xgb.cv]{xgb.cv()}}, this will be the full data, while data for the specific
104 folds can be found in the \code{model} object.
105 \item evals The evaluation data, as passed under argument \code{evals} to \code{\link[=xgb.train]{xgb.train()}}.
106
107 For \code{\link[=xgb.cv]{xgb.cv()}}, this will always be \code{NULL}.
108 \item begin_iteration Index of the first boosting iteration that will be executed (base-1 indexing).
109
110 This will typically be '1', but when using training continuation, depending on the
111 parameters for updates, boosting rounds will be continued from where the previous
112 model ended, in which case this will be larger than 1.
113 \item end_iteration Index of the last boostign iteration that will be executed
114 (base-1 indexing, inclusive of this end).
115
116 It should match with argument \code{nrounds} passed to \code{\link[=xgb.train]{xgb.train()}} or \code{\link[=xgb.cv]{xgb.cv()}}.
117
118 Note that boosting might be interrupted before reaching this last iteration, for
119 example by using the early stopping callback \code{\link[=xgb.cb.early.stop]{xgb.cb.early.stop()}}.
120 \item iteration Index of the iteration number that is being executed (first iteration
121 will be the same as parameter \code{begin_iteration}, then next one will add +1, and so on).
122 \item iter_feval Evaluation metrics for \code{evals} that were supplied, either
123 determined by the objective, or by parameter \code{custom_metric}.
124
125 For \code{\link[=xgb.train]{xgb.train()}}, this will be a named vector with one entry per element in
126 \code{evals}, where the names are determined as 'evals name' + '-' + 'metric name' - for
127 example, if \code{evals} contains an entry named "tr" and the metric is "rmse",
128 this will be a one-element vector with name "tr-rmse".
129
130 For \code{\link[=xgb.cv]{xgb.cv()}}, this will be a 2d matrix with dimensions \verb{[length(evals), nfolds]},
131 where the row names will follow the same naming logic as the one-dimensional vector
132 that is passed in \code{\link[=xgb.train]{xgb.train()}}.
133
134 Note that, internally, the built-in callbacks such as \link{xgb.cb.print.evaluation} summarize
135 this table by calculating the row-wise means and standard deviations.
136 \item final_feval The evaluation results after the last boosting round is executed
137 (same format as \code{iter_feval}, and will be the exact same input as passed under
138 \code{iter_feval} to the last round that is executed during model fitting).
139 \item prev_cb_res Result from a previous run of a callback sharing the same name
140 (as given by parameter \code{cb_name}) when conducting training continuation, if there
141 was any in the booster R attributes.
142
143 Sometimes, one might want to append the new results to the previous one, and this will
144 be done automatically by the built-in callbacks such as \link{xgb.cb.evaluation.log},
145 which will append the new rows to the previous table.
146
147 If no such previous callback result is available (which it never will when fitting
148 a model from start instead of updating an existing model), this will be \code{NULL}.
149
150 For \code{\link[=xgb.cv]{xgb.cv()}}, which doesn't support training continuation, this will always be \code{NULL}.
151 }
152
153 The following names (\code{cb_name} values) are reserved for internal callbacks:
154 \itemize{
155 \item print_evaluation
156 \item evaluation_log
157 \item reset_parameters
158 \item early_stop
159 \item save_model
160 \item cv_predict
161 \item gblinear_history
162 }
163
164 The following names are reserved for other non-callback attributes:
165 \itemize{
166 \item names
167 \item class
168 \item call
169 \item params
170 \item niter
171 \item nfeatures
172 \item folds
173 }
174
175 When using the built-in early stopping callback (\link{xgb.cb.early.stop}), said callback
176 will always be executed before the others, as it sets some booster C-level attributes
177 that other callbacks might also use. Otherwise, the order of execution will match with
178 the order in which the callbacks are passed to the model fitting function.
179 }
180 \examples{
181 # Example constructing a custom callback that calculates
182 # squared error on the training data (no separate test set),
183 # and outputs the per-iteration results.
184 ssq_callback <- xgb.Callback(
185 cb_name = "ssq",
186 f_before_training = function(env, model, data, evals,
187 begin_iteration, end_iteration) {
188 # A vector to keep track of a number at each iteration
189 env$logs <- rep(NA_real_, end_iteration - begin_iteration + 1)
190 },
191 f_after_iter = function(env, model, data, evals, iteration, iter_feval) {
192 # This calculates the sum of squared errors on the training data.
193 # Note that this can be better done by passing an 'evals' entry,
194 # but this demonstrates a way in which callbacks can be structured.
195 pred <- predict(model, data)
196 err <- pred - getinfo(data, "label")
197 sq_err <- sum(err^2)
198 env$logs[iteration] <- sq_err
199 cat(
200 sprintf(
201 "Squared error at iteration \%d: \%.2f\n",
202 iteration, sq_err
203 )
204 )
205
206 # A return value of 'TRUE' here would signal to finalize the training
207 return(FALSE)
208 },
209 f_after_training = function(env, model, data, evals, iteration,
210 final_feval, prev_cb_res) {
211 return(env$logs)
212 }
213 )
214
215 data(mtcars)
216
217 y <- mtcars$mpg
218 x <- as.matrix(mtcars[, -1])
219
220 dm <- xgb.DMatrix(x, label = y, nthread = 1)
221 model <- xgb.train(
222 data = dm,
223 params = xgb.params(objective = "reg:squarederror", nthread = 1),
224 nrounds = 5,
225 callbacks = list(ssq_callback)
226 )
227
228 # Result from 'f_after_iter' will be available as an attribute
229 attributes(model)$ssq
230 }
231 \seealso{
232 Built-in callbacks:
233 \itemize{
234 \item \link{xgb.cb.print.evaluation}
235 \item \link{xgb.cb.evaluation.log}
236 \item \link{xgb.cb.reset.parameters}
237 \item \link{xgb.cb.early.stop}
238 \item \link{xgb.cb.save.model}
239 \item \link{xgb.cb.cv.predict}
240 \item \link{xgb.cb.gblinear.history}
241 }
242 }