lgb.train.R 10.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 obj objective function, can be character or custom objective function. Examples include
7
8
#'            \code{regression}, \code{regression_l1}, \code{huber},
#'            \code{binary}, \code{lambdarank}, \code{multiclass}, \code{multiclass}
9
#' @param eval evaluation function, can be (a list of) character or custom eval function
10
#' @param record Boolean, TRUE will record iteration message to \code{booster$record_evals}
Guolin Ke's avatar
Guolin Ke committed
11
#' @param colnames feature names, if not null, will use this to overwrite the names in dataset
12
#' @param categorical_feature list of str or int
13
14
15
16
17
18
#'                            type int represents index,
#'                            type str represents feature names
#' @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
James Lamb's avatar
James Lamb committed
19
20
#' @param ... other parameters, see Parameters.rst for more information. A few key parameters:
#'            \itemize{
21
22
23
#'                \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
James Lamb's avatar
James Lamb committed
24
#'                                 overfit when #data is small. Tree still grow by leaf-wise.}
25
#'                \item{\code{num_threads}: Number of threads for LightGBM. For the best speed, set this to
26
#'                                   the number of real CPU cores, not the number of threads (most
James Lamb's avatar
James Lamb committed
27
28
#'                                   CPU using hyper-threading to generate 2 threads per CPU core).}
#'            }
29
#' @return a trained booster model \code{lgb.Booster}.
30
#'
Guolin Ke's avatar
Guolin Ke committed
31
#' @examples
32
33
34
35
36
37
38
39
40
#' library(lightgbm)
#' 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 = 10L
45
#'   , valids = valids
46
47
48
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
49
#' )
Guolin Ke's avatar
Guolin Ke committed
50
#' @export
51
52
lgb.train <- function(params = list(),
                      data,
53
                      nrounds = 10L,
54
55
56
                      valids = list(),
                      obj = NULL,
                      eval = NULL,
57
                      verbose = 1L,
58
59
60
61
62
                      record = TRUE,
                      eval_freq = 1L,
                      init_model = NULL,
                      colnames = NULL,
                      categorical_feature = NULL,
63
                      early_stopping_rounds = NULL,
64
                      callbacks = list(),
65
                      reset_data = FALSE,
66
                      ...) {
67

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

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

94
  # Check for objective (function or not)
95
  if (is.function(params$objective)) {
96
    fobj <- params$objective
Guolin Ke's avatar
Guolin Ke committed
97
98
    params$objective <- "NONE"
  }
99

100
101
102
103
  # Check for loss (function or not)
  if (is.function(eval)) {
    feval <- eval
  }
104

105
  # Init predictor to empty
Guolin Ke's avatar
Guolin Ke committed
106
  predictor <- NULL
107

108
  # Check for boosting from a trained model
109
  if (is.character(init_model)) {
Guolin Ke's avatar
Guolin Ke committed
110
    predictor <- Predictor$new(init_model)
111
  } else if (lgb.is.Booster(init_model)) {
Guolin Ke's avatar
Guolin Ke committed
112
113
    predictor <- init_model$to_predictor()
  }
114

115
  # Set the iteration to start from / end to (and check for boosting from a trained model, again)
116
  begin_iteration <- 1L
117
  if (!is.null(predictor)) {
118
    begin_iteration <- predictor$current_iter() + 1L
Guolin Ke's avatar
Guolin Ke committed
119
  }
120
  # Check for number of rounds passed as parameter - in case there are multiple ones, take only the first one
121
122
  n_trees <- .PARAMETER_ALIASES()[["num_iterations"]]
  if (any(names(params) %in% n_trees)) {
123
    end_iteration <- begin_iteration + params[[which(names(params) %in% n_trees)[1L]]] - 1L
124
  } else {
125
    end_iteration <- begin_iteration + nrounds - 1L
126
  }
127

128
  # Update parameters with parsed parameters
Guolin Ke's avatar
Guolin Ke committed
129
  data$update_params(params)
130

131
  # Create the predictor set
Guolin Ke's avatar
Guolin Ke committed
132
  data$.__enclos_env__$private$set_predictor(predictor)
133

134
135
136
137
  # Write column names
  if (!is.null(colnames)) {
    data$set_colnames(colnames)
  }
138

139
140
141
142
  # Write categorical features
  if (!is.null(categorical_feature)) {
    data$set_categorical_feature(categorical_feature)
  }
143

144
  # Construct datasets, if needed
145
  data$construct()
146
  valid_contain_train <- FALSE
147
148
  train_data_name <- "train"
  reduced_valid_sets <- list()
149

150
  # Parse validation datasets
151
  if (length(valids) > 0L) {
152

153
    # Loop through all validation datasets using name
Guolin Ke's avatar
Guolin Ke committed
154
    for (key in names(valids)) {
155

156
      # Use names to get validation datasets
Guolin Ke's avatar
Guolin Ke committed
157
      valid_data <- valids[[key]]
158

159
      # Check for duplicate train/validation dataset
160
      if (identical(data, valid_data)) {
161
        valid_contain_train <- TRUE
162
        train_data_name <- key
Guolin Ke's avatar
Guolin Ke committed
163
164
        next
      }
165

166
      # Update parameters, data
Guolin Ke's avatar
Guolin Ke committed
167
168
169
      valid_data$update_params(params)
      valid_data$set_reference(data)
      reduced_valid_sets[[key]] <- valid_data
170

Guolin Ke's avatar
Guolin Ke committed
171
    }
172

Guolin Ke's avatar
Guolin Ke committed
173
  }
174

175
  # Add printing log callback
176
  if (verbose > 0L && eval_freq > 0L) {
Guolin Ke's avatar
Guolin Ke committed
177
178
    callbacks <- add.cb(callbacks, cb.print.evaluation(eval_freq))
  }
179

180
  # Add evaluation log callback
181
  if (record && length(valids) > 0L) {
Guolin Ke's avatar
Guolin Ke committed
182
183
    callbacks <- add.cb(callbacks, cb.record.evaluation())
  }
184

185
186
187
188
189
  # If early stopping was passed as a parameter in params(), prefer that to keyword argument
  # early_stopping_rounds by overwriting the value in 'early_stopping_rounds'
  early_stop <- .PARAMETER_ALIASES()[["early_stopping_round"]]
  early_stop_param_indx <- names(params) %in% early_stop
  if (any(early_stop_param_indx)) {
190
    first_early_stop_param <- which(early_stop_param_indx)[[1L]]
191
192
193
194
195
196
197
198
199
200
201
    first_early_stop_param_name <- names(params)[[first_early_stop_param]]
    early_stopping_rounds <- params[[first_early_stop_param_name]]
  }

  # Did user pass parameters that indicate they want to use early stopping?
  using_early_stopping_via_args <- !is.null(early_stopping_rounds)

  boosting_param_names <- .PARAMETER_ALIASES()[["boosting"]]
  using_dart <- any(
    sapply(
      X = boosting_param_names
202
203
      , FUN = function(param) {
        identical(params[[param]], "dart")
204
      }
205
206
207
208
    )
  )

  # Cannot use early stopping with 'dart' boosting
209
  if (using_dart) {
210
211
212
213
214
    warning("Early stopping is not available in 'dart' mode.")
    using_early_stopping_via_args <- FALSE

    # Remove the cb.early.stop() function if it was passed in to callbacks
    callbacks <- Filter(
215
      f = function(cb_func) {
216
217
218
219
220
221
222
        !identical(attr(cb_func, "name"), "cb.early.stop")
      }
      , x = callbacks
    )
  }

  # If user supplied early_stopping_rounds, add the early stopping callback
223
  if (using_early_stopping_via_args) {
224
225
226
227
228
229
230
    callbacks <- add.cb(
      callbacks
      , cb.early.stop(
        stopping_rounds = early_stopping_rounds
        , verbose = verbose
      )
    )
Guolin Ke's avatar
Guolin Ke committed
231
  }
232

233
  # "Categorize" callbacks
Guolin Ke's avatar
Guolin Ke committed
234
  cb <- categorize.callbacks(callbacks)
235

236
  # Construct booster with datasets
237
  booster <- Booster$new(params = params, train_set = data)
238
239
240
  if (valid_contain_train) {
    booster$set_train_data_name(train_data_name)
  }
Guolin Ke's avatar
Guolin Ke committed
241
242
243
  for (key in names(reduced_valid_sets)) {
    booster$add_valid(reduced_valid_sets[[key]], key)
  }
244

245
246
247
  # Callback env
  env <- CB_ENV$new()
  env$model <- booster
Guolin Ke's avatar
Guolin Ke committed
248
  env$begin_iteration <- begin_iteration
249
  env$end_iteration <- end_iteration
250

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

254
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
255
256
    env$iteration <- i
    env$eval_list <- list()
257

258
259
260
261
    # Loop through "pre_iter" element
    for (f in cb$pre_iter) {
      f(env)
    }
262

263
    # Update one boosting iteration
264
    booster$update(fobj = fobj)
265

266
    # Prepare collection of evaluation results
Guolin Ke's avatar
Guolin Ke committed
267
    eval_list <- list()
268

269
    # Collection: Has validation dataset?
270
    if (length(valids) > 0L) {
271

272
      # Validation has training dataset?
273
      if (valid_contain_train) {
274
        eval_list <- append(eval_list, booster$eval_train(feval = feval))
Guolin Ke's avatar
Guolin Ke committed
275
      }
276

277
      # Has no validation dataset
278
      eval_list <- append(eval_list, booster$eval_valid(feval = feval))
Guolin Ke's avatar
Guolin Ke committed
279
    }
280

281
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
282
    env$eval_list <- eval_list
283

284
285
286
287
    # Loop through env
    for (f in cb$post_iter) {
      f(env)
    }
288

289
    # Check for early stopping and break if needed
290
    if (env$met_early_stop) break
291

Guolin Ke's avatar
Guolin Ke committed
292
  }
293

294
295
  # When early stopping is not activated, we compute the best iteration / score ourselves by
  # selecting the first metric and the first dataset
296
297
298
299
  if (record && length(valids) > 0L && is.na(env$best_score)) {
    if (env$eval_list[[1L]]$higher_better[1L] == TRUE) {
      booster$best_iter <- unname(which.max(unlist(booster$record_evals[[2L]][[1L]][[1L]])))
      booster$best_score <- booster$record_evals[[2L]][[1L]][[1L]][[booster$best_iter]]
300
    } else {
301
302
      booster$best_iter <- unname(which.min(unlist(booster$record_evals[[2L]][[1L]][[1L]])))
      booster$best_score <- booster$record_evals[[2L]][[1L]][[1L]][[booster$best_iter]]
303
304
    }
  }
305

306
307
  # Check for booster model conversion to predictor model
  if (reset_data) {
308

309
    # Store temporarily model data elsewhere
310
311
312
313
314
    booster_old <- list(
      best_iter = booster$best_iter
      , best_score = booster$best_score
      , record_evals = booster$record_evals
    )
315

316
317
318
319
320
    # 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
321

322
  }
323

324
325
  # Return booster
  return(booster)
326

Guolin Ke's avatar
Guolin Ke committed
327
}