lgb.train.R 10.2 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
2
#' @title Main training logic for LightGBM
#' @name lgb.train
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
13
14
#' @param categorical_feature list of str or int
#'        type int represents index,
#'        type str represents feature names
15
16
#' @param callbacks list of callback functions
#'        List of callback functions that are applied at each iteration.
17
#' @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
18
19
20
21
#' @param ... other parameters, see Parameters.rst for more information. A few key parameters:
#'            \itemize{
#'                \item{boosting}{Boosting type. \code{"gbdt"} or \code{"dart"}}
#'                \item{num_leaves}{number of leaves in one tree. defaults to 127}
22
#'                \item{max_depth}{Limit the max depth for tree model. This is used to deal with
James Lamb's avatar
James Lamb committed
23
24
#'                                 overfit when #data is small. Tree still grow by leaf-wise.}
#'                \item{num_threads}{Number of threads for LightGBM. For the best speed, set this to
25
#'                                   the number of real CPU cores, not the number of threads (most
James Lamb's avatar
James Lamb committed
26
27
#'                                   CPU using hyper-threading to generate 2 threads per CPU core).}
#'            }
28
#' @return a trained booster model \code{lgb.Booster}.
29
#'
Guolin Ke's avatar
Guolin Ke committed
30
#' @examples
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#' 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)
#' model <- lgb.train(params,
#'                    dtrain,
#'                    100,
#'                    valids,
#'                    min_data = 1,
#'                    learning_rate = 1,
#'                    early_stopping_rounds = 10)
47
#'
Guolin Ke's avatar
Guolin Ke committed
48
#' @export
49
50
51
52
53
54
55
56
57
58
59
60
lgb.train <- function(params = list(),
                      data,
                      nrounds = 10,
                      valids = list(),
                      obj = NULL,
                      eval = NULL,
                      verbose = 1,
                      record = TRUE,
                      eval_freq = 1L,
                      init_model = NULL,
                      colnames = NULL,
                      categorical_feature = NULL,
61
                      early_stopping_rounds = NULL,
62
                      callbacks = list(),
63
                      reset_data = FALSE,
64
                      ...) {
65
  
66
  # Setup temporary variables
67
  additional_params <- list(...)
68
  params <- append(params, additional_params)
Guolin Ke's avatar
Guolin Ke committed
69
  params$verbose <- verbose
70
71
72
73
  params <- lgb.check.obj(params, obj)
  params <- lgb.check.eval(params, eval)
  fobj <- NULL
  feval <- NULL
74
  
75
76
77
  if (nrounds <= 0) {
    stop("nrounds should be greater than zero")
  }
78
  
79
  # Check for objective (function or not)
80
  if (is.function(params$objective)) {
81
    fobj <- params$objective
Guolin Ke's avatar
Guolin Ke committed
82
83
    params$objective <- "NONE"
  }
84
  
85
86
87
88
  # Check for loss (function or not)
  if (is.function(eval)) {
    feval <- eval
  }
89
  
90
  # Check for parameters
Guolin Ke's avatar
Guolin Ke committed
91
  lgb.check.params(params)
92
  
93
  # Init predictor to empty
Guolin Ke's avatar
Guolin Ke committed
94
  predictor <- NULL
95
  
96
  # Check for boosting from a trained model
97
  if (is.character(init_model)) {
Guolin Ke's avatar
Guolin Ke committed
98
    predictor <- Predictor$new(init_model)
99
  } else if (lgb.is.Booster(init_model)) {
Guolin Ke's avatar
Guolin Ke committed
100
101
    predictor <- init_model$to_predictor()
  }
102
  
103
  # Set the iteration to start from / end to (and check for boosting from a trained model, again)
Guolin Ke's avatar
Guolin Ke committed
104
  begin_iteration <- 1
105
  if (!is.null(predictor)) {
Guolin Ke's avatar
Guolin Ke committed
106
107
    begin_iteration <- predictor$current_iter() + 1
  }
108
  # Check for number of rounds passed as parameter - in case there are multiple ones, take only the first one
109
  n_rounds <- c("num_iterations", "num_iteration", "n_iter", "num_tree", "num_trees", "num_round", "num_rounds", "num_boost_round", "n_estimators")
110
111
  if (any(names(params) %in% n_rounds)) {
    end_iteration <- begin_iteration + params[[which(names(params) %in% n_rounds)[1]]] - 1
112
113
114
  } else {
    end_iteration <- begin_iteration + nrounds - 1
  }
115
116
  
  
117
  # Check for training dataset type correctness
118
  if (!lgb.is.Dataset(data)) {
Guolin Ke's avatar
Guolin Ke committed
119
120
    stop("lgb.train: data only accepts lgb.Dataset object")
  }
121
  
122
  # Check for validation dataset type correctness
Guolin Ke's avatar
Guolin Ke committed
123
  if (length(valids) > 0) {
124
    
125
    # One or more validation dataset
126
    
127
    # Check for list as input and type correctness by object
128
    if (!is.list(valids) || !all(vapply(valids, lgb.is.Dataset, logical(1)))) {
129
130
      stop("lgb.train: valids must be a list of lgb.Dataset elements")
    }
131
    
132
    # Attempt to get names
Guolin Ke's avatar
Guolin Ke committed
133
    evnames <- names(valids)
134
    
135
    # Check for names existance
136
137
138
    if (is.null(evnames) || !all(nzchar(evnames))) {
      stop("lgb.train: each element of the valids must have a name tag")
    }
Guolin Ke's avatar
Guolin Ke committed
139
  }
140
  
141
  # Update parameters with parsed parameters
Guolin Ke's avatar
Guolin Ke committed
142
  data$update_params(params)
143
  
144
  # Create the predictor set
Guolin Ke's avatar
Guolin Ke committed
145
  data$.__enclos_env__$private$set_predictor(predictor)
146
  
147
148
149
150
  # Write column names
  if (!is.null(colnames)) {
    data$set_colnames(colnames)
  }
151
  
152
153
154
155
  # Write categorical features
  if (!is.null(categorical_feature)) {
    data$set_categorical_feature(categorical_feature)
  }
156
  
157
  # Construct datasets, if needed
158
  data$construct()
Guolin Ke's avatar
Guolin Ke committed
159
  vaild_contain_train <- FALSE
160
161
  train_data_name <- "train"
  reduced_valid_sets <- list()
162
  
163
  # Parse validation datasets
164
  if (length(valids) > 0) {
165
    
166
    # Loop through all validation datasets using name
Guolin Ke's avatar
Guolin Ke committed
167
    for (key in names(valids)) {
168
      
169
      # Use names to get validation datasets
Guolin Ke's avatar
Guolin Ke committed
170
      valid_data <- valids[[key]]
171
      
172
      # Check for duplicate train/validation dataset
173
      if (identical(data, valid_data)) {
Guolin Ke's avatar
Guolin Ke committed
174
        vaild_contain_train <- TRUE
175
        train_data_name <- key
Guolin Ke's avatar
Guolin Ke committed
176
177
        next
      }
178
      
179
      # Update parameters, data
Guolin Ke's avatar
Guolin Ke committed
180
181
182
      valid_data$update_params(params)
      valid_data$set_reference(data)
      reduced_valid_sets[[key]] <- valid_data
183
      
Guolin Ke's avatar
Guolin Ke committed
184
    }
185
    
Guolin Ke's avatar
Guolin Ke committed
186
  }
187
  
188
  # Add printing log callback
189
  if (verbose > 0 && eval_freq > 0) {
Guolin Ke's avatar
Guolin Ke committed
190
191
    callbacks <- add.cb(callbacks, cb.print.evaluation(eval_freq))
  }
192
  
193
  # Add evaluation log callback
194
  if (record && length(valids) > 0) {
Guolin Ke's avatar
Guolin Ke committed
195
196
    callbacks <- add.cb(callbacks, cb.record.evaluation())
  }
197
  
198
  # Check for early stopping passed as parameter when adding early stopping callback
199
200
201
202
  early_stop <- c("early_stopping_round", "early_stopping_rounds", "early_stopping")
  if (any(names(params) %in% early_stop)) {
    if (params[[which(names(params) %in% early_stop)[1]]] > 0) {
      callbacks <- add.cb(callbacks, cb.early.stop(params[[which(names(params) %in% early_stop)[1]]], verbose = verbose))
203
204
205
206
207
208
    }
  } else {
    if (!is.null(early_stopping_rounds)) {
      if (early_stopping_rounds > 0) {
        callbacks <- add.cb(callbacks, cb.early.stop(early_stopping_rounds, verbose = verbose))
      }
Guolin Ke's avatar
Guolin Ke committed
209
210
    }
  }
211
  
212
  # "Categorize" callbacks
Guolin Ke's avatar
Guolin Ke committed
213
  cb <- categorize.callbacks(callbacks)
214
  
215
  # Construct booster with datasets
216
217
  booster <- Booster$new(params = params, train_set = data)
  if (vaild_contain_train) { booster$set_train_data_name(train_data_name) }
Guolin Ke's avatar
Guolin Ke committed
218
219
220
  for (key in names(reduced_valid_sets)) {
    booster$add_valid(reduced_valid_sets[[key]], key)
  }
221
  
222
223
224
  # Callback env
  env <- CB_ENV$new()
  env$model <- booster
Guolin Ke's avatar
Guolin Ke committed
225
  env$begin_iteration <- begin_iteration
226
  env$end_iteration <- end_iteration
227
  
228
  # Start training model using number of iterations to start and end with
229
  for (i in seq.int(from = begin_iteration, to = end_iteration)) {
230
    
231
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
232
233
    env$iteration <- i
    env$eval_list <- list()
234
    
235
236
237
238
    # Loop through "pre_iter" element
    for (f in cb$pre_iter) {
      f(env)
    }
239
    
240
    # Update one boosting iteration
241
    booster$update(fobj = fobj)
242
    
243
    # Prepare collection of evaluation results
Guolin Ke's avatar
Guolin Ke committed
244
    eval_list <- list()
245
    
246
    # Collection: Has validation dataset?
247
    if (length(valids) > 0) {
248
      
249
      # Validation has training dataset?
250
251
      if (vaild_contain_train) {
        eval_list <- append(eval_list, booster$eval_train(feval = feval))
Guolin Ke's avatar
Guolin Ke committed
252
      }
253
      
254
      # Has no validation dataset
255
      eval_list <- append(eval_list, booster$eval_valid(feval = feval))
Guolin Ke's avatar
Guolin Ke committed
256
    }
257
    
258
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
259
    env$eval_list <- eval_list
260
    
261
262
263
264
    # Loop through env
    for (f in cb$post_iter) {
      f(env)
    }
265
    
266
    # Check for early stopping and break if needed
267
    if (env$met_early_stop) break
268
    
Guolin Ke's avatar
Guolin Ke committed
269
  }
270
271
272
273
274
275
276
277
278
279
280
281
  
  # When early stopping is not activated, we compute the best iteration / score ourselves by selecting the first metric and the first dataset
  if (record && length(valids) > 0 && is.na(env$best_score)) {
    if (env$eval_list[[1]]$higher_better[1] == TRUE) {
      booster$best_iter <- unname(which.max(unlist(booster$record_evals[[2]][[1]][[1]])))
      booster$best_score <- booster$record_evals[[2]][[1]][[1]][[booster$best_iter]]
    } else {
      booster$best_iter <- unname(which.min(unlist(booster$record_evals[[2]][[1]][[1]])))
      booster$best_score <- booster$record_evals[[2]][[1]][[1]][[booster$best_iter]]
    }
  }
  
282
283
  # Check for booster model conversion to predictor model
  if (reset_data) {
284
    
285
286
287
288
    # Store temporarily model data elsewhere
    booster_old <- list(best_iter = booster$best_iter,
                        best_score = booster$best_score,
                        record_evals = booster$record_evals)
289
    
290
291
292
293
294
    # 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
295
    
296
  }
297
  
298
299
  # Return booster
  return(booster)
300
  
Guolin Ke's avatar
Guolin Ke committed
301
}