lgb.train.R 13.1 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
#' @name lgb.train
2
#' @title Main training logic for LightGBM
James Lamb's avatar
James Lamb committed
3
4
#' @description Logic to train with LightGBM
#' @inheritParams lgb_shared_params
5
#' @param valids a list of \code{lgb.Dataset} objects, used for validation
6
#' @param record Boolean, TRUE will record iteration message to \code{booster$record_evals}
Guolin Ke's avatar
Guolin Ke committed
7
#' @param colnames feature names, if not null, will use this to overwrite the names in dataset
8
9
10
#' @param categorical_feature categorical features. This can either be a character vector of feature
#'                            names or an integer vector with the indices of the features (e.g.
#'                            \code{c(1L, 10L)} to say "the first and tenth columns").
11
12
13
14
#' @param callbacks List of callback functions that are applied at each iteration.
#' @param reset_data Boolean, setting it to TRUE (not the default value) will transform the
#'                   booster model into a predictor model which frees up memory and the
#'                   original datasets
15
16
#' @param ... other parameters, see \href{https://lightgbm.readthedocs.io/en/latest/Parameters.html}{
#'            the "Parameters" section of the documentation} for more information. A few key parameters:
James Lamb's avatar
James Lamb committed
17
#'            \itemize{
18
19
20
#'                \item{\code{boosting}: Boosting type. \code{"gbdt"}, \code{"rf"}, \code{"dart"} or \code{"goss"}.}
#'                \item{\code{num_leaves}: Maximum number of leaves in one tree.}
#'                \item{\code{max_depth}: Limit the max depth for tree model. This is used to deal with
21
#'                                 overfitting. Tree still grow by leaf-wise.}
22
#'                \item{\code{num_threads}: Number of threads for LightGBM. For the best speed, set this to
23
24
25
#'                             the number of real CPU cores(\code{parallel::detectCores(logical = FALSE)}),
#'                             not the number of threads (most CPU using hyper-threading to generate 2 threads
#'                             per CPU core).}
James Lamb's avatar
James Lamb committed
26
#'            }
27
#'            NOTE: As of v3.3.0, use of \code{...} is deprecated. Add parameters to \code{params} directly.
28
#' @inheritSection lgb_shared_params Early Stopping
29
#' @return a trained booster model \code{lgb.Booster}.
30
#'
Guolin Ke's avatar
Guolin Ke committed
31
#' @examples
32
#' \donttest{
33
34
35
36
37
38
39
40
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' data(agaricus.test, package = "lightgbm")
#' test <- agaricus.test
#' dtest <- lgb.Dataset.create.valid(dtrain, test$data, label = test$label)
#' params <- list(objective = "regression", metric = "l2")
#' valids <- list(test = dtest)
41
42
43
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
44
#'   , nrounds = 5L
45
#'   , valids = valids
46
47
#'   , min_data = 1L
#'   , learning_rate = 1.0
48
#'   , early_stopping_rounds = 3L
49
#' )
50
#' }
Guolin Ke's avatar
Guolin Ke committed
51
#' @export
52
53
lgb.train <- function(params = list(),
                      data,
54
                      nrounds = 100L,
55
56
57
                      valids = list(),
                      obj = NULL,
                      eval = NULL,
58
                      verbose = 1L,
59
60
61
62
63
                      record = TRUE,
                      eval_freq = 1L,
                      init_model = NULL,
                      colnames = NULL,
                      categorical_feature = NULL,
64
                      early_stopping_rounds = NULL,
65
                      callbacks = list(),
66
                      reset_data = FALSE,
67
                      ...) {
68

69
70
71
72
  # validate inputs early to avoid unnecessary computation
  if (nrounds <= 0L) {
    stop("nrounds should be greater than zero")
  }
73
  if (!lgb.is.Dataset(x = data)) {
74
75
76
    stop("lgb.train: data must be an lgb.Dataset instance")
  }
  if (length(valids) > 0L) {
77
    if (!identical(class(valids), "list") || !all(vapply(valids, lgb.is.Dataset, logical(1L)))) {
78
79
80
81
82
83
84
85
      stop("lgb.train: valids must be a list of lgb.Dataset elements")
    }
    evnames <- names(valids)
    if (is.null(evnames) || !all(nzchar(evnames))) {
      stop("lgb.train: each element of valids must have a name")
    }
  }

86
  # Setup temporary variables
87
  additional_params <- list(...)
88
  params <- append(params, additional_params)
Guolin Ke's avatar
Guolin Ke committed
89
  params$verbose <- verbose
90
91
  params <- lgb.check.obj(params = params, obj = obj)
  params <- lgb.check.eval(params = params, eval = eval)
92
  fobj <- NULL
93
  eval_functions <- list(NULL)
94

95
96
97
98
99
100
101
102
103
  if (length(additional_params) > 0L) {
    warning(paste0(
      "lgb.train: Found the following passed through '...': "
      , paste(names(additional_params), collapse = ", ")
      , ". These will be used, but in future releases of lightgbm, this warning will become an error. "
      , "Add these to 'params' instead. See ?lgb.train for documentation on how to call this function."
    ))
  }

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
  # set some parameters, resolving the way they were passed in with other parameters
  # in `params`.
  # this ensures that the model stored with Booster$save() correctly represents
  # what was passed in
  params <- lgb.check.wrapper_param(
    main_param_name = "num_iterations"
    , params = params
    , alternative_kwarg_value = nrounds
  )
  params <- lgb.check.wrapper_param(
    main_param_name = "early_stopping_round"
    , params = params
    , alternative_kwarg_value = early_stopping_rounds
  )
  early_stopping_rounds <- params[["early_stopping_round"]]

120
  # Check for objective (function or not)
121
  if (is.function(params$objective)) {
122
    fobj <- params$objective
Guolin Ke's avatar
Guolin Ke committed
123
124
    params$objective <- "NONE"
  }
125

126
  # If eval is a single function, store it as a 1-element list
127
  # (for backwards compatibility). If it is a list of functions, store
128
129
  # all of them. This makes it possible to pass any mix of strings like "auc"
  # and custom functions to eval
130
  if (is.function(eval)) {
131
132
133
134
135
136
137
    eval_functions <- list(eval)
  }
  if (methods::is(eval, "list")) {
    eval_functions <- Filter(
      f = is.function
      , x = eval
    )
138
  }
139

140
  # Init predictor to empty
Guolin Ke's avatar
Guolin Ke committed
141
  predictor <- NULL
142

143
  # Check for boosting from a trained model
144
  if (is.character(init_model)) {
145
    predictor <- Predictor$new(modelfile = init_model)
146
  } else if (lgb.is.Booster(x = init_model)) {
Guolin Ke's avatar
Guolin Ke committed
147
148
    predictor <- init_model$to_predictor()
  }
149

150
  # Set the iteration to start from / end to (and check for boosting from a trained model, again)
151
  begin_iteration <- 1L
152
  if (!is.null(predictor)) {
153
    begin_iteration <- predictor$current_iter() + 1L
Guolin Ke's avatar
Guolin Ke committed
154
  }
155
  end_iteration <- begin_iteration + params[["num_iterations"]] - 1L
156

157
158
159
160
161
  # pop interaction_constraints off of params. It needs some preprocessing on the
  # R side before being passed into the Dataset object
  interaction_constraints <- params[["interaction_constraints"]]
  params["interaction_constraints"] <- NULL

162
163
164
165
  # Construct datasets, if needed
  data$update_params(params = params)
  data$construct()

166
167
168
169
170
171
  # Check interaction constraints
  cnames <- NULL
  if (!is.null(colnames)) {
    cnames <- colnames
  } else if (!is.null(data$get_colnames())) {
    cnames <- data$get_colnames()
172
  }
173
  params[["interaction_constraints"]] <- lgb.check_interaction_constraints(
174
    interaction_constraints = interaction_constraints
175
176
    , column_names = cnames
  )
177

178
  # Update parameters with parsed parameters
Guolin Ke's avatar
Guolin Ke committed
179
  data$update_params(params)
180

181
  # Create the predictor set
Guolin Ke's avatar
Guolin Ke committed
182
  data$.__enclos_env__$private$set_predictor(predictor)
183

184
185
186
187
  # Write column names
  if (!is.null(colnames)) {
    data$set_colnames(colnames)
  }
188

189
190
191
192
  # Write categorical features
  if (!is.null(categorical_feature)) {
    data$set_categorical_feature(categorical_feature)
  }
193

194
  valid_contain_train <- FALSE
195
196
  train_data_name <- "train"
  reduced_valid_sets <- list()
197

198
  # Parse validation datasets
199
  if (length(valids) > 0L) {
200

Guolin Ke's avatar
Guolin Ke committed
201
    for (key in names(valids)) {
202

203
      # Use names to get validation datasets
Guolin Ke's avatar
Guolin Ke committed
204
      valid_data <- valids[[key]]
205

206
      # Check for duplicate train/validation dataset
207
      if (identical(data, valid_data)) {
208
        valid_contain_train <- TRUE
209
        train_data_name <- key
Guolin Ke's avatar
Guolin Ke committed
210
211
        next
      }
212

213
      # Update parameters, data
Guolin Ke's avatar
Guolin Ke committed
214
215
216
      valid_data$update_params(params)
      valid_data$set_reference(data)
      reduced_valid_sets[[key]] <- valid_data
217

Guolin Ke's avatar
Guolin Ke committed
218
    }
219

Guolin Ke's avatar
Guolin Ke committed
220
  }
221

222
  # Add printing log callback
223
  if (verbose > 0L && eval_freq > 0L) {
224
    callbacks <- add.cb(cb_list = callbacks, cb = cb.print.evaluation(period = eval_freq))
Guolin Ke's avatar
Guolin Ke committed
225
  }
226

227
  # Add evaluation log callback
228
  if (record && length(valids) > 0L) {
229
    callbacks <- add.cb(cb_list = callbacks, cb = cb.record.evaluation())
Guolin Ke's avatar
Guolin Ke committed
230
  }
231

232
  # Did user pass parameters that indicate they want to use early stopping?
233
  using_early_stopping <- !is.null(early_stopping_rounds) && early_stopping_rounds > 0L
234
235
236
237
238

  boosting_param_names <- .PARAMETER_ALIASES()[["boosting"]]
  using_dart <- any(
    sapply(
      X = boosting_param_names
239
240
      , FUN = function(param) {
        identical(params[[param]], "dart")
241
      }
242
243
244
245
    )
  )

  # Cannot use early stopping with 'dart' boosting
246
  if (using_dart) {
247
    warning("Early stopping is not available in 'dart' mode.")
248
    using_early_stopping <- FALSE
249
250
251

    # Remove the cb.early.stop() function if it was passed in to callbacks
    callbacks <- Filter(
252
      f = function(cb_func) {
253
254
255
256
257
258
259
        !identical(attr(cb_func, "name"), "cb.early.stop")
      }
      , x = callbacks
    )
  }

  # If user supplied early_stopping_rounds, add the early stopping callback
260
  if (using_early_stopping) {
261
    callbacks <- add.cb(
262
263
      cb_list = callbacks
      , cb = cb.early.stop(
264
        stopping_rounds = early_stopping_rounds
265
        , first_metric_only = isTRUE(params[["first_metric_only"]])
266
267
268
        , verbose = verbose
      )
    )
Guolin Ke's avatar
Guolin Ke committed
269
  }
270

271
  cb <- categorize.callbacks(cb_list = callbacks)
272

273
  # Construct booster with datasets
274
  booster <- Booster$new(params = params, train_set = data)
275
  if (valid_contain_train) {
276
    booster$set_train_data_name(name = train_data_name)
277
  }
278

Guolin Ke's avatar
Guolin Ke committed
279
  for (key in names(reduced_valid_sets)) {
280
    booster$add_valid(data = reduced_valid_sets[[key]], name = key)
Guolin Ke's avatar
Guolin Ke committed
281
  }
282

283
284
285
  # Callback env
  env <- CB_ENV$new()
  env$model <- booster
Guolin Ke's avatar
Guolin Ke committed
286
  env$begin_iteration <- begin_iteration
287
  env$end_iteration <- end_iteration
288

289
  # Start training model using number of iterations to start and end with
290
  for (i in seq.int(from = begin_iteration, to = end_iteration)) {
291

292
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
293
294
    env$iteration <- i
    env$eval_list <- list()
295

296
297
298
299
    # Loop through "pre_iter" element
    for (f in cb$pre_iter) {
      f(env)
    }
300

301
    # Update one boosting iteration
302
    booster$update(fobj = fobj)
303

304
    # Prepare collection of evaluation results
Guolin Ke's avatar
Guolin Ke committed
305
    eval_list <- list()
306

307
    # Collection: Has validation dataset?
308
    if (length(valids) > 0L) {
309

310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
      # Get evaluation results with passed-in functions
      for (eval_function in eval_functions) {

        # Validation has training dataset?
        if (valid_contain_train) {
          eval_list <- append(eval_list, booster$eval_train(feval = eval_function))
        }

        eval_list <- append(eval_list, booster$eval_valid(feval = eval_function))
      }

      # Calling booster$eval_valid() will get
      # evaluation results with the metrics in params$metric by calling LGBM_BoosterGetEval_R",
      # so need to be sure that gets called, which it wouldn't be above if no functions
      # were passed in
      if (length(eval_functions) == 0L) {
        if (valid_contain_train) {
          eval_list <- append(eval_list, booster$eval_train(feval = eval_function))
        }
        eval_list <- append(eval_list, booster$eval_valid(feval = eval_function))
Guolin Ke's avatar
Guolin Ke committed
330
      }
331

Guolin Ke's avatar
Guolin Ke committed
332
    }
333

334
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
335
    env$eval_list <- eval_list
336

337
338
339
340
    # Loop through env
    for (f in cb$post_iter) {
      f(env)
    }
341

342
    # Check for early stopping and break if needed
343
    if (env$met_early_stop) break
344

Guolin Ke's avatar
Guolin Ke committed
345
  }
346

347
348
349
350
  # check if any valids were given other than the training data
  non_train_valid_names <- names(valids)[!(names(valids) == train_data_name)]
  first_valid_name <- non_train_valid_names[1L]

351
352
  # When early stopping is not activated, we compute the best iteration / score ourselves by
  # selecting the first metric and the first dataset
353
  if (record && length(non_train_valid_names) > 0L && is.na(env$best_score)) {
354
355
356

    # when using a custom eval function, the metric name is returned from the
    # function, so figure it out from record_evals
357
    if (!is.null(eval_functions[1L])) {
358
359
360
361
362
      first_metric <- names(booster$record_evals[[first_valid_name]])[1L]
    } else {
      first_metric <- booster$.__enclos_env__$private$eval_names[1L]
    }

363
364
365
    .find_best <- which.min
    if (isTRUE(env$eval_list[[1L]]$higher_better[1L])) {
      .find_best <- which.max
366
    }
367
368
369
370
371
372
373
374
    booster$best_iter <- unname(
      .find_best(
        unlist(
          booster$record_evals[[first_valid_name]][[first_metric]][[.EVAL_KEY()]]
        )
      )
    )
    booster$best_score <- booster$record_evals[[first_valid_name]][[first_metric]][[.EVAL_KEY()]][[booster$best_iter]]
375
  }
376

377
378
  # Check for booster model conversion to predictor model
  if (reset_data) {
379

380
    # Store temporarily model data elsewhere
381
382
383
384
385
    booster_old <- list(
      best_iter = booster$best_iter
      , best_score = booster$best_score
      , record_evals = booster$record_evals
    )
386

387
388
389
390
391
    # Reload model
    booster <- lgb.load(model_str = booster$save_model_to_string())
    booster$best_iter <- booster_old$best_iter
    booster$best_score <- booster_old$best_score
    booster$record_evals <- booster_old$record_evals
392

393
  }
394

395
  return(booster)
396

Guolin Ke's avatar
Guolin Ke committed
397
}