lgb.train.R 9.16 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
#' Main training logic for LightGBM
2
#' 
Guolin Ke's avatar
Guolin Ke committed
3
4
5
#' @param params List of parameters
#' @param data a \code{lgb.Dataset} object, used for training
#' @param nrounds number of training rounds
6
#' @param valids a list of \code{lgb.Dataset} objects, used for validation
7
8
9
10
11
12
13
14
#' @param obj objective function, can be character or custom objective function. Examples include 
#'        \code{regression}, \code{regression_l1}, \code{huber},
#'        \code{binary}, \code{lambdarank}, \code{multiclass}, \code{multiclass}
#' @param boosting boosting type. \code{gbdt}, \code{dart}
#' @param num_leaves number of leaves in one tree. defaults to 127
#' @param max_depth Limit the max depth for tree model. This is used to deal with overfit when #data is small. 
#'        Tree still grow by leaf-wise.
#' @param num_threads Number of threads for LightGBM. For the best speed, set this to the number of real CPU cores, not the number of threads (most CPU using hyper-threading to generate 2 threads per CPU core).
15
#' @param eval evaluation function, can be (a list of) character or custom eval function
16
17
18
#' @param verbose verbosity for output, if <= 0, also will disable the print of evalutaion during training
#' @param record Boolean, TRUE will record iteration message to \code{booster$record_evals} 
#' @param eval_freq evalutaion output frequency, only effect when verbose > 0
19
#' @param init_model path of model file of \code{lgb.Booster} object, will continue training from this model
Guolin Ke's avatar
Guolin Ke committed
20
#' @param colnames feature names, if not null, will use this to overwrite the names in dataset
21
22
23
#' @param categorical_feature list of str or int
#'        type int represents index,
#'        type str represents feature names
Guolin Ke's avatar
Guolin Ke committed
24
25
26
27
28
29
#' @param early_stopping_rounds int
#'        Activates early stopping.
#'        Requires at least one validation data and one metric
#'        If there's more than one, will check all of them
#'        Returns the model with (best_iter + early_stopping_rounds)
#'        If early stopping occurs, the model will have 'best_iter' field
30
#' @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
Guolin Ke's avatar
Guolin Ke committed
31
32
33
#' @param callbacks list of callback functions
#'        List of callback functions that are applied at each iteration.
#' @param ... other parameters, see parameters.md for more informations
34
#' 
35
#' @return a trained booster model \code{lgb.Booster}.
36
#' 
Guolin Ke's avatar
Guolin Ke committed
37
#' @examples
38
#' \dontrun{
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#' 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)
55
#' }
56
#' 
Guolin Ke's avatar
Guolin Ke committed
57
#' @rdname lgb.train
58
#' 
Guolin Ke's avatar
Guolin Ke committed
59
#' @export
60
61
62
63
64
65
66
67
68
69
70
71
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,
72
                      early_stopping_rounds = NULL,
73
                      callbacks = list(),
74
                      reset_data = FALSE,
75
76
77
                      ...) {
  
  # Setup temporary variables
78
  additional_params <- list(...)
79
  params <- append(params, additional_params)
Guolin Ke's avatar
Guolin Ke committed
80
  params$verbose <- verbose
81
82
83
84
85
86
  params <- lgb.check.obj(params, obj)
  params <- lgb.check.eval(params, eval)
  fobj <- NULL
  feval <- NULL
  
  # Check for objective (function or not)
87
  if (is.function(params$objective)) {
88
    fobj <- params$objective
Guolin Ke's avatar
Guolin Ke committed
89
90
    params$objective <- "NONE"
  }
91
92
93
94
95
96
97
  
  # Check for loss (function or not)
  if (is.function(eval)) {
    feval <- eval
  }
  
  # Check for parameters
Guolin Ke's avatar
Guolin Ke committed
98
  lgb.check.params(params)
99
100
  
  # Init predictor to empty
Guolin Ke's avatar
Guolin Ke committed
101
  predictor <- NULL
102
103
  
  # Check for boosting from a trained model
104
  if (is.character(init_model)) {
Guolin Ke's avatar
Guolin Ke committed
105
    predictor <- Predictor$new(init_model)
106
  } else if (lgb.is.Booster(init_model)) {
Guolin Ke's avatar
Guolin Ke committed
107
108
    predictor <- init_model$to_predictor()
  }
109
110
  
  # Set the iteration to start from / end to (and check for boosting from a trained model, again)
Guolin Ke's avatar
Guolin Ke committed
111
  begin_iteration <- 1
112
  if (!is.null(predictor)) {
Guolin Ke's avatar
Guolin Ke committed
113
114
115
    begin_iteration <- predictor$current_iter() + 1
  }
  end_iteration <- begin_iteration + nrounds - 1
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
126
127
    
    # One or more validation dataset
    
    # Check for list as input and type correctness by object
128
129
130
    if (!is.list(valids) || !all(sapply(valids, lgb.is.Dataset))) {
      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
151
152
153
154
155
156
157
  
  # Write column names
  if (!is.null(colnames)) {
    data$set_colnames(colnames)
  }
  
  # Write categorical features
  if (!is.null(categorical_feature)) {
    data$set_categorical_feature(categorical_feature)
  }
  
  # Construct datasets, if needed
158
  data$construct()
Guolin Ke's avatar
Guolin Ke committed
159
  vaild_contain_train <- FALSE
160
161
162
163
  train_data_name <- "train"
  reduced_valid_sets <- list()
  
  # 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
  
  # Add early stopping callback
Guolin Ke's avatar
Guolin Ke committed
199
  if (!is.null(early_stopping_rounds)) {
200
201
    if (early_stopping_rounds > 0) {
      callbacks <- add.cb(callbacks, cb.early.stop(early_stopping_rounds, verbose = verbose))
Guolin Ke's avatar
Guolin Ke committed
202
203
    }
  }
204
205
  
  # "Categorize" callbacks
Guolin Ke's avatar
Guolin Ke committed
206
  cb <- categorize.callbacks(callbacks)
207
208
  
  # Construct booster with datasets
209
210
  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
211
212
213
  for (key in names(reduced_valid_sets)) {
    booster$add_valid(reduced_valid_sets[[key]], key)
  }
214
215
216
217
  
  # Callback env
  env <- CB_ENV$new()
  env$model <- booster
Guolin Ke's avatar
Guolin Ke committed
218
  env$begin_iteration <- begin_iteration
219
  env$end_iteration <- end_iteration
220
  
221
  # Start training model using number of iterations to start and end with
222
  for (i in seq(from = begin_iteration, to = end_iteration)) {
223
224
    
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
225
226
    env$iteration <- i
    env$eval_list <- list()
227
228
229
230
231
232
233
    
    # Loop through "pre_iter" element
    for (f in cb$pre_iter) {
      f(env)
    }
    
    # Update one boosting iteration
234
    booster$update(fobj = fobj)
235
236
    
    # Prepare collection of evaluation results
Guolin Ke's avatar
Guolin Ke committed
237
    eval_list <- list()
238
239
    
    # Collection: Has validation dataset?
240
    if (length(valids) > 0) {
241
242
      
      # Validation has training dataset?
243
244
      if (vaild_contain_train) {
        eval_list <- append(eval_list, booster$eval_train(feval = feval))
Guolin Ke's avatar
Guolin Ke committed
245
      }
246
247
      
      # Has no validation dataset
248
      eval_list <- append(eval_list, booster$eval_valid(feval = feval))
Guolin Ke's avatar
Guolin Ke committed
249
    }
250
251
    
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
252
    env$eval_list <- eval_list
253
254
255
256
257
258
259
    
    # Loop through env
    for (f in cb$post_iter) {
      f(env)
    }
    
    # Check for early stopping and break if needed
260
    if (env$met_early_stop) break
261
    
Guolin Ke's avatar
Guolin Ke committed
262
  }
263
  
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
  # Check for booster model conversion to predictor model
  if (reset_data) {
    
    # Store temporarily model data elsewhere
    booster_old <- list(best_iter = booster$best_iter,
                        best_score = booster$best_score,
                        record_evals = booster$record_evals)
    
    # 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
    
  }
  
280
281
282
  # Return booster
  return(booster)
  
Guolin Ke's avatar
Guolin Ke committed
283
}