callback.R 9.79 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
    # Check for model environment
33
34
35
    if (is.null(env$model)) {
      stop("Env should have a ", sQuote("model"))
    }
36

37
38
39
    # Store boosting rounds
    nrounds <<- env$end_iteration - env$begin_iteration + 1L

40
    # Check parameter names
Guolin Ke's avatar
Guolin Ke committed
41
    for (n in pnames) {
42

43
      # Set name
Guolin Ke's avatar
Guolin Ke committed
44
      p <- new_params[[n]]
45

46
      # Check if function for parameter
Guolin Ke's avatar
Guolin Ke committed
47
      if (is.function(p)) {
48

49
        # Check if requires at least two arguments
50
        if (length(formals(p)) != 2L) {
51
          stop("Parameter ", sQuote(n), " is a function but not of two arguments")
52
        }
53

54
        # Check if numeric or character
Guolin Ke's avatar
Guolin Ke committed
55
      } else if (is.numeric(p) || is.character(p)) {
56

57
58
        # Check if length is matching
        if (length(p) != nrounds) {
59
          stop("Length of ", sQuote(n), " has to be equal to length of ", sQuote("nrounds"))
60
        }
61

Guolin Ke's avatar
Guolin Ke committed
62
      } else {
63

64
        stop("Parameter ", sQuote(n), " is not a function or a vector")
65

Guolin Ke's avatar
Guolin Ke committed
66
      }
67

Guolin Ke's avatar
Guolin Ke committed
68
    }
69

Guolin Ke's avatar
Guolin Ke committed
70
  }
71

Guolin Ke's avatar
Guolin Ke committed
72
  callback <- function(env) {
73

74
75
76
77
    # Check if rounds is null
    if (is.null(nrounds)) {
      init(env)
    }
78

79
    # Store iteration
Guolin Ke's avatar
Guolin Ke committed
80
    i <- env$iteration - env$begin_iteration
81

82
    # Apply list on parameters
Guolin Ke's avatar
Guolin Ke committed
83
    pars <- lapply(new_params, function(p) {
84
85
86
      if (is.function(p)) {
        return(p(i, nrounds))
      }
Guolin Ke's avatar
Guolin Ke committed
87
88
      p[i]
    })
89

90
91
92
    if (!is.null(env$model)) {
      env$model$reset_parameter(pars)
    }
93

Guolin Ke's avatar
Guolin Ke committed
94
  }
95

96
97
98
  attr(callback, "call") <- match.call()
  attr(callback, "is_pre_iteration") <- TRUE
  attr(callback, "name") <- "cb.reset.parameters"
99
  callback
Guolin Ke's avatar
Guolin Ke committed
100
101
102
}

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

105
  # Check for empty evaluation string
106
  if (is.null(eval_res) || length(eval_res) == 0L) {
107
108
    stop("no evaluation results")
  }
109

110
  # Check for empty evaluation error
Guolin Ke's avatar
Guolin Ke committed
111
  if (!is.null(eval_err)) {
112
    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
113
  } else {
114
    sprintf("%s\'s %s:%g", eval_res$data_name, eval_res$name, eval_res$value)
Guolin Ke's avatar
Guolin Ke committed
115
  }
116

Guolin Ke's avatar
Guolin Ke committed
117
118
}

119
merge.eval.string <- function(env) {
120

121
  # Check length of evaluation list
122
  if (length(env$eval_list) <= 0L) {
123
124
    return("")
  }
125

126
127
  # Get evaluation
  msg <- list(sprintf("[%d]:", env$iteration))
128

129
  # Set if evaluation error
130
  is_eval_err <- length(env$eval_err_list) > 0L
131

132
  # Loop through evaluation list
133
  for (j in seq_along(env$eval_list)) {
134

135
    # Store evaluation error
Guolin Ke's avatar
Guolin Ke committed
136
    eval_err <- NULL
137
138
139
    if (is_eval_err) {
      eval_err <- env$eval_err_list[[j]]
    }
140

141
    # Set error message
142
    msg <- c(msg, format.eval.string(env$eval_list[[j]], eval_err))
143

Guolin Ke's avatar
Guolin Ke committed
144
  }
145

146
147
  # Return tabulated separated message
  paste0(msg, collapse = "\t")
148

Guolin Ke's avatar
Guolin Ke committed
149
150
}

151
cb.print.evaluation <- function(period = 1L) {
152

153
  # Create callback
154
  callback <- function(env) {
155

156
    # Check if period is at least 1 or more
157
    if (period > 0L) {
158

159
      # Store iteration
Guolin Ke's avatar
Guolin Ke committed
160
      i <- env$iteration
161

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

165
        # Merge evaluation string
166
        msg <- merge.eval.string(env)
167

168
        # Check if message is existing
169
        if (nchar(msg) > 0L) {
170
171
          cat(merge.eval.string(env), "\n")
        }
172

Guolin Ke's avatar
Guolin Ke committed
173
      }
174

Guolin Ke's avatar
Guolin Ke committed
175
    }
176

Guolin Ke's avatar
Guolin Ke committed
177
  }
178

179
180
181
  # Store attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.print.evaluation"
182

183
  # Return callback
184
  callback
185

Guolin Ke's avatar
Guolin Ke committed
186
187
188
}

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

190
  # Create callback
191
  callback <- function(env) {
192

193
    # Return empty if empty evaluation list
194
    if (length(env$eval_list) <= 0L) {
195
196
      return()
    }
197

198
    # Set if evaluation error
199
    is_eval_err <- length(env$eval_err_list) > 0L
200

201
    # Check length of recorded evaluation
202
    if (length(env$model$record_evals) == 0L) {
203

204
      # Loop through each evaluation list element
205
      for (j in seq_along(env$eval_list)) {
206

207
        # Store names
Guolin Ke's avatar
Guolin Ke committed
208
        data_name <- env$eval_list[[j]]$data_name
209
        name <- env$eval_list[[j]]$name
Guolin Ke's avatar
Guolin Ke committed
210
        env$model$record_evals$start_iter <- env$begin_iteration
211

212
        # Check if evaluation record exists
213
        if (is.null(env$model$record_evals[[data_name]])) {
Guolin Ke's avatar
Guolin Ke committed
214
215
          env$model$record_evals[[data_name]] <- list()
        }
216

217
218
219
        # 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
220
        env$model$record_evals[[data_name]][[name]]$eval_err <- list()
221

Guolin Ke's avatar
Guolin Ke committed
222
      }
223

Guolin Ke's avatar
Guolin Ke committed
224
    }
225

226
    # Loop through each evaluation list element
227
    for (j in seq_along(env$eval_list)) {
228

229
      # Get evaluation data
Guolin Ke's avatar
Guolin Ke committed
230
231
      eval_res <- env$eval_list[[j]]
      eval_err <- NULL
232
233
234
      if (is_eval_err) {
        eval_err <- env$eval_err_list[[j]]
      }
235

236
      # Store names
Guolin Ke's avatar
Guolin Ke committed
237
      data_name <- eval_res$data_name
238
      name <- eval_res$name
239

240
      # Store evaluation data
241
242
243
244
245
246
247
248
      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
      )
249

Guolin Ke's avatar
Guolin Ke committed
250
    }
251

Guolin Ke's avatar
Guolin Ke committed
252
  }
253

254
255
256
  # Store attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.record.evaluation"
257

258
  # Return callback
259
  callback
260

Guolin Ke's avatar
Guolin Ke committed
261
262
}

263
cb.early.stop <- function(stopping_rounds, verbose = TRUE) {
264

265
  # Initialize variables
Guolin Ke's avatar
Guolin Ke committed
266
  factor_to_bigger_better <- NULL
267
268
269
270
  best_iter <- NULL
  best_score <- NULL
  best_msg <- NULL
  eval_len <- NULL
271

272
  # Initialization function
Guolin Ke's avatar
Guolin Ke committed
273
  init <- function(env) {
274

275
    # Early stopping cannot work without metrics
276
    if (length(env$eval_list) == 0L) {
Guolin Ke's avatar
Guolin Ke committed
277
      stop("For early stopping, valids must have at least one element")
278
    }
279

280
281
282
    # Store evaluation length
    eval_len <<- length(env$eval_list)

283
    # Check if verbose or not
284
    if (isTRUE(verbose)) {
285
      cat("Will train until there is no improvement in ", stopping_rounds, " rounds.\n\n", sep = "")
286
    }
287

288
    # Maximization or minimization task
289
    factor_to_bigger_better <<- rep.int(1.0, eval_len)
290
    best_iter <<- rep.int(-1L, eval_len)
291
    best_score <<- rep.int(-Inf, eval_len)
292
    best_msg <<- list()
293

294
    # Loop through evaluation elements
295
    for (i in seq_len(eval_len)) {
296

297
      # Prepend message
Guolin Ke's avatar
Guolin Ke committed
298
      best_msg <<- c(best_msg, "")
299

300
      # Check if maximization or minimization
301
      if (!env$eval_list[[i]]$higher_better) {
Guolin Ke's avatar
Guolin Ke committed
302
303
        factor_to_bigger_better[i] <<- -1.0
      }
304

Guolin Ke's avatar
Guolin Ke committed
305
    }
306

Guolin Ke's avatar
Guolin Ke committed
307
  }
308

309
  # Create callback
Guolin Ke's avatar
Guolin Ke committed
310
  callback <- function(env, finalize = FALSE) {
311

312
313
314
315
    # Check for empty evaluation
    if (is.null(eval_len)) {
      init(env)
    }
316

317
    # Store iteration
Guolin Ke's avatar
Guolin Ke committed
318
    cur_iter <- env$iteration
319

320
    # Loop through evaluation
321
    for (i in seq_len(eval_len)) {
322

323
      # Store score
Guolin Ke's avatar
Guolin Ke committed
324
      score <- env$eval_list[[i]]$value * factor_to_bigger_better[i]
325

326
327
        # Check if score is better
        if (score > best_score[i]) {
328

329
330
331
          # Store new scores
          best_score[i] <<- score
          best_iter[i] <<- cur_iter
332

333
334
335
          # Prepare to print if verbose
          if (verbose) {
            best_msg[[i]] <<- as.character(merge.eval.string(env))
336
          }
337

338
        } else {
339

340
341
          # Check if early stopping is required
          if (cur_iter - best_iter[i] >= stopping_rounds) {
342

343
344
345
346
347
            # 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]
            }
348

349
350
            # Print message if verbose
            if (isTRUE(verbose)) {
351

352
353
              cat("Early stopping, best iteration is:", "\n")
              cat(best_msg[[i]], "\n")
354

355
            }
356

357
358
359
            # Store best iteration and stop
            env$best_iter <- best_iter[i]
            env$met_early_stop <- TRUE
Guolin Ke's avatar
Guolin Ke committed
360
          }
361

Guolin Ke's avatar
Guolin Ke committed
362
        }
363

Guolin Ke's avatar
Guolin Ke committed
364
      if (!isTRUE(env$met_early_stop) && cur_iter == env$end_iteration) {
365
366
367
368
369
        # 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]
        }
370

371
372
373
374
375
        # Print message if verbose
        if (isTRUE(verbose)) {
          cat("Did not meet early stopping, best iteration is:", "\n")
          cat(best_msg[[i]], "\n")
        }
376

377
378
379
380
        # Store best iteration and stop
        env$best_iter <- best_iter[i]
        env$met_early_stop <- TRUE
      }
Guolin Ke's avatar
Guolin Ke committed
381
382
    }
  }
383

384
385
386
  # Set attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.early.stop"
387

388
  # Return callback
389
  callback
390

Guolin Ke's avatar
Guolin Ke committed
391
392
393
}

# Extract callback names from the list of callbacks
394
395
396
callback.names <- function(cb_list) {
  unlist(lapply(cb_list, attr, "name"))
}
Guolin Ke's avatar
Guolin Ke committed
397
398

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

400
  # Combine two elements
Guolin Ke's avatar
Guolin Ke committed
401
  cb_list <- c(cb_list, cb)
402

403
  # Set names of elements
Guolin Ke's avatar
Guolin Ke committed
404
  names(cb_list) <- callback.names(cb_list)
405

406
407
  # Check for existence
  if ("cb.early.stop" %in% names(cb_list)) {
408

409
410
    # Concatenate existing elements
    cb_list <- c(cb_list, cb_list["cb.early.stop"])
411

412
413
    # Remove only the first one
    cb_list["cb.early.stop"] <- NULL
414

Guolin Ke's avatar
Guolin Ke committed
415
  }
416

417
  # Return element
Guolin Ke's avatar
Guolin Ke committed
418
  cb_list
419

Guolin Ke's avatar
Guolin Ke committed
420
421
422
}

categorize.callbacks <- function(cb_list) {
423

424
  # Check for pre-iteration or post-iteration
Guolin Ke's avatar
Guolin Ke committed
425
426
  list(
    pre_iter = Filter(function(x) {
427
428
429
      pre <- attr(x, "is_pre_iteration")
      !is.null(pre) && pre
    }, cb_list),
Guolin Ke's avatar
Guolin Ke committed
430
    post_iter = Filter(function(x) {
431
432
433
      pre <- attr(x, "is_pre_iteration")
      is.null(pre) || !pre
    }, cb_list)
Guolin Ke's avatar
Guolin Ke committed
434
  )
435

Guolin Ke's avatar
Guolin Ke committed
436
}