lgb.cv.R 18.9 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
      return(invisible(NULL))
13
    },
14
    reset_parameter = function(new_params) {
15
16
      for (x in self$boosters) {
        x[["booster"]]$reset_parameter(params = new_params)
17
      }
18
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
19
20
21
22
    }
  )
)

23
#' @name lgb.cv
James Lamb's avatar
James Lamb committed
24
#' @title Main CV logic for LightGBM
James Lamb's avatar
James Lamb committed
25
26
#' @description Cross validation logic used by LightGBM
#' @inheritParams lgb_shared_params
27
#' @param nfold the original dataset is randomly partitioned into \code{nfold} equal size subsamples.
28
#' @param record Boolean, TRUE will record iteration message to \code{booster$record_evals}
29
30
31
#' @param showsd \code{boolean}, whether to show standard deviation of cross validation.
#'               This parameter defaults to \code{TRUE}. Setting it to \code{FALSE} can lead to a
#'               slight speedup by avoiding unnecessary computation.
32
#' @param stratified a \code{boolean} indicating whether sampling of folds should be stratified
33
#'                   by the values of outcome labels.
Guolin Ke's avatar
Guolin Ke committed
34
#' @param folds \code{list} provides a possibility to use a list of pre-defined CV folds
35
36
37
38
39
#'              (each element must be a vector of test fold's indices). When folds are supplied,
#'              the \code{nfold} and \code{stratified} parameters are ignored.
#' @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
40
41
42
#' @param eval_train_metric \code{boolean}, whether to add the cross validation results on the
#'               training data. This parameter defaults to \code{FALSE}. Setting it to \code{TRUE}
#'               will increase run time.
43
#' @inheritSection lgb_shared_params Early Stopping
44
#' @return a trained model \code{lgb.CVBooster}.
45
#'
Guolin Ke's avatar
Guolin Ke committed
46
#' @examples
47
#' \donttest{
48
49
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
50
51
52
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
53
54
55
56
57
#' params <- list(
#'   objective = "regression"
#'   , metric = "l2"
#'   , min_data = 1L
#'   , learning_rate = 1.0
58
#'   , num_threads = 2L
59
#' )
60
61
62
#' model <- lgb.cv(
#'   params = params
#'   , data = dtrain
63
#'   , nrounds = 5L
64
#'   , nfold = 3L
65
#' )
66
#' }
67
#'
68
#' @importFrom data.table data.table setorderv
Guolin Ke's avatar
Guolin Ke committed
69
#' @export
70
71
lgb.cv <- function(params = list()
                   , data
72
                   , nrounds = 100L
73
74
75
76
77
78
                   , nfold = 3L
                   , obj = NULL
                   , eval = NULL
                   , verbose = 1L
                   , record = TRUE
                   , eval_freq = 1L
79
                   , showsd = TRUE
80
81
82
83
84
85
                   , stratified = TRUE
                   , folds = NULL
                   , init_model = NULL
                   , early_stopping_rounds = NULL
                   , callbacks = list()
                   , reset_data = FALSE
86
                   , serializable = TRUE
87
                   , eval_train_metric = FALSE
88
                   ) {
89

90
91
92
  if (nrounds <= 0L) {
    stop("nrounds should be greater than zero")
  }
93
  if (!.is_Dataset(x = data)) {
94
    stop("lgb.cv: data must be an lgb.Dataset instance")
95
96
  }

97
98
99
100
  # 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
101
  params <- .check_wrapper_param(
102
103
104
105
    main_param_name = "verbosity"
    , params = params
    , alternative_kwarg_value = verbose
  )
106
  params <- .check_wrapper_param(
107
108
109
110
    main_param_name = "num_iterations"
    , params = params
    , alternative_kwarg_value = nrounds
  )
111
  params <- .check_wrapper_param(
112
113
114
115
    main_param_name = "metric"
    , params = params
    , alternative_kwarg_value = NULL
  )
116
  params <- .check_wrapper_param(
117
118
    main_param_name = "objective"
    , params = params
119
    , alternative_kwarg_value = obj
120
  )
121
  params <- .check_wrapper_param(
122
123
124
125
126
127
    main_param_name = "early_stopping_round"
    , params = params
    , alternative_kwarg_value = early_stopping_rounds
  )
  early_stopping_rounds <- params[["early_stopping_round"]]

128
129
  # extract any function objects passed for objective or metric
  fobj <- NULL
130
  if (is.function(params$objective)) {
Guolin Ke's avatar
Guolin Ke committed
131
    fobj <- params$objective
132
    params$objective <- "none"
Guolin Ke's avatar
Guolin Ke committed
133
  }
134

135
  # If eval is a single function, store it as a 1-element list
136
  # (for backwards compatibility). If it is a list of functions, store
137
138
  # all of them. This makes it possible to pass any mix of strings like "auc"
  # and custom functions to eval
139
  params <- .check_eval(params = params, eval = eval)
140
  eval_functions <- list(NULL)
141
  if (is.function(eval)) {
142
143
144
145
146
147
148
    eval_functions <- list(eval)
  }
  if (methods::is(eval, "list")) {
    eval_functions <- Filter(
      f = is.function
      , x = eval
    )
149
  }
150

151
  # Init predictor to empty
Guolin Ke's avatar
Guolin Ke committed
152
  predictor <- NULL
153

154
  # Check for boosting from a trained model
155
  if (is.character(init_model)) {
156
    predictor <- Predictor$new(modelfile = init_model)
157
  } else if (.is_Booster(x = init_model)) {
Guolin Ke's avatar
Guolin Ke committed
158
159
    predictor <- init_model$to_predictor()
  }
160

161
  # Set the iteration to start from / end to (and check for boosting from a trained model, again)
162
  begin_iteration <- 1L
163
  if (!is.null(predictor)) {
164
    begin_iteration <- predictor$current_iter() + 1L
Guolin Ke's avatar
Guolin Ke committed
165
  }
166
  end_iteration <- begin_iteration + params[["num_iterations"]] - 1L
167

168
169
170
171
172
  # 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

173
174
175
176
  # Construct datasets, if needed
  data$update_params(params = params)
  data$construct()

177
  # Check interaction constraints
178
  params[["interaction_constraints"]] <- .check_interaction_constraints(
179
    interaction_constraints = interaction_constraints
180
    , column_names = data$get_colnames()
181
  )
182

183
  # Update parameters with parsed parameters
184
  data$update_params(params = params)
185

186
  # Create the predictor set
187
  data$.__enclos_env__$private$set_predictor(predictor = predictor)
188

189
  if (!is.null(folds)) {
190

191
    # Check for list of folds or for single value
192
    if (!identical(class(folds), "list") || length(folds) < 2L) {
193
      stop(sQuote("folds"), " must be a list with 2 or more elements that are vectors of indices for each CV-fold")
194
    }
195

Guolin Ke's avatar
Guolin Ke committed
196
  } else {
197

198
    if (nfold <= 1L) {
199
200
      stop(sQuote("nfold"), " must be > 1")
    }
201

202
    # Create folds
203
    folds <- .generate_cv_folds(
204
205
206
      nfold = nfold
      , nrows = nrow(data)
      , stratified = stratified
207
208
      , label = get_field(dataset = data, field_name = "label")
      , group = get_field(dataset = data, field_name = "group")
209
      , params = params
210
    )
211

Guolin Ke's avatar
Guolin Ke committed
212
  }
213

214
  # Add printing log callback
215
  if (params[["verbosity"]] > 0L && eval_freq > 0L) {
216
    callbacks <- .add_cb(cb_list = callbacks, cb = cb_print_evaluation(period = eval_freq))
Guolin Ke's avatar
Guolin Ke committed
217
  }
218

219
220
  # Add evaluation log callback
  if (record) {
221
    callbacks <- .add_cb(cb_list = callbacks, cb = cb_record_evaluation())
222
  }
223

224
  # Did user pass parameters that indicate they want to use early stopping?
225
  using_early_stopping <- !is.null(early_stopping_rounds) && early_stopping_rounds > 0L
226
227
228
229
230

  boosting_param_names <- .PARAMETER_ALIASES()[["boosting"]]
  using_dart <- any(
    sapply(
      X = boosting_param_names
231
232
      , FUN = function(param) {
        identical(params[[param]], "dart")
233
      }
234
235
236
237
    )
  )

  # Cannot use early stopping with 'dart' boosting
238
  if (using_dart) {
239
240
241
    if (using_early_stopping) {
      warning("Early stopping is not available in 'dart' mode.")
    }
242
    using_early_stopping <- FALSE
243

244
    # Remove the cb_early_stop() function if it was passed in to callbacks
245
    callbacks <- Filter(
246
      f = function(cb_func) {
247
        !identical(attr(cb_func, "name"), "cb_early_stop")
248
249
250
251
252
253
      }
      , x = callbacks
    )
  }

  # If user supplied early_stopping_rounds, add the early stopping callback
254
  if (using_early_stopping) {
255
    callbacks <- .add_cb(
256
      cb_list = callbacks
257
      , cb = cb_early_stop(
258
        stopping_rounds = early_stopping_rounds
259
        , first_metric_only = isTRUE(params[["first_metric_only"]])
260
        , verbose = params[["verbosity"]] > 0L
261
262
      )
    )
Guolin Ke's avatar
Guolin Ke committed
263
  }
264

265
  cb <- .categorize_callbacks(cb_list = callbacks)
266

267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
  # Construct booster for each fold. The data.table() code below is used to
  # guarantee that indices are sorted while keeping init_score and weight together
  # with the correct indices. Note that it takes advantage of the fact that
  # someDT$some_column returns NULL is 'some_column' does not exist in the data.table
  bst_folds <- lapply(
    X = seq_along(folds)
    , FUN = function(k) {

      # For learning-to-rank, each fold is a named list with two elements:
      #   * `fold` = an integer vector of row indices
      #   * `group` = an integer vector describing which groups are in the fold
      # For classification or regression tasks, it will just be an integer
      # vector of row indices
      folds_have_group <- "group" %in% names(folds[[k]])
      if (folds_have_group) {
        test_indices <- folds[[k]]$fold
        test_group_indices <- folds[[k]]$group
284
285
        test_groups <- get_field(dataset = data, field_name = "group")[test_group_indices]
        train_groups <- get_field(dataset = data, field_name = "group")[-test_group_indices]
286
287
288
289
290
291
292
293
      } else {
        test_indices <- folds[[k]]
      }
      train_indices <- seq_len(nrow(data))[-test_indices]

      # set up test set
      indexDT <- data.table::data.table(
        indices = test_indices
294
295
        , weight = get_field(dataset = data, field_name = "weight")[test_indices]
        , init_score = get_field(dataset = data, field_name = "init_score")[test_indices]
296
      )
297
      data.table::setorderv(x = indexDT, cols = "indices", order = 1L)
298
      dtest <- lgb.slice.Dataset(data, indexDT$indices)
299
300
      set_field(dataset = dtest, field_name = "weight", data = indexDT$weight)
      set_field(dataset = dtest, field_name = "init_score", data = indexDT$init_score)
301
302
303
304

      # set up training set
      indexDT <- data.table::data.table(
        indices = train_indices
305
306
        , weight = get_field(dataset = data, field_name = "weight")[train_indices]
        , init_score = get_field(dataset = data, field_name = "init_score")[train_indices]
307
      )
308
      data.table::setorderv(x = indexDT, cols = "indices", order = 1L)
309
      dtrain <- lgb.slice.Dataset(data, indexDT$indices)
310
311
      set_field(dataset = dtrain, field_name = "weight", data = indexDT$weight)
      set_field(dataset = dtrain, field_name = "init_score", data = indexDT$init_score)
312
313

      if (folds_have_group) {
314
315
        set_field(dataset = dtest, field_name = "group", data = test_groups)
        set_field(dataset = dtrain, field_name = "group", data = train_groups)
316
317
      }

318
      booster <- Booster$new(params = params, train_set = dtrain)
319
320
321
      if (isTRUE(eval_train_metric)) {
        booster$add_valid(data = dtrain, name = "train")
      }
322
      booster$add_valid(data = dtest, name = "valid")
323
324
325
326
327
      return(
        list(booster = booster)
      )
    }
  )
328

329
  # Create new booster
330
  cv_booster <- CVBooster$new(x = bst_folds)
331

332
333
334
  # Callback env
  env <- CB_ENV$new()
  env$model <- cv_booster
Guolin Ke's avatar
Guolin Ke committed
335
  env$begin_iteration <- begin_iteration
336
  env$end_iteration <- end_iteration
337

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

341
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
342
343
    env$iteration <- i
    env$eval_list <- list()
344

345
346
347
    for (f in cb$pre_iter) {
      f(env)
    }
348

349
    # Update one boosting iteration
Guolin Ke's avatar
Guolin Ke committed
350
    msg <- lapply(cv_booster$boosters, function(fd) {
351
      fd$booster$update(fobj = fobj)
352
353
354
355
356
      out <- list()
      for (eval_function in eval_functions) {
        out <- append(out, fd$booster$eval_valid(feval = eval_function))
      }
      return(out)
Guolin Ke's avatar
Guolin Ke committed
357
    })
358

359
    # Prepare collection of evaluation results
360
    merged_msg <- .merge_cv_result(
361
362
363
      msg = msg
      , showsd = showsd
    )
364

365
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
366
    env$eval_list <- merged_msg$eval_list
367

368
    # Check for standard deviation requirement
369
    if (showsd) {
370
371
      env$eval_err_list <- merged_msg$eval_err_list
    }
372

373
374
375
376
    # Loop through env
    for (f in cb$post_iter) {
      f(env)
    }
377

378
    # Check for early stopping and break if needed
379
    if (env$met_early_stop) break
380

Guolin Ke's avatar
Guolin Ke committed
381
  }
382

383
384
  # When early stopping is not activated, we compute the best iteration / score ourselves
  # based on the first first metric
385
  if (record && is.na(env$best_score)) {
386
387
388
389
390
391
392
    # when using a custom eval function, the metric name is returned from the
    # function, so figure it out from record_evals
    if (!is.null(eval_functions[1L])) {
      first_metric <- names(cv_booster$record_evals[["valid"]])[1L]
    } else {
      first_metric <- cv_booster$.__enclos_env__$private$eval_names[1L]
    }
393
394
395
    .find_best <- which.min
    if (isTRUE(env$eval_list[[1L]]$higher_better[1L])) {
      .find_best <- which.max
396
    }
397
398
399
400
401
402
403
404
    cv_booster$best_iter <- unname(
      .find_best(
        unlist(
          cv_booster$record_evals[["valid"]][[first_metric]][[.EVAL_KEY()]]
        )
      )
    )
    cv_booster$best_score <- cv_booster$record_evals[["valid"]][[first_metric]][[.EVAL_KEY()]][[cv_booster$best_iter]]
405
  }
406
407
408
409
  # Propagate the best_iter attribute from the cv_booster to the individual boosters
  for (bst in cv_booster$boosters) {
    bst$booster$best_iter <- cv_booster$best_iter
  }
410

411
412
413
  if (reset_data) {
    lapply(cv_booster$boosters, function(fd) {
      # Store temporarily model data elsewhere
414
415
      booster_old <- list(
        best_iter = fd$booster$best_iter
416
        , best_score = fd$booster$best_score
417
418
        , record_evals = fd$booster$record_evals
      )
419
420
421
422
423
424
425
      # 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
    })
  }
426

427
428
429
430
  if (serializable) {
    lapply(cv_booster$boosters, function(model) model$booster$save_raw())
  }

431
  return(cv_booster)
432

Guolin Ke's avatar
Guolin Ke committed
433
434
435
}

# Generates random (stratified if needed) CV folds
436
.generate_cv_folds <- function(nfold, nrows, stratified, label, group, params) {
437

438
439
  # Check for group existence
  if (is.null(group)) {
440

441
    # Shuffle
442
    rnd_idx <- sample.int(nrows)
443

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

447
      y <- label[rnd_idx]
448
      y <- as.factor(y)
449
      folds <- .stratified_folds(y = y, k = nfold)
450

451
    } else {
452

453
454
      # Make simple non-stratified folds
      folds <- list()
455

456
      # Loop through each fold
457
      for (i in seq_len(nfold)) {
458
        kstep <- length(rnd_idx) %/% (nfold - i + 1L)
459
        folds[[i]] <- rnd_idx[seq_len(kstep)]
460
        rnd_idx <- rnd_idx[-seq_len(kstep)]
461
      }
462

463
    }
464

Guolin Ke's avatar
Guolin Ke committed
465
  } else {
466

467
468
    # When doing group, stratified is not possible (only random selection)
    if (nfold > length(group)) {
469
      stop("\nYou requested too many folds for the number of available groups.\n")
470
    }
471

472
    # Degroup the groups
473
    ungrouped <- inverse.rle(list(lengths = group, values = seq_along(group)))
474

475
    # Can't stratify, shuffle
476
    rnd_idx <- sample.int(length(group))
477

478
    # Make simple non-stratified folds
Guolin Ke's avatar
Guolin Ke committed
479
    folds <- list()
480

481
    # Loop through each fold
482
    for (i in seq_len(nfold)) {
483
      kstep <- length(rnd_idx) %/% (nfold - i + 1L)
484
485
486
487
      folds[[i]] <- list(
        fold = which(ungrouped %in% rnd_idx[seq_len(kstep)])
        , group = rnd_idx[seq_len(kstep)]
      )
488
      rnd_idx <- rnd_idx[-seq_len(kstep)]
Guolin Ke's avatar
Guolin Ke committed
489
    }
490

Guolin Ke's avatar
Guolin Ke committed
491
  }
492

493
  return(folds)
494

Guolin Ke's avatar
Guolin Ke committed
495
496
497
}

# Creates CV folds stratified by the values of y.
498
# It was borrowed from caret::createFolds and simplified
Guolin Ke's avatar
Guolin Ke committed
499
# by always returning an unnamed list of fold indices.
500
#' @importFrom stats quantile
501
.stratified_folds <- function(y, k) {
502

503
504
505
506
507
508
509
510
  # 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
511
  if (is.numeric(y)) {
512

513
    cuts <- length(y) %/% k
514
515
    if (cuts < 2L) {
      cuts <- 2L
516
    }
517
518
    if (cuts > 5L) {
      cuts <- 5L
519
520
521
    }
    y <- cut(
      y
522
      , unique(stats::quantile(y, probs = seq.int(0.0, 1.0, length.out = cuts)))
523
524
      , include.lowest = TRUE
    )
525

Guolin Ke's avatar
Guolin Ke committed
526
  }
527

Guolin Ke's avatar
Guolin Ke committed
528
  if (k < length(y)) {
529

530
531
    # Reset levels so that the possible levels and
    # the levels in the vector are the same
532
    y <- as.factor(as.character(y))
Guolin Ke's avatar
Guolin Ke committed
533
534
    numInClass <- table(y)
    foldVector <- vector(mode = "integer", length(y))
535

536
537
538
    # For each class, balance the fold allocation as far
    # as possible, then resample the remainder.
    # The final assignment of folds is also randomized.
539
    for (i in seq_along(numInClass)) {
540

541
542
543
      # Create a vector of integers from 1:k as many times as possible without
      # 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 produced here.
544
      seqVector <- rep(seq_len(k), numInClass[i] %/% k)
545

546
      # Add enough random integers to get length(seqVector) == numInClass[i]
547
      if (numInClass[i] %% k > 0L) {
548
        seqVector <- c(seqVector, sample.int(k, numInClass[i] %% k))
549
      }
550

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

Guolin Ke's avatar
Guolin Ke committed
554
    }
555

Guolin Ke's avatar
Guolin Ke committed
556
  } else {
557

Guolin Ke's avatar
Guolin Ke committed
558
    foldVector <- seq(along = y)
559

Guolin Ke's avatar
Guolin Ke committed
560
  }
561

Guolin Ke's avatar
Guolin Ke committed
562
  out <- split(seq(along = y), foldVector)
563
  names(out) <- NULL
564
  return(out)
Guolin Ke's avatar
Guolin Ke committed
565
566
}

567
.merge_cv_result <- function(msg, showsd) {
568

569
  if (length(msg) == 0L) {
570
571
    stop("lgb.cv: size of cv result error")
  }
572

573
  eval_len <- length(msg[[1L]])
574

575
  if (eval_len == 0L) {
576
577
    stop("lgb.cv: should provide at least one metric for CV")
  }
578

579
  # Get evaluation results using a list apply
580
  eval_result <- lapply(seq_len(eval_len), function(j) {
581
582
    as.numeric(lapply(seq_along(msg), function(i) {
      msg[[i]][[j]]$value }))
Guolin Ke's avatar
Guolin Ke committed
583
  })
584

585
  # Get evaluation. Just taking the first element here to
586
  # get structure (name, higher_better, data_name)
587
  ret_eval <- msg[[1L]]
588

589
590
591
  for (j in seq_len(eval_len)) {
    ret_eval[[j]]$value <- mean(eval_result[[j]])
  }
592

Guolin Ke's avatar
Guolin Ke committed
593
  ret_eval_err <- NULL
594

595
  # Check for standard deviation
596
  if (showsd) {
597

598
    # Parse standard deviation
599
    for (j in seq_len(eval_len)) {
600
601
      ret_eval_err <- c(
        ret_eval_err
602
        , sqrt(mean(eval_result[[j]] ^ 2L) - mean(eval_result[[j]]) ^ 2L)
603
      )
Guolin Ke's avatar
Guolin Ke committed
604
    }
605

Guolin Ke's avatar
Guolin Ke committed
606
    ret_eval_err <- as.list(ret_eval_err)
607

Guolin Ke's avatar
Guolin Ke committed
608
  }
609

610
611
612
613
614
  return(
    list(
      eval_list = ret_eval
      , eval_err_list = ret_eval_err
    )
615
  )
616

617
}