lgb.cv.R 17.3 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
2
#' @importFrom R6 R6Class
CVBooster <- R6::R6Class(
3
  classname = "lgb.CVBooster",
4
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
5
  public = list(
6
    best_iter = -1L,
7
    best_score = NA,
Guolin Ke's avatar
Guolin Ke committed
8
    record_evals = list(),
9
10
    boosters = list(),
    initialize = function(x) {
Guolin Ke's avatar
Guolin Ke committed
11
      self$boosters <- x
12
    },
13
14
15
    reset_parameter = function(new_params) {
      for (x in boosters) { x$reset_parameter(new_params) }
      self
Guolin Ke's avatar
Guolin Ke committed
16
17
18
19
    }
  )
)

James Lamb's avatar
James Lamb committed
20
#' @title Main CV logic for LightGBM
James Lamb's avatar
James Lamb committed
21
#' @description Cross validation logic used by LightGBM
James Lamb's avatar
James Lamb committed
22
#' @name lgb.cv
James Lamb's avatar
James Lamb committed
23
#' @inheritParams lgb_shared_params
24
#' @param nfold the original dataset is randomly partitioned into \code{nfold} equal size subsamples.
Guolin Ke's avatar
Guolin Ke committed
25
#' @param label vector of response values. Should be provided only when data is an R-matrix.
26
#' @param weight vector of response values. If not NULL, will set to dataset
27
#' @param obj objective function, can be character or custom objective function. Examples include
28
29
#'            \code{regression}, \code{regression_l1}, \code{huber},
#'             \code{binary}, \code{lambdarank}, \code{multiclass}, \code{multiclass}
Guolin Ke's avatar
Guolin Ke committed
30
#' @param eval evaluation function, can be (list of) character or custom eval function
31
#' @param record Boolean, TRUE will record iteration message to \code{booster$record_evals}
Guolin Ke's avatar
Guolin Ke committed
32
#' @param showsd \code{boolean}, whether to show standard deviation of cross validation
33
#' @param stratified a \code{boolean} indicating whether sampling of folds should be stratified
34
#'                   by the values of outcome labels.
Guolin Ke's avatar
Guolin Ke committed
35
#' @param folds \code{list} provides a possibility to use a list of pre-defined CV folds
36
37
#'              (each element must be a vector of test fold's indices). When folds are supplied,
#'              the \code{nfold} and \code{stratified} parameters are ignored.
Guolin Ke's avatar
Guolin Ke committed
38
#' @param colnames feature names, if not null, will use this to overwrite the names in dataset
39
#' @param categorical_feature list of str or int
40
41
42
43
44
#'                            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
45
46
47
48
#' @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}
49
#'                \item{max_depth}{Limit the max depth for tree model. This is used to deal with
James Lamb's avatar
James Lamb committed
50
51
#'                                 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
52
#'                                   the number of real CPU cores, not the number of threads (most
James Lamb's avatar
James Lamb committed
53
54
#'                                   CPU using hyper-threading to generate 2 threads per CPU core).}
#'            }
55
#'
56
#' @return a trained model \code{lgb.CVBooster}.
57
#'
Guolin Ke's avatar
Guolin Ke committed
58
#' @examples
59
60
61
62
63
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' params <- list(objective = "regression", metric = "l2")
64
65
66
#' model <- lgb.cv(
#'   params = params
#'   , data = dtrain
67
68
69
70
71
#'   , nrounds = 10L
#'   , nfold = 3L
#'   , min_data = 1L
#'   , learning_rate = 1.0
#'   , early_stopping_rounds = 5L
72
#' )
Guolin Ke's avatar
Guolin Ke committed
73
#' @export
74
75
76
77
78
79
80
81
82
83
84
lgb.cv <- function(params = list()
                   , data
                   , nrounds = 10L
                   , nfold = 3L
                   , label = NULL
                   , weight = NULL
                   , obj = NULL
                   , eval = NULL
                   , verbose = 1L
                   , record = TRUE
                   , eval_freq = 1L
85
                   , showsd = TRUE
86
87
88
89
90
91
92
93
94
95
                   , stratified = TRUE
                   , folds = NULL
                   , init_model = NULL
                   , colnames = NULL
                   , categorical_feature = NULL
                   , early_stopping_rounds = NULL
                   , callbacks = list()
                   , reset_data = FALSE
                   , ...
                   ) {
96

97
  # Setup temporary variables
Guolin Ke's avatar
Guolin Ke committed
98
  addiction_params <- list(...)
99
100
101
102
103
104
  params <- append(params, addiction_params)
  params$verbose <- verbose
  params <- lgb.check.obj(params, obj)
  params <- lgb.check.eval(params, eval)
  fobj <- NULL
  feval <- NULL
105

106
  if (nrounds <= 0L) {
107
108
    stop("nrounds should be greater than zero")
  }
109

110
  # Check for objective (function or not)
111
  if (is.function(params$objective)) {
Guolin Ke's avatar
Guolin Ke committed
112
113
114
    fobj <- params$objective
    params$objective <- "NONE"
  }
115

116
117
118
119
  # Check for loss (function or not)
  if (is.function(eval)) {
    feval <- eval
  }
120

121
  # Check for parameters
Guolin Ke's avatar
Guolin Ke committed
122
  lgb.check.params(params)
123

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

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

134
  # Set the iteration to start from / end to (and check for boosting from a trained model, again)
135
  begin_iteration <- 1L
136
  if (!is.null(predictor)) {
137
    begin_iteration <- predictor$current_iter() + 1L
Guolin Ke's avatar
Guolin Ke committed
138
  }
139
  # Check for number of rounds passed as parameter - in case there are multiple ones, take only the first one
140
  n_trees <- .PARAMETER_ALIASES()[["num_iterations"]]
141
  if (any(names(params) %in% n_trees)) {
142
    end_iteration <- begin_iteration + params[[which(names(params) %in% n_trees)[1L]]] - 1L
143
  } else {
144
    end_iteration <- begin_iteration + nrounds - 1L
145
  }
146

147
  # Check for training dataset type correctness
148
  if (!lgb.is.Dataset(data)) {
149
150
151
    if (is.null(label)) {
      stop("Labels must be provided for lgb.cv")
    }
152
    data <- lgb.Dataset(data, label = label)
Guolin Ke's avatar
Guolin Ke committed
153
  }
154

155
156
  # Check for weights
  if (!is.null(weight)) {
157
    data$setinfo("weight", weight)
158
  }
159

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

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

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

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

176
  # Construct datasets, if needed
Guolin Ke's avatar
Guolin Ke committed
177
  data$construct()
178

179
  # Check for folds
180
  if (!is.null(folds)) {
181

182
    # Check for list of folds or for single value
183
    if (!is.list(folds) || length(folds) < 2L) {
184
      stop(sQuote("folds"), " must be a list with 2 or more elements that are vectors of indices for each CV-fold")
185
    }
186

187
    # Set number of folds
Guolin Ke's avatar
Guolin Ke committed
188
    nfold <- length(folds)
189

Guolin Ke's avatar
Guolin Ke committed
190
  } else {
191

192
    # Check fold value
193
    if (nfold <= 1L) {
194
195
      stop(sQuote("nfold"), " must be > 1")
    }
196

197
    # Create folds
198
199
200
201
202
203
204
205
    folds <- generate.cv.folds(
      nfold
      , nrow(data)
      , stratified
      , getinfo(data, "label")
      , getinfo(data, "group")
      , params
    )
206

Guolin Ke's avatar
Guolin Ke committed
207
  }
208

209
  # Add printing log callback
210
  if (verbose > 0L && eval_freq > 0L) {
Guolin Ke's avatar
Guolin Ke committed
211
212
    callbacks <- add.cb(callbacks, cb.print.evaluation(eval_freq))
  }
213

214
215
216
217
  # Add evaluation log callback
  if (record) {
    callbacks <- add.cb(callbacks, cb.record.evaluation())
  }
218

219
220
221
222
223
  # 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)) {
224
    first_early_stop_param <- which(early_stop_param_indx)[[1L]]
225
226
227
228
229
230
231
232
233
234
235
    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
236
237
      , FUN = function(param) {
        identical(params[[param]], "dart")
238
      }
239
240
241
242
    )
  )

  # Cannot use early stopping with 'dart' boosting
243
  if (using_dart) {
244
245
246
247
248
    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(
249
      f = function(cb_func) {
250
251
252
253
254
255
256
        !identical(attr(cb_func, "name"), "cb.early.stop")
      }
      , x = callbacks
    )
  }

  # If user supplied early_stopping_rounds, add the early stopping callback
257
  if (using_early_stopping_via_args) {
258
259
260
261
262
263
264
    callbacks <- add.cb(
      callbacks
      , cb.early.stop(
        stopping_rounds = early_stopping_rounds
        , verbose = verbose
      )
    )
Guolin Ke's avatar
Guolin Ke committed
265
  }
266

267
  # Categorize callbacks
Guolin Ke's avatar
Guolin Ke committed
268
  cb <- categorize.callbacks(callbacks)
269

270
  # Construct booster using a list apply, check if requires group or not
271
  if (!is.list(folds[[1L]])) {
272
273
    bst_folds <- lapply(seq_along(folds), function(k) {
      dtest <- slice(data, folds[[k]])
274
      dtrain <- slice(data, seq_len(nrow(data))[-folds[[k]]])
275
276
277
278
279
280
281
282
283
284
285
      setinfo(dtrain, "weight", getinfo(data, "weight")[-folds[[k]]])
      setinfo(dtrain, "init_score", getinfo(data, "init_score")[-folds[[k]]])
      setinfo(dtest, "weight", getinfo(data, "weight")[folds[[k]]])
      setinfo(dtest, "init_score", getinfo(data, "init_score")[folds[[k]]])
      booster <- Booster$new(params, dtrain)
      booster$add_valid(dtest, "valid")
      list(booster = booster)
    })
  } else {
    bst_folds <- lapply(seq_along(folds), function(k) {
      dtest <- slice(data, folds[[k]]$fold)
286
      dtrain <- slice(data, (seq_len(nrow(data)))[-folds[[k]]$fold])
287
288
289
290
291
292
293
294
295
296
297
      setinfo(dtrain, "weight", getinfo(data, "weight")[-folds[[k]]$fold])
      setinfo(dtrain, "init_score", getinfo(data, "init_score")[-folds[[k]]$fold])
      setinfo(dtrain, "group", getinfo(data, "group")[-folds[[k]]$group])
      setinfo(dtest, "weight", getinfo(data, "weight")[folds[[k]]$fold])
      setinfo(dtest, "init_score", getinfo(data, "init_score")[folds[[k]]$fold])
      setinfo(dtest, "group", getinfo(data, "group")[folds[[k]]$group])
      booster <- Booster$new(params, dtrain)
      booster$add_valid(dtest, "valid")
      list(booster = booster)
    })
  }
298
299


300
  # Create new booster
Guolin Ke's avatar
Guolin Ke committed
301
  cv_booster <- CVBooster$new(bst_folds)
302

303
304
305
  # Callback env
  env <- CB_ENV$new()
  env$model <- cv_booster
Guolin Ke's avatar
Guolin Ke committed
306
  env$begin_iteration <- begin_iteration
307
  env$end_iteration <- end_iteration
308

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

312
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
313
314
    env$iteration <- i
    env$eval_list <- list()
315

316
317
318
319
    # Loop through "pre_iter" element
    for (f in cb$pre_iter) {
      f(env)
    }
320

321
    # Update one boosting iteration
Guolin Ke's avatar
Guolin Ke committed
322
    msg <- lapply(cv_booster$boosters, function(fd) {
323
324
      fd$booster$update(fobj = fobj)
      fd$booster$eval_valid(feval = feval)
Guolin Ke's avatar
Guolin Ke committed
325
    })
326

327
    # Prepare collection of evaluation results
Guolin Ke's avatar
Guolin Ke committed
328
    merged_msg <- lgb.merge.cv.result(msg)
329

330
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
331
    env$eval_list <- merged_msg$eval_list
332

333
    # Check for standard deviation requirement
334
    if (showsd) {
335
336
      env$eval_err_list <- merged_msg$eval_err_list
    }
337

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

343
    # Check for early stopping and break if needed
344
    if (env$met_early_stop) break
345

Guolin Ke's avatar
Guolin Ke committed
346
  }
347

348
  if (record && is.na(env$best_score)) {
349
350
351
    if (env$eval_list[[1L]]$higher_better[1L] == TRUE) {
      cv_booster$best_iter <- unname(which.max(unlist(cv_booster$record_evals[[2L]][[1L]][[1L]])))
      cv_booster$best_score <- cv_booster$record_evals[[2L]][[1L]][[1L]][[cv_booster$best_iter]]
352
    } else {
353
354
      cv_booster$best_iter <- unname(which.min(unlist(cv_booster$record_evals[[2L]][[1L]][[1L]])))
      cv_booster$best_score <- cv_booster$record_evals[[2L]][[1L]][[1L]][[cv_booster$best_iter]]
355
356
    }
  }
357

358
359
360
  if (reset_data) {
    lapply(cv_booster$boosters, function(fd) {
      # Store temporarily model data elsewhere
361
362
      booster_old <- list(
        best_iter = fd$booster$best_iter
363
        , best_score = fd$booster$best_score
364
365
        , record_evals = fd$booster$record_evals
      )
366
367
368
369
370
371
372
      # Reload model
      fd$booster <- lgb.load(model_str = fd$booster$save_model_to_string())
      fd$booster$best_iter <- booster_old$best_iter
      fd$booster$best_score <- booster_old$best_score
      fd$booster$record_evals <- booster_old$record_evals
    })
  }
373

374
375
  # Return booster
  return(cv_booster)
376

Guolin Ke's avatar
Guolin Ke committed
377
378
379
}

# Generates random (stratified if needed) CV folds
380
generate.cv.folds <- function(nfold, nrows, stratified, label, group, params) {
381

382
383
  # Check for group existence
  if (is.null(group)) {
384

385
    # Shuffle
386
    rnd_idx <- sample.int(nrows)
387

388
    # Request stratified folds
389
    if (isTRUE(stratified) && params$objective %in% c("binary", "multiclass") && length(label) == length(rnd_idx)) {
390

391
392
393
      y <- label[rnd_idx]
      y <- factor(y)
      folds <- lgb.stratified.folds(y, nfold)
394

395
    } else {
396

397
398
      # Make simple non-stratified folds
      folds <- list()
399

400
      # Loop through each fold
401
      for (i in seq_len(nfold)) {
402
        kstep <- length(rnd_idx) %/% (nfold - i + 1L)
403
        folds[[i]] <- rnd_idx[seq_len(kstep)]
404
        rnd_idx <- rnd_idx[-seq_len(kstep)]
405
      }
406

407
    }
408

Guolin Ke's avatar
Guolin Ke committed
409
  } else {
410

411
412
413
414
    # When doing group, stratified is not possible (only random selection)
    if (nfold > length(group)) {
      stop("\n\tYou requested too many folds for the number of available groups.\n")
    }
415

416
    # Degroup the groups
417
    ungrouped <- inverse.rle(list(lengths = group, values = seq_along(group)))
418

419
    # Can't stratify, shuffle
420
    rnd_idx <- sample.int(length(group))
421

422
    # Make simple non-stratified folds
Guolin Ke's avatar
Guolin Ke committed
423
    folds <- list()
424

425
    # Loop through each fold
426
    for (i in seq_len(nfold)) {
427
      kstep <- length(rnd_idx) %/% (nfold - i + 1L)
428
429
430
431
      folds[[i]] <- list(
        fold = which(ungrouped %in% rnd_idx[seq_len(kstep)])
        , group = rnd_idx[seq_len(kstep)]
      )
432
      rnd_idx <- rnd_idx[-seq_len(kstep)]
Guolin Ke's avatar
Guolin Ke committed
433
    }
434

Guolin Ke's avatar
Guolin Ke committed
435
  }
436

437
438
  # Return folds
  return(folds)
439

Guolin Ke's avatar
Guolin Ke committed
440
441
442
443
444
}

# Creates CV folds stratified by the values of y.
# It was borrowed from caret::lgb.stratified.folds and simplified
# by always returning an unnamed list of fold indices.
445
#' @importFrom stats quantile
446
lgb.stratified.folds <- function(y, k = 10L) {
447

448
449
450
451
452
453
454
455
  ## Group the numeric data based on their magnitudes
  ## and sample within those groups.
  ## When the number of samples is low, we may have
  ## issues further slicing the numeric data into
  ## groups. The number of groups will depend on the
  ## ratio of the number of folds to the sample size.
  ## At most, we will use quantiles. If the sample
  ## is too small, we just do regular unstratified CV
Guolin Ke's avatar
Guolin Ke committed
456
  if (is.numeric(y)) {
457

458
    cuts <- length(y) %/% k
459
460
    if (cuts < 2L) {
      cuts <- 2L
461
    }
462
463
    if (cuts > 5L) {
      cuts <- 5L
464
465
466
    }
    y <- cut(
      y
467
      , unique(stats::quantile(y, probs = seq.int(0.0, 1.0, length.out = cuts)))
468
469
      , include.lowest = TRUE
    )
470

Guolin Ke's avatar
Guolin Ke committed
471
  }
472

Guolin Ke's avatar
Guolin Ke committed
473
  if (k < length(y)) {
474

475
    ## Reset levels so that the possible levels and
Guolin Ke's avatar
Guolin Ke committed
476
477
478
479
    ## the levels in the vector are the same
    y <- factor(as.character(y))
    numInClass <- table(y)
    foldVector <- vector(mode = "integer", length(y))
480

Guolin Ke's avatar
Guolin Ke committed
481
482
483
    ## For each class, balance the fold allocation as far
    ## as possible, then resample the remainder.
    ## The final assignment of folds is also randomized.
484

485
    for (i in seq_along(numInClass)) {
486

487
      ## Create a vector of integers from 1:k as many times as possible without
Guolin Ke's avatar
Guolin Ke committed
488
489
      ## going over the number of samples in the class. Note that if the number
      ## of samples in a class is less than k, nothing is producd here.
490
      seqVector <- rep(seq_len(k), numInClass[i] %/% k)
491

492
      ## Add enough random integers to get  length(seqVector) == numInClass[i]
493
      if (numInClass[i] %% k > 0L) {
494
        seqVector <- c(seqVector, sample.int(k, numInClass[i] %% k))
495
      }
496

497
      ## Shuffle the integers for fold assignment and assign to this classes's data
498
      foldVector[y == dimnames(numInClass)$y[i]] <- sample(seqVector)
499

Guolin Ke's avatar
Guolin Ke committed
500
    }
501

Guolin Ke's avatar
Guolin Ke committed
502
  } else {
503

Guolin Ke's avatar
Guolin Ke committed
504
    foldVector <- seq(along = y)
505

Guolin Ke's avatar
Guolin Ke committed
506
  }
507

508
  # Return data
Guolin Ke's avatar
Guolin Ke committed
509
  out <- split(seq(along = y), foldVector)
510
511
  names(out) <- NULL
  out
Guolin Ke's avatar
Guolin Ke committed
512
513
}

514
lgb.merge.cv.result <- function(msg, showsd = TRUE) {
515

516
  # Get CV message length
517
  if (length(msg) == 0L) {
518
519
    stop("lgb.cv: size of cv result error")
  }
520

521
  # Get evaluation message length
522
  eval_len <- length(msg[[1L]])
523

524
  # Is evaluation message empty?
525
  if (eval_len == 0L) {
526
527
    stop("lgb.cv: should provide at least one metric for CV")
  }
528

529
  # Get evaluation results using a list apply
530
  eval_result <- lapply(seq_len(eval_len), function(j) {
531
532
    as.numeric(lapply(seq_along(msg), function(i) {
      msg[[i]][[j]]$value }))
Guolin Ke's avatar
Guolin Ke committed
533
  })
534

535
  # Get evaluation
536
  ret_eval <- msg[[1L]]
537

538
539
540
541
  # Go through evaluation length items
  for (j in seq_len(eval_len)) {
    ret_eval[[j]]$value <- mean(eval_result[[j]])
  }
542

543
  # Preinit evaluation error
Guolin Ke's avatar
Guolin Ke committed
544
  ret_eval_err <- NULL
545

546
  # Check for standard deviation
547
  if (showsd) {
548

549
    # Parse standard deviation
550
    for (j in seq_len(eval_len)) {
551
552
      ret_eval_err <- c(
        ret_eval_err
553
        , sqrt(mean(eval_result[[j]] ^ 2L) - mean(eval_result[[j]]) ^ 2L)
554
      )
Guolin Ke's avatar
Guolin Ke committed
555
    }
556

557
    # Convert to list
Guolin Ke's avatar
Guolin Ke committed
558
    ret_eval_err <- as.list(ret_eval_err)
559

Guolin Ke's avatar
Guolin Ke committed
560
  }
561

562
  # Return errors
563
564
565
566
  list(
    eval_list = ret_eval
    , eval_err_list = ret_eval_err
  )
567

568
}