lgb.train.R 11.7 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
#' @inheritSection lgb_shared_params Early Stopping
16
#' @return a trained booster model \code{lgb.Booster}.
17
#'
Guolin Ke's avatar
Guolin Ke committed
18
#' @examples
19
#' \donttest{
20
21
22
23
24
25
#' 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)
26
27
28
29
30
31
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
#' )
32
#' valids <- list(test = dtest)
33
34
35
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
36
#'   , nrounds = 5L
37
#'   , valids = valids
38
#'   , early_stopping_rounds = 3L
39
#' )
40
#' }
Guolin Ke's avatar
Guolin Ke committed
41
#' @export
42
43
lgb.train <- function(params = list(),
                      data,
44
                      nrounds = 100L,
45
46
47
                      valids = list(),
                      obj = NULL,
                      eval = NULL,
48
                      verbose = 1L,
49
50
51
52
53
                      record = TRUE,
                      eval_freq = 1L,
                      init_model = NULL,
                      colnames = NULL,
                      categorical_feature = NULL,
54
                      early_stopping_rounds = NULL,
55
                      callbacks = list(),
56
                      reset_data = FALSE,
57
                      serializable = TRUE) {
58

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

76
  # Setup temporary variables
77
78
  params <- lgb.check.obj(params = params, obj = obj)
  params <- lgb.check.eval(params = params, eval = eval)
79
  fobj <- NULL
80
  eval_functions <- list(NULL)
81

82
83
84
85
  # 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
86
87
88
89
90
  params <- lgb.check.wrapper_param(
    main_param_name = "verbosity"
    , params = params
    , alternative_kwarg_value = verbose
  )
91
92
93
94
95
96
97
98
99
100
101
102
  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"]]

103
  # Check for objective (function or not)
104
  if (is.function(params$objective)) {
105
    fobj <- params$objective
Guolin Ke's avatar
Guolin Ke committed
106
107
    params$objective <- "NONE"
  }
108

109
  # If eval is a single function, store it as a 1-element list
110
  # (for backwards compatibility). If it is a list of functions, store
111
112
  # all of them. This makes it possible to pass any mix of strings like "auc"
  # and custom functions to eval
113
  if (is.function(eval)) {
114
115
116
117
118
119
120
    eval_functions <- list(eval)
  }
  if (methods::is(eval, "list")) {
    eval_functions <- Filter(
      f = is.function
      , x = eval
    )
121
  }
122

123
  # Init predictor to empty
Guolin Ke's avatar
Guolin Ke committed
124
  predictor <- NULL
125

126
  # Check for boosting from a trained model
127
  if (is.character(init_model)) {
128
    predictor <- Predictor$new(modelfile = init_model)
129
  } else if (lgb.is.Booster(x = init_model)) {
Guolin Ke's avatar
Guolin Ke committed
130
131
    predictor <- init_model$to_predictor()
  }
132

133
  # Set the iteration to start from / end to (and check for boosting from a trained model, again)
134
  begin_iteration <- 1L
135
  if (!is.null(predictor)) {
136
    begin_iteration <- predictor$current_iter() + 1L
Guolin Ke's avatar
Guolin Ke committed
137
  }
138
  end_iteration <- begin_iteration + params[["num_iterations"]] - 1L
139

140
141
142
143
144
  # 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

145
146
147
148
  # Construct datasets, if needed
  data$update_params(params = params)
  data$construct()

149
150
151
152
153
154
  # Check interaction constraints
  cnames <- NULL
  if (!is.null(colnames)) {
    cnames <- colnames
  } else if (!is.null(data$get_colnames())) {
    cnames <- data$get_colnames()
155
  }
156
  params[["interaction_constraints"]] <- lgb.check_interaction_constraints(
157
    interaction_constraints = interaction_constraints
158
159
    , column_names = cnames
  )
160

161
  # Update parameters with parsed parameters
Guolin Ke's avatar
Guolin Ke committed
162
  data$update_params(params)
163

164
  # Create the predictor set
Guolin Ke's avatar
Guolin Ke committed
165
  data$.__enclos_env__$private$set_predictor(predictor)
166

167
168
169
170
  # Write column names
  if (!is.null(colnames)) {
    data$set_colnames(colnames)
  }
171

172
173
174
175
  # Write categorical features
  if (!is.null(categorical_feature)) {
    data$set_categorical_feature(categorical_feature)
  }
176

177
  valid_contain_train <- FALSE
178
179
  train_data_name <- "train"
  reduced_valid_sets <- list()
180

181
  # Parse validation datasets
182
  if (length(valids) > 0L) {
183

Guolin Ke's avatar
Guolin Ke committed
184
    for (key in names(valids)) {
185

186
      # Use names to get validation datasets
Guolin Ke's avatar
Guolin Ke committed
187
      valid_data <- valids[[key]]
188

189
      # Check for duplicate train/validation dataset
190
      if (identical(data, valid_data)) {
191
        valid_contain_train <- TRUE
192
        train_data_name <- key
Guolin Ke's avatar
Guolin Ke committed
193
194
        next
      }
195

196
      # Update parameters, data
Guolin Ke's avatar
Guolin Ke committed
197
198
199
      valid_data$update_params(params)
      valid_data$set_reference(data)
      reduced_valid_sets[[key]] <- valid_data
200

Guolin Ke's avatar
Guolin Ke committed
201
    }
202

Guolin Ke's avatar
Guolin Ke committed
203
  }
204

205
  # Add printing log callback
206
  if (verbose > 0L && eval_freq > 0L) {
207
    callbacks <- add.cb(cb_list = callbacks, cb = cb.print.evaluation(period = eval_freq))
Guolin Ke's avatar
Guolin Ke committed
208
  }
209

210
  # Add evaluation log callback
211
  if (record && length(valids) > 0L) {
212
    callbacks <- add.cb(cb_list = callbacks, cb = cb.record.evaluation())
Guolin Ke's avatar
Guolin Ke committed
213
  }
214

215
  # Did user pass parameters that indicate they want to use early stopping?
216
  using_early_stopping <- !is.null(early_stopping_rounds) && early_stopping_rounds > 0L
217
218
219
220
221

  boosting_param_names <- .PARAMETER_ALIASES()[["boosting"]]
  using_dart <- any(
    sapply(
      X = boosting_param_names
222
223
      , FUN = function(param) {
        identical(params[[param]], "dart")
224
      }
225
226
227
228
    )
  )

  # Cannot use early stopping with 'dart' boosting
229
  if (using_dart) {
230
    warning("Early stopping is not available in 'dart' mode.")
231
    using_early_stopping <- FALSE
232
233
234

    # Remove the cb.early.stop() function if it was passed in to callbacks
    callbacks <- Filter(
235
      f = function(cb_func) {
236
237
238
239
240
241
242
        !identical(attr(cb_func, "name"), "cb.early.stop")
      }
      , x = callbacks
    )
  }

  # If user supplied early_stopping_rounds, add the early stopping callback
243
  if (using_early_stopping) {
244
    callbacks <- add.cb(
245
246
      cb_list = callbacks
      , cb = cb.early.stop(
247
        stopping_rounds = early_stopping_rounds
248
        , first_metric_only = isTRUE(params[["first_metric_only"]])
249
250
251
        , verbose = verbose
      )
    )
Guolin Ke's avatar
Guolin Ke committed
252
  }
253

254
  cb <- categorize.callbacks(cb_list = callbacks)
255

256
  # Construct booster with datasets
257
  booster <- Booster$new(params = params, train_set = data)
258
  if (valid_contain_train) {
259
    booster$set_train_data_name(name = train_data_name)
260
  }
261

Guolin Ke's avatar
Guolin Ke committed
262
  for (key in names(reduced_valid_sets)) {
263
    booster$add_valid(data = reduced_valid_sets[[key]], name = key)
Guolin Ke's avatar
Guolin Ke committed
264
  }
265

266
267
268
  # Callback env
  env <- CB_ENV$new()
  env$model <- booster
Guolin Ke's avatar
Guolin Ke committed
269
  env$begin_iteration <- begin_iteration
270
  env$end_iteration <- end_iteration
271

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

275
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
276
277
    env$iteration <- i
    env$eval_list <- list()
278

279
280
281
282
    # Loop through "pre_iter" element
    for (f in cb$pre_iter) {
      f(env)
    }
283

284
    # Update one boosting iteration
285
    booster$update(fobj = fobj)
286

287
    # Prepare collection of evaluation results
Guolin Ke's avatar
Guolin Ke committed
288
    eval_list <- list()
289

290
    # Collection: Has validation dataset?
291
    if (length(valids) > 0L) {
292

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
      # 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
313
      }
314

Guolin Ke's avatar
Guolin Ke committed
315
    }
316

317
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
318
    env$eval_list <- eval_list
319

320
321
322
323
    # Loop through env
    for (f in cb$post_iter) {
      f(env)
    }
324

325
    # Check for early stopping and break if needed
326
    if (env$met_early_stop) break
327

Guolin Ke's avatar
Guolin Ke committed
328
  }
329

330
331
332
333
  # 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]

334
335
  # When early stopping is not activated, we compute the best iteration / score ourselves by
  # selecting the first metric and the first dataset
336
  if (record && length(non_train_valid_names) > 0L && is.na(env$best_score)) {
337
338
339

    # when using a custom eval function, the metric name is returned from the
    # function, so figure it out from record_evals
340
    if (!is.null(eval_functions[1L])) {
341
342
343
344
345
      first_metric <- names(booster$record_evals[[first_valid_name]])[1L]
    } else {
      first_metric <- booster$.__enclos_env__$private$eval_names[1L]
    }

346
347
348
    .find_best <- which.min
    if (isTRUE(env$eval_list[[1L]]$higher_better[1L])) {
      .find_best <- which.max
349
    }
350
351
352
353
354
355
356
357
    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]]
358
  }
359

360
361
  # Check for booster model conversion to predictor model
  if (reset_data) {
362

363
    # Store temporarily model data elsewhere
364
365
366
367
368
    booster_old <- list(
      best_iter = booster$best_iter
      , best_score = booster$best_score
      , record_evals = booster$record_evals
    )
369

370
371
372
373
374
    # 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
375

376
  }
377

378
379
380
381
  if (serializable) {
    booster$save_raw()
  }

382
  return(booster)
383

Guolin Ke's avatar
Guolin Ke committed
384
}