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


#' Main CV logic for LightGBM
20
#'
Guolin Ke's avatar
Guolin Ke committed
21
#' Main CV logic for LightGBM
22
#'
Guolin Ke's avatar
Guolin Ke committed
23
24
25
#' @param params List of parameters
#' @param data a \code{lgb.Dataset} object, used for CV
#' @param nrounds number of CV rounds
26
#' @param nfold the original dataset is randomly partitioned into \code{nfold} equal size subsamples.
Guolin Ke's avatar
Guolin Ke committed
27
#' @param label vector of response values. Should be provided only when data is an R-matrix.
28
#' @param weight vector of response values. If not NULL, will set to dataset
29
30
31
32
33
34
35
36
#' @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).
Guolin Ke's avatar
Guolin Ke committed
37
#' @param eval evaluation function, can be (list of) character or custom eval function
38
39
40
#' @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 frequence, only effect when verbose > 0
Guolin Ke's avatar
Guolin Ke committed
41
#' @param showsd \code{boolean}, whether to show standard deviation of cross validation
42
#' @param stratified a \code{boolean} indicating whether sampling of folds should be stratified
Guolin Ke's avatar
Guolin Ke committed
43
44
#'        by the values of outcome labels.
#' @param folds \code{list} provides a possibility to use a list of pre-defined CV folds
45
#'        (each element must be a vector of test fold's indices). When folds are supplied,
Guolin Ke's avatar
Guolin Ke committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#'        the \code{nfold} and \code{stratified} parameters are ignored.
#' @param init_model path of model file of \code{lgb.Booster} object, will continue train from this model
#' @param colnames feature names, if not null, will use this to overwrite the names in dataset
#' @param categorical_feature list of str or int
#'        type int represents index,
#'        type str represents feature names
#' @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
#' @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
61
#' @return a trained model \code{lgb.CVBooster}.
Guolin Ke's avatar
Guolin Ke committed
62
#' @examples
63
64
65
66
67
68
69
70
#' \dontrun{
#'   library(lightgbm)
#'   data(agaricus.train, package='lightgbm')
#'   train <- agaricus.train
#'   dtrain <- lgb.Dataset(train$data, label=train$label)
#'   params <- list(objective="regression", metric="l2")
#'   model <- lgb.cv(params, dtrain, 10, nfold=5, min_data=1, learning_rate=1, early_stopping_rounds=10)
#' }
Guolin Ke's avatar
Guolin Ke committed
71
72
#' @rdname lgb.train
#' @export
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
lgb.cv <- function(params=list(), data, nrounds = 10, 
                   nfold                 = 3,
                   label                 = NULL,
                   weight                = NULL,
                   obj                   = NULL,
                   eval                  = NULL,
                   verbose               = 1,
                   record                = TRUE,
                   eval_freq             = 1L,
                   showsd                = TRUE,
                   stratified            = TRUE,
                   folds                 = NULL,
                   init_model            = NULL,
                   colnames              = NULL,
                   categorical_feature   = NULL,
                   early_stopping_rounds = NULL,
                   callbacks             = list(), ...) {
Guolin Ke's avatar
Guolin Ke committed
90
  addiction_params <- list(...)
91
92
93
94
95
96
97
  params           <- append(params, addiction_params)
  params$verbose   <- verbose
  params           <- lgb.check.obj(params, obj)
  params           <- lgb.check.eval(params, eval)
  fobj             <- NULL
  feval            <- NULL
  if (is.function(params$objective)) {
Guolin Ke's avatar
Guolin Ke committed
98
99
100
    fobj <- params$objective
    params$objective <- "NONE"
  }
101
  if (is.function(eval)) { feval <- eval }
Guolin Ke's avatar
Guolin Ke committed
102
103
  lgb.check.params(params)
  predictor <- NULL
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
109
    predictor <- init_model$to_predictor()
  }
  begin_iteration <- 1
110
  if (!is.null(predictor)) {
Guolin Ke's avatar
Guolin Ke committed
111
112
113
114
    begin_iteration <- predictor$current_iter() + 1
  }
  end_iteration <- begin_iteration + nrounds - 1

115
116
117
  if (!lgb.is.Dataset(data)) {
    if (is.null(label)) { stop("Labels must be provided for lgb.cv") }
    data <- lgb.Dataset(data, label = label)
Guolin Ke's avatar
Guolin Ke committed
118
119
  }

120
  if (!is.null(weight)) { data$set_info("weight", weight) }
Guolin Ke's avatar
Guolin Ke committed
121
122
123

  data$update_params(params)
  data$.__enclos_env__$private$set_predictor(predictor)
124
  if (!is.null(colnames)) { data$set_colnames(colnames) }
Guolin Ke's avatar
Guolin Ke committed
125
  if (!is.null(categorical_feature)) { data$set_categorical_feature(categorical_feature) }
Guolin Ke's avatar
Guolin Ke committed
126
127
  data$construct()

128
  if (!is.null(folds)) {
129
    if (!is.list(folds) | length(folds) < 2)
130
      stop(sQuote("folds"), " must be a list with 2 or more elements that are vectors of indices for each CV-fold")
Guolin Ke's avatar
Guolin Ke committed
131
132
    nfold <- length(folds)
  } else {
133
    if (nfold <= 1) { stop(sQuote("nfold"), " must be > 1") }
Guolin Ke's avatar
Guolin Ke committed
134
135
136
    folds <- generate.cv.folds(nfold, nrow(data), stratified, getinfo(data, 'label'), params)
  }

137
  if (verbose > 0 & eval_freq > 0) {
Guolin Ke's avatar
Guolin Ke committed
138
139
140
    callbacks <- add.cb(callbacks, cb.print.evaluation(eval_freq))
  }

141
  if (record) { callbacks <- add.cb(callbacks, cb.record.evaluation()) }
Guolin Ke's avatar
Guolin Ke committed
142
143

  if (!is.null(early_stopping_rounds)) {
144
145
    if (early_stopping_rounds > 0) {
      callbacks <- add.cb(callbacks, cb.early.stop(early_stopping_rounds, verbose = verbose))
Guolin Ke's avatar
Guolin Ke committed
146
147
148
149
150
151
    }
  }

  cb <- categorize.callbacks(callbacks)

  # construct booster
152
153
154
  bst_folds <- lapply(seq_along(folds), function(k) {
    dtest   <- slice(data, folds[[k]])
    dtrain  <- slice(data, unlist(folds[-k]))
Guolin Ke's avatar
Guolin Ke committed
155
156
    booster <- Booster$new(params, dtrain)
    booster$add_valid(dtest, "valid")
157
    list(booster = booster)
Guolin Ke's avatar
Guolin Ke committed
158
159
160
161
162
  })

  cv_booster <- CVBooster$new(bst_folds)

  # callback env
163
164
  env                 <- CB_ENV$new()
  env$model           <- cv_booster
Guolin Ke's avatar
Guolin Ke committed
165
  env$begin_iteration <- begin_iteration
166
  env$end_iteration   <- end_iteration
Guolin Ke's avatar
Guolin Ke committed
167
168

  #start training
169
  for (i in seq(from = begin_iteration, to = end_iteration)) {
Guolin Ke's avatar
Guolin Ke committed
170
171
    env$iteration <- i
    env$eval_list <- list()
172
    for (f in cb$pre_iter) { f(env) }
Guolin Ke's avatar
Guolin Ke committed
173
174
    # update one iter
    msg <- lapply(cv_booster$boosters, function(fd) {
175
176
      fd$booster$update(fobj = fobj)
      fd$booster$eval_valid(feval = feval)
Guolin Ke's avatar
Guolin Ke committed
177
178
179
180
181
    })

    merged_msg <- lgb.merge.cv.result(msg)

    env$eval_list <- merged_msg$eval_list
182
183
    if(showsd) { env$eval_err_list <- merged_msg$eval_err_list }
    for (f in cb$post_iter) { f(env) }
Guolin Ke's avatar
Guolin Ke committed
184
185

    # met early stopping
186
    if (env$met_early_stop) break
Guolin Ke's avatar
Guolin Ke committed
187
188
  }

189
  cv_booster
Guolin Ke's avatar
Guolin Ke committed
190
191
192
193
194
}

# Generates random (stratified if needed) CV folds
generate.cv.folds <- function(nfold, nrows, stratified, label, params) {
  # cannot do it for rank
195
  if (exists('objective', where = params) &&
Guolin Ke's avatar
Guolin Ke committed
196
197
198
199
200
201
      is.character(params$objective) &&
      params$objective == 'lambdarank') {
    stop("\n\tAutomatic generation of CV-folds is not implemented for lambdarank!\n",
         "\tConsider providing pre-computed CV-folds through the 'folds=' parameter.\n")
  }
  # shuffle
202
203
  rnd_idx <- sample(seq_len(nrows))
  if (isTRUE(stratified) &&
Guolin Ke's avatar
Guolin Ke committed
204
      length(label) == length(rnd_idx)) {
205
206
    y     <- label[rnd_idx]
    y     <- factor(y)
Guolin Ke's avatar
Guolin Ke committed
207
208
209
210
211
    folds <- lgb.stratified.folds(y, nfold)
  } else {
    # make simple non-stratified folds
    kstep <- length(rnd_idx) %/% nfold
    folds <- list()
212
213
214
    for (i in seq_len(nfold - 1)) {
      folds[[i]] <- rnd_idx[seq_len(kstep)]
      rnd_idx    <- rnd_idx[-(seq_len(kstep))]
Guolin Ke's avatar
Guolin Ke committed
215
216
217
    }
    folds[[nfold]] <- rnd_idx
  }
218
  folds
Guolin Ke's avatar
Guolin Ke committed
219
220
221
222
223
}

# 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.
224
lgb.stratified.folds <- function(y, k = 10) {
Guolin Ke's avatar
Guolin Ke committed
225
226
227
228
229
230
231
232
233
  if (is.numeric(y)) {
    ## 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
234
    ## is too small, we just do regular unstratified CV
Guolin Ke's avatar
Guolin Ke committed
235
    cuts <- floor(length(y) / k)
236
237
    if (cuts < 2) { cuts <- 2 }
    if (cuts > 5) { cuts <- 5 }
Guolin Ke's avatar
Guolin Ke committed
238
    y <- cut(y,
239
240
      unique(stats::quantile(y, probs = seq(0, 1, length = cuts))),
      include.lowest = TRUE)
Guolin Ke's avatar
Guolin Ke committed
241
242
243
244
245
246
247
248
249
250
251
252
  }

  if (k < length(y)) {
    ## reset levels so that the possible levels and
    ## the levels in the vector are the same
    y <- factor(as.character(y))
    numInClass <- table(y)
    foldVector <- vector(mode = "integer", length(y))

    ## For each class, balance the fold allocation as far
    ## as possible, then resample the remainder.
    ## The final assignment of folds is also randomized.
253
    for (i in seq_along(numInClass)) {
Guolin Ke's avatar
Guolin Ke committed
254
255
256
      ## 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 producd here.
257
      seqVector <- rep(seq_len(k), numInClass[i] %/% k)
Guolin Ke's avatar
Guolin Ke committed
258
      ## add enough random integers to get  length(seqVector) == numInClass[i]
259
260
261
      if (numInClass[i] %% k > 0) {
        seqVector <- c(seqVector, sample(seq_len(k), numInClass[i] %% k))
      }
Guolin Ke's avatar
Guolin Ke committed
262
      ## shuffle the integers for fold assignment and assign to this classes's data
263
      foldVector[y == dimnames(numInClass)$y[i]] <- sample(seqVector)
Guolin Ke's avatar
Guolin Ke committed
264
265
266
267
268
269
    }
  } else {
    foldVector <- seq(along = y)
  }

  out <- split(seq(along = y), foldVector)
270
  `names<-`(out, NULL)
Guolin Ke's avatar
Guolin Ke committed
271
272
}

273
274
lgb.merge.cv.result <- function(msg, showsd = TRUE){
  if (length(msg) == 0) { stop("lgb.cv: size of cv result error") }
Guolin Ke's avatar
Guolin Ke committed
275
  eval_len <- length(msg[[1]])
276
277
278
  if (eval_len == 0) { stop("lgb.cv: should provide at least one metric for CV") }
  eval_result <- lapply(seq_len(eval_len), function(j) {
    as.numeric(lapply(seq_along(msg), function(i) { msg[[i]][[j]]$value }))
Guolin Ke's avatar
Guolin Ke committed
279
280
  })
  ret_eval <- msg[[1]]
281
  for (j in seq_len(eval_len)) { ret_eval[[j]]$value <- mean(eval_result[[j]]) }
Guolin Ke's avatar
Guolin Ke committed
282
  ret_eval_err <- NULL
283
284
  if (showsd) {
    for (j in seq_len(eval_len)) {
Guolin Ke's avatar
Guolin Ke committed
285
286
287
288
      ret_eval_err <- c( ret_eval_err, sqrt( mean(eval_result[[j]]^2) - mean(eval_result[[j]])^2 ))
    }
    ret_eval_err <- as.list(ret_eval_err)
  }
289
290
  list(eval_list = ret_eval, eval_err_list = ret_eval_err)
}