callback.R 10.2 KB
Newer Older
James Lamb's avatar
James Lamb committed
1
2
#' @importFrom R6 R6Class
CB_ENV <- R6::R6Class(
Guolin Ke's avatar
Guolin Ke committed
3
  "lgb.cb_env",
4
  cloneable = FALSE,
Guolin Ke's avatar
Guolin Ke committed
5
  public = list(
6
7
    model = NULL,
    iteration = NULL,
8
    begin_iteration = NULL,
9
10
11
    end_iteration = NULL,
    eval_list = list(),
    eval_err_list = list(),
12
    best_iter = -1L,
13
    best_score = NA,
14
    met_early_stop = FALSE
Guolin Ke's avatar
Guolin Ke committed
15
16
17
18
  )
)

cb.reset.parameters <- function(new_params) {
19

20
21
22
23
  # Check for parameter list
  if (!is.list(new_params)) {
    stop(sQuote("new_params"), " must be a list")
  }
24

25
  # Deparse parameter list
26
  pnames  <- gsub("\\.", "_", names(new_params))
Guolin Ke's avatar
Guolin Ke committed
27
  nrounds <- NULL
28

29
  # Run some checks in the beginning
Guolin Ke's avatar
Guolin Ke committed
30
  init <- function(env) {
31

32
    # Store boosting rounds
33
    nrounds <<- env$end_iteration - env$begin_iteration + 1L
34

35
    # Check for model environment
36
    if (is.null(env$model)) { stop("Env should have a ", sQuote("model")) }
37

Guolin Ke's avatar
Guolin Ke committed
38
39
    # Some parameters are not allowed to be changed,
    # since changing them would simply wreck some chaos
40
41
42
43
44
    not_allowed <- c(
      .PARAMETER_ALIASES()[["num_class"]]
      , .PARAMETER_ALIASES()[["metric"]]
      , .PARAMETER_ALIASES()[["boosting"]]
    )
45
    if (any(pnames %in% not_allowed)) {
46
47
48
49
50
      stop(
        "Parameters "
        , paste0(pnames[pnames %in% not_allowed], collapse = ", ")
        , " cannot be changed during boosting"
      )
51
    }
52

53
    # Check parameter names
Guolin Ke's avatar
Guolin Ke committed
54
    for (n in pnames) {
55

56
      # Set name
Guolin Ke's avatar
Guolin Ke committed
57
      p <- new_params[[n]]
58

59
      # Check if function for parameter
Guolin Ke's avatar
Guolin Ke committed
60
      if (is.function(p)) {
61

62
        # Check if requires at least two arguments
63
        if (length(formals(p)) != 2L) {
64
          stop("Parameter ", sQuote(n), " is a function but not of two arguments")
65
        }
66

67
        # Check if numeric or character
Guolin Ke's avatar
Guolin Ke committed
68
      } else if (is.numeric(p) || is.character(p)) {
69

70
71
        # Check if length is matching
        if (length(p) != nrounds) {
72
          stop("Length of ", sQuote(n), " has to be equal to length of ", sQuote("nrounds"))
73
        }
74

Guolin Ke's avatar
Guolin Ke committed
75
      } else {
76

77
        stop("Parameter ", sQuote(n), " is not a function or a vector")
78

Guolin Ke's avatar
Guolin Ke committed
79
      }
80

Guolin Ke's avatar
Guolin Ke committed
81
    }
82

Guolin Ke's avatar
Guolin Ke committed
83
  }
84

Guolin Ke's avatar
Guolin Ke committed
85
  callback <- function(env) {
86

87
88
89
90
    # Check if rounds is null
    if (is.null(nrounds)) {
      init(env)
    }
91

92
    # Store iteration
Guolin Ke's avatar
Guolin Ke committed
93
    i <- env$iteration - env$begin_iteration
94

95
    # Apply list on parameters
Guolin Ke's avatar
Guolin Ke committed
96
    pars <- lapply(new_params, function(p) {
97
98
99
      if (is.function(p)) {
        return(p(i, nrounds))
      }
Guolin Ke's avatar
Guolin Ke committed
100
101
      p[i]
    })
102

103
104
105
106
    # To-do check pars
    if (!is.null(env$model)) {
      env$model$reset_parameter(pars)
    }
107

Guolin Ke's avatar
Guolin Ke committed
108
  }
109

110
111
112
  attr(callback, "call") <- match.call()
  attr(callback, "is_pre_iteration") <- TRUE
  attr(callback, "name") <- "cb.reset.parameters"
113
  callback
Guolin Ke's avatar
Guolin Ke committed
114
115
116
}

# Format the evaluation metric string
117
format.eval.string <- function(eval_res, eval_err = NULL) {
118

119
  # Check for empty evaluation string
120
  if (is.null(eval_res) || length(eval_res) == 0L) {
121
122
    stop("no evaluation results")
  }
123

124
  # Check for empty evaluation error
Guolin Ke's avatar
Guolin Ke committed
125
  if (!is.null(eval_err)) {
126
    sprintf("%s\'s %s:%g+%g", eval_res$data_name, eval_res$name, eval_res$value, eval_err)
Guolin Ke's avatar
Guolin Ke committed
127
  } else {
128
    sprintf("%s\'s %s:%g", eval_res$data_name, eval_res$name, eval_res$value)
Guolin Ke's avatar
Guolin Ke committed
129
  }
130

Guolin Ke's avatar
Guolin Ke committed
131
132
}

133
merge.eval.string <- function(env) {
134

135
  # Check length of evaluation list
136
  if (length(env$eval_list) <= 0L) {
137
138
    return("")
  }
139

140
141
  # Get evaluation
  msg <- list(sprintf("[%d]:", env$iteration))
142

143
  # Set if evaluation error
144
  is_eval_err <- length(env$eval_err_list) > 0L
145

146
  # Loop through evaluation list
147
  for (j in seq_along(env$eval_list)) {
148

149
    # Store evaluation error
Guolin Ke's avatar
Guolin Ke committed
150
    eval_err <- NULL
151
152
153
    if (is_eval_err) {
      eval_err <- env$eval_err_list[[j]]
    }
154

155
    # Set error message
156
    msg <- c(msg, format.eval.string(env$eval_list[[j]], eval_err))
157

Guolin Ke's avatar
Guolin Ke committed
158
  }
159

160
161
  # Return tabulated separated message
  paste0(msg, collapse = "\t")
162

Guolin Ke's avatar
Guolin Ke committed
163
164
}

165
cb.print.evaluation <- function(period = 1L) {
166

167
  # Create callback
168
  callback <- function(env) {
169

170
    # Check if period is at least 1 or more
171
    if (period > 0L) {
172

173
      # Store iteration
Guolin Ke's avatar
Guolin Ke committed
174
      i <- env$iteration
175

176
      # Check if iteration matches moduo
177
      if ((i - 1L) %% period == 0L || is.element(i, c(env$begin_iteration, env$end_iteration))) {
178

179
        # Merge evaluation string
180
        msg <- merge.eval.string(env)
181

182
        # Check if message is existing
183
        if (nchar(msg) > 0L) {
184
185
          cat(merge.eval.string(env), "\n")
        }
186

Guolin Ke's avatar
Guolin Ke committed
187
      }
188

Guolin Ke's avatar
Guolin Ke committed
189
    }
190

Guolin Ke's avatar
Guolin Ke committed
191
  }
192

193
194
195
  # Store attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.print.evaluation"
196

197
  # Return callback
198
  callback
199

Guolin Ke's avatar
Guolin Ke committed
200
201
202
}

cb.record.evaluation <- function() {
203

204
  # Create callback
205
  callback <- function(env) {
206

207
    # Return empty if empty evaluation list
208
    if (length(env$eval_list) <= 0L) {
209
210
      return()
    }
211

212
    # Set if evaluation error
213
    is_eval_err <- length(env$eval_err_list) > 0L
214

215
    # Check length of recorded evaluation
216
    if (length(env$model$record_evals) == 0L) {
217

218
      # Loop through each evaluation list element
219
      for (j in seq_along(env$eval_list)) {
220

221
        # Store names
Guolin Ke's avatar
Guolin Ke committed
222
        data_name <- env$eval_list[[j]]$data_name
223
        name <- env$eval_list[[j]]$name
Guolin Ke's avatar
Guolin Ke committed
224
        env$model$record_evals$start_iter <- env$begin_iteration
225

226
        # Check if evaluation record exists
227
        if (is.null(env$model$record_evals[[data_name]])) {
Guolin Ke's avatar
Guolin Ke committed
228
229
          env$model$record_evals[[data_name]] <- list()
        }
230

231
232
233
        # Create dummy lists
        env$model$record_evals[[data_name]][[name]] <- list()
        env$model$record_evals[[data_name]][[name]]$eval <- list()
Guolin Ke's avatar
Guolin Ke committed
234
        env$model$record_evals[[data_name]][[name]]$eval_err <- list()
235

Guolin Ke's avatar
Guolin Ke committed
236
      }
237

Guolin Ke's avatar
Guolin Ke committed
238
    }
239

240
    # Loop through each evaluation list element
241
    for (j in seq_along(env$eval_list)) {
242

243
      # Get evaluation data
Guolin Ke's avatar
Guolin Ke committed
244
245
      eval_res <- env$eval_list[[j]]
      eval_err <- NULL
246
247
248
      if (is_eval_err) {
        eval_err <- env$eval_err_list[[j]]
      }
249

250
      # Store names
Guolin Ke's avatar
Guolin Ke committed
251
      data_name <- eval_res$data_name
252
      name <- eval_res$name
253

254
      # Store evaluation data
255
256
257
258
259
260
261
262
      env$model$record_evals[[data_name]][[name]]$eval <- c(
        env$model$record_evals[[data_name]][[name]]$eval
        , eval_res$value
      )
      env$model$record_evals[[data_name]][[name]]$eval_err <- c(
        env$model$record_evals[[data_name]][[name]]$eval_err
        , eval_err
      )
263

Guolin Ke's avatar
Guolin Ke committed
264
    }
265

Guolin Ke's avatar
Guolin Ke committed
266
  }
267

268
269
270
  # Store attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.record.evaluation"
271

272
  # Return callback
273
  callback
274

Guolin Ke's avatar
Guolin Ke committed
275
276
}

277
cb.early.stop <- function(stopping_rounds, verbose = TRUE) {
278

279
  # Initialize variables
Guolin Ke's avatar
Guolin Ke committed
280
  factor_to_bigger_better <- NULL
281
282
283
284
  best_iter <- NULL
  best_score <- NULL
  best_msg <- NULL
  eval_len <- NULL
285

286
  # Initialization function
Guolin Ke's avatar
Guolin Ke committed
287
  init <- function(env) {
288

289
    # Store evaluation length
290
    eval_len <<- length(env$eval_list)
291

292
    # Early stopping cannot work without metrics
293
    if (eval_len == 0L) {
Guolin Ke's avatar
Guolin Ke committed
294
      stop("For early stopping, valids must have at least one element")
295
    }
296

297
    # Check if verbose or not
298
    if (isTRUE(verbose)) {
299
      cat("Will train until there is no improvement in ", stopping_rounds, " rounds.\n\n", sep = "")
300
    }
301

302
    # Maximization or minimization task
303
    factor_to_bigger_better <<- rep.int(1.0, eval_len)
304
    best_iter <<- rep.int(-1L, eval_len)
305
    best_score <<- rep.int(-Inf, eval_len)
306
    best_msg <<- list()
307

308
    # Loop through evaluation elements
309
    for (i in seq_len(eval_len)) {
310

311
      # Prepend message
Guolin Ke's avatar
Guolin Ke committed
312
      best_msg <<- c(best_msg, "")
313

314
      # Check if maximization or minimization
315
      if (!env$eval_list[[i]]$higher_better) {
Guolin Ke's avatar
Guolin Ke committed
316
317
        factor_to_bigger_better[i] <<- -1.0
      }
318

Guolin Ke's avatar
Guolin Ke committed
319
    }
320

Guolin Ke's avatar
Guolin Ke committed
321
  }
322

323
  # Create callback
Guolin Ke's avatar
Guolin Ke committed
324
  callback <- function(env, finalize = FALSE) {
325

326
327
328
329
    # Check for empty evaluation
    if (is.null(eval_len)) {
      init(env)
    }
330

331
    # Store iteration
Guolin Ke's avatar
Guolin Ke committed
332
    cur_iter <- env$iteration
333

334
    # Loop through evaluation
335
    for (i in seq_len(eval_len)) {
336

337
      # Store score
Guolin Ke's avatar
Guolin Ke committed
338
      score <- env$eval_list[[i]]$value * factor_to_bigger_better[i]
339

340
341
        # Check if score is better
        if (score > best_score[i]) {
342

343
344
345
          # Store new scores
          best_score[i] <<- score
          best_iter[i] <<- cur_iter
346

347
348
349
          # Prepare to print if verbose
          if (verbose) {
            best_msg[[i]] <<- as.character(merge.eval.string(env))
350
          }
351

352
        } else {
353

354
355
          # Check if early stopping is required
          if (cur_iter - best_iter[i] >= stopping_rounds) {
356

357
358
359
360
361
            # Check if model is not null
            if (!is.null(env$model)) {
              env$model$best_score <- best_score[i]
              env$model$best_iter <- best_iter[i]
            }
362

363
364
            # Print message if verbose
            if (isTRUE(verbose)) {
365

366
367
              cat("Early stopping, best iteration is:", "\n")
              cat(best_msg[[i]], "\n")
368

369
            }
370

371
372
373
            # Store best iteration and stop
            env$best_iter <- best_iter[i]
            env$met_early_stop <- TRUE
Guolin Ke's avatar
Guolin Ke committed
374
          }
375

Guolin Ke's avatar
Guolin Ke committed
376
        }
377

Guolin Ke's avatar
Guolin Ke committed
378
      if (!isTRUE(env$met_early_stop) && cur_iter == env$end_iteration) {
379
380
381
382
383
        # Check if model is not null
        if (!is.null(env$model)) {
          env$model$best_score <- best_score[i]
          env$model$best_iter <- best_iter[i]
        }
384

385
386
387
388
389
        # Print message if verbose
        if (isTRUE(verbose)) {
          cat("Did not meet early stopping, best iteration is:", "\n")
          cat(best_msg[[i]], "\n")
        }
390

391
392
393
394
        # Store best iteration and stop
        env$best_iter <- best_iter[i]
        env$met_early_stop <- TRUE
      }
Guolin Ke's avatar
Guolin Ke committed
395
396
    }
  }
397

398
399
400
  # Set attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.early.stop"
401

402
  # Return callback
403
  callback
404

Guolin Ke's avatar
Guolin Ke committed
405
406
407
}

# Extract callback names from the list of callbacks
408
409
410
callback.names <- function(cb_list) {
  unlist(lapply(cb_list, attr, "name"))
}
Guolin Ke's avatar
Guolin Ke committed
411
412

add.cb <- function(cb_list, cb) {
413

414
  # Combine two elements
Guolin Ke's avatar
Guolin Ke committed
415
  cb_list <- c(cb_list, cb)
416

417
  # Set names of elements
Guolin Ke's avatar
Guolin Ke committed
418
  names(cb_list) <- callback.names(cb_list)
419

420
421
  # Check for existence
  if ("cb.early.stop" %in% names(cb_list)) {
422

423
424
    # Concatenate existing elements
    cb_list <- c(cb_list, cb_list["cb.early.stop"])
425

426
427
    # Remove only the first one
    cb_list["cb.early.stop"] <- NULL
428

Guolin Ke's avatar
Guolin Ke committed
429
  }
430

431
  # Return element
Guolin Ke's avatar
Guolin Ke committed
432
  cb_list
433

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

categorize.callbacks <- function(cb_list) {
437

438
  # Check for pre-iteration or post-iteration
Guolin Ke's avatar
Guolin Ke committed
439
440
  list(
    pre_iter = Filter(function(x) {
441
442
443
      pre <- attr(x, "is_pre_iteration")
      !is.null(pre) && pre
    }, cb_list),
Guolin Ke's avatar
Guolin Ke committed
444
    post_iter = Filter(function(x) {
445
446
447
      pre <- attr(x, "is_pre_iteration")
      is.null(pre) || !pre
    }, cb_list)
Guolin Ke's avatar
Guolin Ke committed
448
  )
449

Guolin Ke's avatar
Guolin Ke committed
450
}