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
    if (!is.null(env$model)) {
      env$model$reset_parameter(pars)
    }
106

Guolin Ke's avatar
Guolin Ke committed
107
  }
108

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

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

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

123
  # Check for empty evaluation error
Guolin Ke's avatar
Guolin Ke committed
124
  if (!is.null(eval_err)) {
125
    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
126
  } else {
127
    sprintf("%s\'s %s:%g", eval_res$data_name, eval_res$name, eval_res$value)
Guolin Ke's avatar
Guolin Ke committed
128
  }
129

Guolin Ke's avatar
Guolin Ke committed
130
131
}

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
157
  }
158

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

Guolin Ke's avatar
Guolin Ke committed
162
163
}

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
186
      }
187

Guolin Ke's avatar
Guolin Ke committed
188
    }
189

Guolin Ke's avatar
Guolin Ke committed
190
  }
191

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

196
  # Return callback
197
  callback
198

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

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

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

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

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

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

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

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

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

230
231
232
        # 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
233
        env$model$record_evals[[data_name]][[name]]$eval_err <- list()
234

Guolin Ke's avatar
Guolin Ke committed
235
      }
236

Guolin Ke's avatar
Guolin Ke committed
237
    }
238

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

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

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

253
      # Store evaluation data
254
255
256
257
258
259
260
261
      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
      )
262

Guolin Ke's avatar
Guolin Ke committed
263
    }
264

Guolin Ke's avatar
Guolin Ke committed
265
  }
266

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

271
  # Return callback
272
  callback
273

Guolin Ke's avatar
Guolin Ke committed
274
275
}

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

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

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

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
318
    }
319

Guolin Ke's avatar
Guolin Ke committed
320
  }
321

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

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

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

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

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

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

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

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

351
        } else {
352

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

356
357
358
359
360
            # 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]
            }
361

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

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

368
            }
369

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

Guolin Ke's avatar
Guolin Ke committed
375
        }
376

Guolin Ke's avatar
Guolin Ke committed
377
      if (!isTRUE(env$met_early_stop) && cur_iter == env$end_iteration) {
378
379
380
381
382
        # 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]
        }
383

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

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

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

401
  # Return callback
402
  callback
403

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

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

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

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

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

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

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

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

Guolin Ke's avatar
Guolin Ke committed
428
  }
429

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

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

categorize.callbacks <- function(cb_list) {
436

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

Guolin Ke's avatar
Guolin Ke committed
449
}