lgb.cv.R 19.6 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
15
    reset_parameter = function(new_params) {
      for (x in boosters) { x$reset_parameter(new_params) }
16
      return(invisible(self))
Guolin Ke's avatar
Guolin Ke committed
17
18
19
20
    }
  )
)

21
#' @name lgb.cv
James Lamb's avatar
James Lamb committed
22
#' @title Main CV logic for LightGBM
James Lamb's avatar
James Lamb committed
23
24
#' @description Cross validation logic used by LightGBM
#' @inheritParams lgb_shared_params
25
#' @param nfold the original dataset is randomly partitioned into \code{nfold} equal size subsamples.
26
#' @param label Vector of labels, used if \code{data} is not an \code{\link{lgb.Dataset}}
27
#' @param weight vector of response values. If not NULL, will set to dataset
28
#' @param record Boolean, TRUE will record iteration message to \code{booster$record_evals}
Guolin Ke's avatar
Guolin Ke committed
29
#' @param showsd \code{boolean}, whether to show standard deviation of cross validation
30
#' @param stratified a \code{boolean} indicating whether sampling of folds should be stratified
31
#'                   by the values of outcome labels.
Guolin Ke's avatar
Guolin Ke committed
32
#' @param folds \code{list} provides a possibility to use a list of pre-defined CV folds
33
34
#'              (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
35
#' @param colnames feature names, if not null, will use this to overwrite the names in dataset
36
37
38
#' @param categorical_feature categorical features. This can either be a character vector of feature
#'                            names or an integer vector with the indices of the features (e.g.
#'                            \code{c(1L, 10L)} to say "the first and tenth columns").
39
40
41
#' @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
42
43
#' @param ... other parameters, see Parameters.rst for more information. A few key parameters:
#'            \itemize{
44
45
46
#'                \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
47
#'                                 overfit when #data is small. Tree still grow by leaf-wise.}
48
#'                \item{\code{num_threads}: Number of threads for LightGBM. For the best speed, set this to
49
50
51
#'                             the number of real CPU cores(\code{parallel::detectCores(logical = FALSE)}),
#'                             not the number of threads (most CPU using hyper-threading to generate 2 threads
#'                             per CPU core).}
James Lamb's avatar
James Lamb committed
52
#'            }
53
#' @inheritSection lgb_shared_params Early Stopping
54
#' @return a trained model \code{lgb.CVBooster}.
55
#'
Guolin Ke's avatar
Guolin Ke committed
56
#' @examples
57
#' \donttest{
58
59
60
61
#' data(agaricus.train, package = "lightgbm")
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' params <- list(objective = "regression", metric = "l2")
62
63
64
#' model <- lgb.cv(
#'   params = params
#'   , data = dtrain
65
#'   , nrounds = 5L
66
67
68
#'   , nfold = 3L
#'   , min_data = 1L
#'   , learning_rate = 1.0
69
#' )
70
#' }
71
#' @importFrom data.table data.table setorderv
Guolin Ke's avatar
Guolin Ke committed
72
#' @export
73
74
75
76
77
78
79
80
81
82
83
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
84
                   , showsd = TRUE
85
86
87
88
89
90
91
92
93
94
                   , stratified = TRUE
                   , folds = NULL
                   , init_model = NULL
                   , colnames = NULL
                   , categorical_feature = NULL
                   , early_stopping_rounds = NULL
                   , callbacks = list()
                   , reset_data = FALSE
                   , ...
                   ) {
95

96
97
98
99
100
  if (nrounds <= 0L) {
    stop("nrounds should be greater than zero")
  }

  # If 'data' is not an lgb.Dataset, try to construct one using 'label'
101
  if (!lgb.is.Dataset(x = data)) {
102
103
104
    if (is.null(label)) {
      stop("'label' must be provided for lgb.cv if 'data' is not an 'lgb.Dataset'")
    }
105
    data <- lgb.Dataset(data = data, label = label)
106
107
  }

108
  # Setup temporary variables
109
  params <- append(params, list(...))
110
  params$verbose <- verbose
111
112
  params <- lgb.check.obj(params = params, obj = obj)
  params <- lgb.check.eval(params = params, eval = eval)
113
  fobj <- NULL
114
  eval_functions <- list(NULL)
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
  # 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
  params <- lgb.check.wrapper_param(
    main_param_name = "num_iterations"
    , params = params
    , alternative_kwarg_value = nrounds
  )
  params <- lgb.check.wrapper_param(
    main_param_name = "early_stopping_round"
    , params = params
    , alternative_kwarg_value = early_stopping_rounds
  )
  early_stopping_rounds <- params[["early_stopping_round"]]

132
  # Check for objective (function or not)
133
  if (is.function(params$objective)) {
Guolin Ke's avatar
Guolin Ke committed
134
135
136
    fobj <- params$objective
    params$objective <- "NONE"
  }
137

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

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

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

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

169
170
171
172
  # Construct datasets, if needed
  data$update_params(params = params)
  data$construct()

173
174
175
176
177
178
179
  # Check interaction constraints
  cnames <- NULL
  if (!is.null(colnames)) {
    cnames <- colnames
  } else if (!is.null(data$get_colnames())) {
    cnames <- data$get_colnames()
  }
180
  params[["interaction_constraints"]] <- lgb.check_interaction_constraints(params = params, column_names = cnames)
181

182
183
  # Check for weights
  if (!is.null(weight)) {
184
    data$setinfo(name = "weight", info = weight)
185
  }
186

187
  # Update parameters with parsed parameters
188
  data$update_params(params = params)
189

190
  # Create the predictor set
191
  data$.__enclos_env__$private$set_predictor(predictor = predictor)
192

193
194
  # Write column names
  if (!is.null(colnames)) {
195
    data$set_colnames(colnames = colnames)
196
  }
197

198
199
  # Write categorical features
  if (!is.null(categorical_feature)) {
200
    data$set_categorical_feature(categorical_feature = categorical_feature)
201
  }
202

203
  # Check for folds
204
  if (!is.null(folds)) {
205

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

211
    # Set number of folds
Guolin Ke's avatar
Guolin Ke committed
212
    nfold <- length(folds)
213

Guolin Ke's avatar
Guolin Ke committed
214
  } else {
215

216
    # Check fold value
217
    if (nfold <= 1L) {
218
219
      stop(sQuote("nfold"), " must be > 1")
    }
220

221
    # Create folds
222
    folds <- generate.cv.folds(
223
224
225
      nfold = nfold
      , nrows = nrow(data)
      , stratified = stratified
226
227
      , label = getinfo(dataset = data, name = "label")
      , group = getinfo(dataset = data, name = "group")
228
      , params = params
229
    )
230

Guolin Ke's avatar
Guolin Ke committed
231
  }
232

233
  # Add printing log callback
234
  if (verbose > 0L && eval_freq > 0L) {
235
    callbacks <- add.cb(cb_list = callbacks, cb = cb.print.evaluation(period = eval_freq))
Guolin Ke's avatar
Guolin Ke committed
236
  }
237

238
239
  # Add evaluation log callback
  if (record) {
240
    callbacks <- add.cb(cb_list = callbacks, cb = cb.record.evaluation())
241
  }
242

243
  # Did user pass parameters that indicate they want to use early stopping?
244
  using_early_stopping <- !is.null(early_stopping_rounds) && early_stopping_rounds > 0L
245
246
247
248
249

  boosting_param_names <- .PARAMETER_ALIASES()[["boosting"]]
  using_dart <- any(
    sapply(
      X = boosting_param_names
250
251
      , FUN = function(param) {
        identical(params[[param]], "dart")
252
      }
253
254
255
256
    )
  )

  # Cannot use early stopping with 'dart' boosting
257
  if (using_dart) {
258
    warning("Early stopping is not available in 'dart' mode.")
259
    using_early_stopping <- FALSE
260
261
262

    # Remove the cb.early.stop() function if it was passed in to callbacks
    callbacks <- Filter(
263
      f = function(cb_func) {
264
265
266
267
268
269
270
        !identical(attr(cb_func, "name"), "cb.early.stop")
      }
      , x = callbacks
    )
  }

  # If user supplied early_stopping_rounds, add the early stopping callback
271
  if (using_early_stopping) {
272
    callbacks <- add.cb(
273
274
      cb_list = callbacks
      , cb = cb.early.stop(
275
        stopping_rounds = early_stopping_rounds
276
        , first_metric_only = isTRUE(params[["first_metric_only"]])
277
278
279
        , verbose = verbose
      )
    )
Guolin Ke's avatar
Guolin Ke committed
280
  }
281

282
  cb <- categorize.callbacks(cb_list = callbacks)
283

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
  # 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
301
302
        test_groups <- getinfo(dataset = data, name = "group")[test_group_indices]
        train_groups <- getinfo(dataset = data, name = "group")[-test_group_indices]
303
304
305
306
307
308
309
310
      } 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
311
312
        , weight = getinfo(dataset = data, name = "weight")[test_indices]
        , init_score = getinfo(dataset = data, name = "init_score")[test_indices]
313
      )
314
      data.table::setorderv(x = indexDT, cols = "indices", order = 1L)
315
      dtest <- slice(data, indexDT$indices)
316
317
      setinfo(dataset = dtest, name = "weight", info = indexDT$weight)
      setinfo(dataset = dtest, name = "init_score", info = indexDT$init_score)
318
319
320
321

      # set up training set
      indexDT <- data.table::data.table(
        indices = train_indices
322
323
        , weight = getinfo(dataset = data, name = "weight")[train_indices]
        , init_score = getinfo(dataset = data, name = "init_score")[train_indices]
324
      )
325
      data.table::setorderv(x = indexDT, cols = "indices", order = 1L)
326
      dtrain <- slice(data, indexDT$indices)
327
328
      setinfo(dataset = dtrain, name = "weight", info = indexDT$weight)
      setinfo(dataset = dtrain, name = "init_score", info = indexDT$init_score)
329
330

      if (folds_have_group) {
331
332
        setinfo(dataset = dtest, name = "group", info = test_groups)
        setinfo(dataset = dtrain, name = "group", info = train_groups)
333
334
      }

335
336
      booster <- Booster$new(params = params, train_set = dtrain)
      booster$add_valid(data = dtest, name = "valid")
337
338
339
340
341
      return(
        list(booster = booster)
      )
    }
  )
342

343
  # Create new booster
344
  cv_booster <- CVBooster$new(x = bst_folds)
345

346
347
348
  # Callback env
  env <- CB_ENV$new()
  env$model <- cv_booster
Guolin Ke's avatar
Guolin Ke committed
349
  env$begin_iteration <- begin_iteration
350
  env$end_iteration <- end_iteration
351

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

355
    # Overwrite iteration in environment
Guolin Ke's avatar
Guolin Ke committed
356
357
    env$iteration <- i
    env$eval_list <- list()
358

359
360
361
    for (f in cb$pre_iter) {
      f(env)
    }
362

363
    # Update one boosting iteration
Guolin Ke's avatar
Guolin Ke committed
364
    msg <- lapply(cv_booster$boosters, function(fd) {
365
      fd$booster$update(fobj = fobj)
366
367
368
369
370
      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
371
    })
372

373
    # Prepare collection of evaluation results
374
    merged_msg <- lgb.merge.cv.result(msg = msg)
375

376
    # Write evaluation result in environment
Guolin Ke's avatar
Guolin Ke committed
377
    env$eval_list <- merged_msg$eval_list
378

379
    # Check for standard deviation requirement
380
    if (showsd) {
381
382
      env$eval_err_list <- merged_msg$eval_err_list
    }
383

384
385
386
387
    # Loop through env
    for (f in cb$post_iter) {
      f(env)
    }
388

389
    # Check for early stopping and break if needed
390
    if (env$met_early_stop) break
391

Guolin Ke's avatar
Guolin Ke committed
392
  }
393

394
395
  # When early stopping is not activated, we compute the best iteration / score ourselves
  # based on the first first metric
396
  if (record && is.na(env$best_score)) {
397
398
399
400
401
402
403
    # 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]
    }
404
405
406
    .find_best <- which.min
    if (isTRUE(env$eval_list[[1L]]$higher_better[1L])) {
      .find_best <- which.max
407
    }
408
409
410
411
412
413
414
415
    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]]
416
  }
417

418
419
420
  if (reset_data) {
    lapply(cv_booster$boosters, function(fd) {
      # Store temporarily model data elsewhere
421
422
      booster_old <- list(
        best_iter = fd$booster$best_iter
423
        , best_score = fd$booster$best_score
424
425
        , record_evals = fd$booster$record_evals
      )
426
427
428
429
430
431
432
      # 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
    })
  }
433

434
  return(cv_booster)
435

Guolin Ke's avatar
Guolin Ke committed
436
437
438
}

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

441
442
  # Check for group existence
  if (is.null(group)) {
443

444
    # Shuffle
445
    rnd_idx <- sample.int(nrows)
446

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

450
      y <- label[rnd_idx]
451
      y <- as.factor(y)
452
      folds <- lgb.stratified.folds(y = y, k = nfold)
453

454
    } else {
455

456
457
      # Make simple non-stratified folds
      folds <- list()
458

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

466
    }
467

Guolin Ke's avatar
Guolin Ke committed
468
  } else {
469

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

475
    # Degroup the groups
476
    ungrouped <- inverse.rle(list(lengths = group, values = seq_along(group)))
477

478
    # Can't stratify, shuffle
479
    rnd_idx <- sample.int(length(group))
480

481
    # Make simple non-stratified folds
Guolin Ke's avatar
Guolin Ke committed
482
    folds <- list()
483

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

Guolin Ke's avatar
Guolin Ke committed
494
  }
495

496
  return(folds)
497

Guolin Ke's avatar
Guolin Ke committed
498
499
500
}

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

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

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

Guolin Ke's avatar
Guolin Ke committed
529
  }
530

Guolin Ke's avatar
Guolin Ke committed
531
  if (k < length(y)) {
532

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

Guolin Ke's avatar
Guolin Ke committed
539
540
541
    ## For each class, balance the fold allocation as far
    ## as possible, then resample the remainder.
    ## The final assignment of folds is also randomized.
542

543
    for (i in seq_along(numInClass)) {
544

545
      ## Create a vector of integers from 1:k as many times as possible without
Guolin Ke's avatar
Guolin Ke committed
546
547
      ## 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.
548
      seqVector <- rep(seq_len(k), numInClass[i] %/% k)
549

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

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

Guolin Ke's avatar
Guolin Ke committed
558
    }
559

Guolin Ke's avatar
Guolin Ke committed
560
  } else {
561

Guolin Ke's avatar
Guolin Ke committed
562
    foldVector <- seq(along = y)
563

Guolin Ke's avatar
Guolin Ke committed
564
  }
565

Guolin Ke's avatar
Guolin Ke committed
566
  out <- split(seq(along = y), foldVector)
567
  names(out) <- NULL
568
  return(out)
Guolin Ke's avatar
Guolin Ke committed
569
570
}

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

573
  # Get CV message length
574
  if (length(msg) == 0L) {
575
576
    stop("lgb.cv: size of cv result error")
  }
577

578
  # Get evaluation message length
579
  eval_len <- length(msg[[1L]])
580

581
  # Is evaluation message empty?
582
  if (eval_len == 0L) {
583
584
    stop("lgb.cv: should provide at least one metric for CV")
  }
585

586
  # Get evaluation results using a list apply
587
  eval_result <- lapply(seq_len(eval_len), function(j) {
588
589
    as.numeric(lapply(seq_along(msg), function(i) {
      msg[[i]][[j]]$value }))
Guolin Ke's avatar
Guolin Ke committed
590
  })
591

592
  # Get evaluation. Just taking the first element here to
593
  # get structure (name, higher_better, data_name)
594
  ret_eval <- msg[[1L]]
595

596
597
598
599
  # Go through evaluation length items
  for (j in seq_len(eval_len)) {
    ret_eval[[j]]$value <- mean(eval_result[[j]])
  }
600

Guolin Ke's avatar
Guolin Ke committed
601
  ret_eval_err <- NULL
602

603
  # Check for standard deviation
604
  if (showsd) {
605

606
    # Parse standard deviation
607
    for (j in seq_len(eval_len)) {
608
609
      ret_eval_err <- c(
        ret_eval_err
610
        , sqrt(mean(eval_result[[j]] ^ 2L) - mean(eval_result[[j]]) ^ 2L)
611
      )
Guolin Ke's avatar
Guolin Ke committed
612
    }
613

614
    # Convert to list
Guolin Ke's avatar
Guolin Ke committed
615
    ret_eval_err <- as.list(ret_eval_err)
616

Guolin Ke's avatar
Guolin Ke committed
617
  }
618

619
  # Return errors
620
621
622
623
624
  return(
    list(
      eval_list = ret_eval
      , eval_err_list = ret_eval_err
    )
625
  )
626

627
}