lgb.train.R 12.3 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
#' @name lgb.train
2
#' @title Main training logic for LightGBM
3
4
5
#' @description Low-level R interface to train a LightGBM model. Unlike \code{\link{lightgbm}},
#'              this function is focused on performance (e.g. speed, memory efficiency). It is also
#'              less likely to have breaking API changes in new releases than \code{\link{lightgbm}}.
James Lamb's avatar
James Lamb committed
6
#' @inheritParams lgb_shared_params
7
#' @param valids a list of \code{lgb.Dataset} objects, used for validation
8
#' @param record Boolean, TRUE will record iteration message to \code{booster$record_evals}
Guolin Ke's avatar
Guolin Ke committed
9
#' @param colnames feature names, if not null, will use this to overwrite the names in dataset
10
11
12
#' @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").
13
14
15
16
#' @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
17
#' @inheritSection lgb_shared_params Early Stopping
18
#' @return a trained booster model \code{lgb.Booster}.
19
#'
Guolin Ke's avatar
Guolin Ke committed
20
#' @examples
21
#' \donttest{
22
23
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
24
25
26
27
28
29
#' 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)
30
31
32
33
34
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
35
#'   , num_threads = 2L
36
#' )
37
#' valids <- list(test = dtest)
38
39
40
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
41
#'   , nrounds = 5L
42
#'   , valids = valids
43
#'   , early_stopping_rounds = 3L
44
#' )
45
#' }
Guolin Ke's avatar
Guolin Ke committed
46
#' @export
47
48
lgb.train <- function(params = list(),
                      data,
49
                      nrounds = 100L,
50
51
52
                      valids = list(),
                      obj = NULL,
                      eval = NULL,
53
                      verbose = 1L,
54
55
56
57
58
                      record = TRUE,
                      eval_freq = 1L,
                      init_model = NULL,
                      colnames = NULL,
                      categorical_feature = NULL,
59
                      early_stopping_rounds = NULL,
60
                      callbacks = list(),
61
                      reset_data = FALSE,
62
                      serializable = TRUE) {
63

64
65
66
67
  # validate inputs early to avoid unnecessary computation
  if (nrounds <= 0L) {
    stop("nrounds should be greater than zero")
  }
68
  if (!.is_Dataset(x = data)) {
69
70
71
    stop("lgb.train: data must be an lgb.Dataset instance")
  }
  if (length(valids) > 0L) {
72
    if (!identical(class(valids), "list") || !all(vapply(valids, .is_Dataset, logical(1L)))) {
73
74
75
76
77
78
79
80
      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")
    }
  }

81
82
83
84
  # 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
85
  params <- .check_wrapper_param(
86
87
88
89
    main_param_name = "verbosity"
    , params = params
    , alternative_kwarg_value = verbose
  )
90
  params <- .check_wrapper_param(
91
92
93
94
    main_param_name = "num_iterations"
    , params = params
    , alternative_kwarg_value = nrounds
  )
95
  params <- .check_wrapper_param(
96
97
98
99
    main_param_name = "metric"
    , params = params
    , alternative_kwarg_value = NULL
  )
100
  params <- .check_wrapper_param(
101
102
    main_param_name = "objective"
    , params = params
103
    , alternative_kwarg_value = obj
104
  )
105
  params <- .check_wrapper_param(
106
107
108
109
110
111
    main_param_name = "early_stopping_round"
    , params = params
    , alternative_kwarg_value = early_stopping_rounds
  )
  early_stopping_rounds <- params[["early_stopping_round"]]

112
113
  # extract any function objects passed for objective or metric
  fobj <- NULL
114
  if (is.function(params$objective)) {
115
    fobj <- params$objective
116
    params$objective <- "none"
Guolin Ke's avatar
Guolin Ke committed
117
  }
118

119
  # If eval is a single function, store it as a 1-element list
120
  # (for backwards compatibility). If it is a list of functions, store
121
122
  # all of them. This makes it possible to pass any mix of strings like "auc"
  # and custom functions to eval
123
  params <- .check_eval(params = params, eval = eval)
124
  eval_functions <- list(NULL)
125
  if (is.function(eval)) {
126
127
128
129
130
131
132
    eval_functions <- list(eval)
  }
  if (methods::is(eval, "list")) {
    eval_functions <- Filter(
      f = is.function
      , x = eval
    )
133
  }
134

135
  # Init predictor to empty
Guolin Ke's avatar
Guolin Ke committed
136
  predictor <- NULL
137

138
  # Check for boosting from a trained model
139
  if (is.character(init_model)) {
140
    predictor <- Predictor$new(modelfile = init_model)
141
  } else if (.is_Booster(x = init_model)) {
Guolin Ke's avatar
Guolin Ke committed
142
143
    predictor <- init_model$to_predictor()
  }
144

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

152
153
154
155
156
  # 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

157
158
  # Construct datasets, if needed
  data$update_params(params = params)
159
160
161
  if (!is.null(categorical_feature)) {
    data$set_categorical_feature(categorical_feature)
  }
162
163
  data$construct()

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

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

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

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

187
  valid_contain_train <- FALSE
188
189
  train_data_name <- "train"
  reduced_valid_sets <- list()
190

191
  # Parse validation datasets
192
  if (length(valids) > 0L) {
193

Guolin Ke's avatar
Guolin Ke committed
194
    for (key in names(valids)) {
195

196
      # Use names to get validation datasets
Guolin Ke's avatar
Guolin Ke committed
197
      valid_data <- valids[[key]]
198

199
      # Check for duplicate train/validation dataset
200
      if (identical(data, valid_data)) {
201
        valid_contain_train <- TRUE
202
        train_data_name <- key
Guolin Ke's avatar
Guolin Ke committed
203
204
        next
      }
205

206
      # Update parameters, data
Guolin Ke's avatar
Guolin Ke committed
207
208
209
      valid_data$update_params(params)
      valid_data$set_reference(data)
      reduced_valid_sets[[key]] <- valid_data
210

Guolin Ke's avatar
Guolin Ke committed
211
    }
212

Guolin Ke's avatar
Guolin Ke committed
213
  }
214

215
  # Add printing log callback
216
  if (params[["verbosity"]] > 0L && eval_freq > 0L) {
217
218
219
220
    callbacks <- .add_cb(
        cb_list = callbacks
        , cb = cb_print_evaluation(period = eval_freq)
    )
Guolin Ke's avatar
Guolin Ke committed
221
  }
222

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

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

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

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

249
    # Remove the cb_early_stop() function if it was passed in to callbacks
250
    callbacks <- Filter(
251
      f = function(cb_func) {
252
        !identical(attr(cb_func, "name"), "cb_early_stop")
253
254
255
256
257
258
      }
      , x = callbacks
    )
  }

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

270
  cb <- .categorize_callbacks(cb_list = callbacks)
271

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

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

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

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

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

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

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

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

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

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
      # 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
329
      }
330

Guolin Ke's avatar
Guolin Ke committed
331
    }
332

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

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

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

Guolin Ke's avatar
Guolin Ke committed
344
  }
345

346
347
348
349
  # 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]

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

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

362
363
364
    .find_best <- which.min
    if (isTRUE(env$eval_list[[1L]]$higher_better[1L])) {
      .find_best <- which.max
365
    }
366
367
368
369
370
371
372
373
    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]]
374
  }
375

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

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

386
387
388
389
390
    # 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
391

392
  }
393

394
395
396
397
  if (serializable) {
    booster$save_raw()
  }

398
  return(booster)
399

Guolin Ke's avatar
Guolin Ke committed
400
}