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

cb.reset.parameters <- function(new_params) {
18
19
20
21
22
23
24
  
  # Check for parameter list
  if (!is.list(new_params)) {
    stop(sQuote("new_params"), " must be a list")
  }
  
  # Deparse parameter list
25
  pnames  <- gsub("\\.", "_", names(new_params))
Guolin Ke's avatar
Guolin Ke committed
26
  nrounds <- NULL
27

28
  # Run some checks in the beginning
Guolin Ke's avatar
Guolin Ke committed
29
  init <- function(env) {
30
31
    
    # Store boosting rounds
Guolin Ke's avatar
Guolin Ke committed
32
    nrounds <<- env$end_iteration - env$begin_iteration + 1
33
34
    
    # Check for model environment
35
    if (is.null(env$model)) { stop("Env should have a ", sQuote("model")) }
36
    
Guolin Ke's avatar
Guolin Ke committed
37
38
    # Some parameters are not allowed to be changed,
    # since changing them would simply wreck some chaos
39
40
41
42
    not_allowed <- c("num_class", "metric", "boosting_type")
    if (any(pnames %in% not_allowed)) {
      stop("Parameters ", paste0(pnames[pnames %in% not_allowed], collapse = ", "), " cannot be changed during boosting")
    }
43
44
    
    # Check parameter names
Guolin Ke's avatar
Guolin Ke committed
45
    for (n in pnames) {
46
47
      
      # Set name
Guolin Ke's avatar
Guolin Ke committed
48
      p <- new_params[[n]]
49
50
      
      # Check if function for parameter
Guolin Ke's avatar
Guolin Ke committed
51
      if (is.function(p)) {
52
53
54
        
        # Check if requires at least two arguments
        if (length(formals(p)) != 2) {
55
          stop("Parameter ", sQuote(n), " is a function but not of two arguments")
56
57
58
        }
        
        # Check if numeric or character
Guolin Ke's avatar
Guolin Ke committed
59
      } else if (is.numeric(p) || is.character(p)) {
60
61
62
        
        # Check if length is matching
        if (length(p) != nrounds) {
63
          stop("Length of ", sQuote(n), " has to be equal to length of ", sQuote("nrounds"))
64
65
        }
        
Guolin Ke's avatar
Guolin Ke committed
66
      } else {
67
        
68
        stop("Parameter ", sQuote(n), " is not a function or a vector")
69
        
Guolin Ke's avatar
Guolin Ke committed
70
      }
71
      
Guolin Ke's avatar
Guolin Ke committed
72
    }
73
    
Guolin Ke's avatar
Guolin Ke committed
74
  }
75

Guolin Ke's avatar
Guolin Ke committed
76
  callback <- function(env) {
77
78
79
80
81
82
83
    
    # Check if rounds is null
    if (is.null(nrounds)) {
      init(env)
    }
    
    # Store iteration
Guolin Ke's avatar
Guolin Ke committed
84
    i <- env$iteration - env$begin_iteration
85
86
    
    # Apply list on parameters
Guolin Ke's avatar
Guolin Ke committed
87
    pars <- lapply(new_params, function(p) {
88
89
90
      if (is.function(p)) {
        return(p(i, nrounds))
      }
Guolin Ke's avatar
Guolin Ke committed
91
92
      p[i]
    })
93
94
95
96
97
98
    
    # To-do check pars
    if (!is.null(env$model)) {
      env$model$reset_parameter(pars)
    }
    
Guolin Ke's avatar
Guolin Ke committed
99
  }
100
101
102
103
  
  attr(callback, "call") <- match.call()
  attr(callback, "is_pre_iteration") <- TRUE
  attr(callback, "name") <- "cb.reset.parameters"
104
  callback
Guolin Ke's avatar
Guolin Ke committed
105
106
107
}

# Format the evaluation metric string
108
format.eval.string <- function(eval_res, eval_err = NULL) {
109
110
111
112
113
114
115
  
  # Check for empty evaluation string
  if (is.null(eval_res) || length(eval_res) == 0) {
    stop("no evaluation results")
  }
  
  # Check for empty evaluation error
Guolin Ke's avatar
Guolin Ke committed
116
  if (!is.null(eval_err)) {
117
    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
118
  } else {
119
    sprintf("%s\'s %s:%g", eval_res$data_name, eval_res$name, eval_res$value)
Guolin Ke's avatar
Guolin Ke committed
120
  }
121
  
Guolin Ke's avatar
Guolin Ke committed
122
123
}

124
merge.eval.string <- function(env) {
125
126
127
128
129
130
131
132
133
134
  
  # Check length of evaluation list
  if (length(env$eval_list) <= 0) {
    return("")
  }
  
  # Get evaluation
  msg <- list(sprintf("[%d]:", env$iteration))
  
  # Set if evaluation error
135
  is_eval_error <- length(env$eval_err_list) > 0
136
137
  
  # Loop through evaluation list
138
  for (j in seq_along(env$eval_list)) {
139
140
    
    # Store evaluation error
Guolin Ke's avatar
Guolin Ke committed
141
    eval_err <- NULL
142
143
144
145
146
    if (is_eval_err) {
      eval_err <- env$eval_err_list[[j]]
    }
    
    # Set error message
147
    msg <- c(msg, format.eval.string(env$eval_list[[j]], eval_err))
148
    
Guolin Ke's avatar
Guolin Ke committed
149
  }
150
151
152
153
  
  # Return tabulated separated message
  paste0(msg, collapse = "\t")
  
Guolin Ke's avatar
Guolin Ke committed
154
155
}

156
157
158
cb.print.evaluation <- function(period = 1) {
  
  # Create callback
159
  callback <- function(env) {
160
161
    
    # Check if period is at least 1 or more
162
    if (period > 0) {
163
164
      
      # Store iteration
Guolin Ke's avatar
Guolin Ke committed
165
      i <- env$iteration
166
167
      
      # Check if iteration matches moduo
168
      if ((i - 1) %% period == 0 || is.element(i, c(env$begin_iteration, env$end_iteration ))) {
169
170
        
        # Merge evaluation string
171
        msg <- merge.eval.string(env)
172
173
174
175
176
177
        
        # Check if message is existing
        if (nchar(msg) > 0) {
          cat(merge.eval.string(env), "\n")
        }
        
Guolin Ke's avatar
Guolin Ke committed
178
      }
179
      
Guolin Ke's avatar
Guolin Ke committed
180
    }
181
    
Guolin Ke's avatar
Guolin Ke committed
182
  }
183
184
185
186
187
188
  
  # Store attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.print.evaluation"
  
  # Return callback
189
  callback
190
  
Guolin Ke's avatar
Guolin Ke committed
191
192
193
}

cb.record.evaluation <- function() {
194
195
  
  # Create callback
196
  callback <- function(env) {
197
198
199
200
201
202
203
    
    # Return empty if empty evaluation list
    if (length(env$eval_list) <= 0) {
      return()
    }
    
    # Set if evaluation error
204
    is_eval_err <- length(env$eval_err_list) > 0
205
206
    
    # Check length of recorded evaluation
207
    if (length(env$model$record_evals) == 0) {
208
209
      
      # Loop through each evaluation list element
210
      for (j in seq_along(env$eval_list)) {
211
212
        
        # Store names
Guolin Ke's avatar
Guolin Ke committed
213
        data_name <- env$eval_list[[j]]$data_name
214
        name <- env$eval_list[[j]]$name
Guolin Ke's avatar
Guolin Ke committed
215
        env$model$record_evals$start_iter <- env$begin_iteration
216
217
        
        # Check if evaluation record exists
218
        if (is.null(env$model$record_evals[[data_name]])) {
Guolin Ke's avatar
Guolin Ke committed
219
220
          env$model$record_evals[[data_name]] <- list()
        }
221
222
223
224
        
        # 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
225
        env$model$record_evals[[data_name]][[name]]$eval_err <- list()
226
        
Guolin Ke's avatar
Guolin Ke committed
227
      }
228
      
Guolin Ke's avatar
Guolin Ke committed
229
    }
230
231
    
    # Loop through each evaluation list element
232
    for (j in seq_along(env$eval_list)) {
233
234
      
      # Get evaluation data
Guolin Ke's avatar
Guolin Ke committed
235
236
      eval_res <- env$eval_list[[j]]
      eval_err <- NULL
237
238
239
240
241
      if (is_eval_err) {
        eval_err <- env$eval_err_list[[j]]
      }
      
      # Store names
Guolin Ke's avatar
Guolin Ke committed
242
      data_name <- eval_res$data_name
243
244
245
      name <- eval_res$name
      
      # Store evaluation data
Guolin Ke's avatar
Guolin Ke committed
246
247
      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)
248
      
Guolin Ke's avatar
Guolin Ke committed
249
    }
250
    
Guolin Ke's avatar
Guolin Ke committed
251
  }
252
253
254
255
256
257
  
  # Store attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.record.evaluation"
  
  # Return callback
258
  callback
259
  
Guolin Ke's avatar
Guolin Ke committed
260
261
}

262
cb.early.stop <- function(stopping_rounds, verbose = TRUE) {
263
264
  
  # Initialize variables
Guolin Ke's avatar
Guolin Ke committed
265
  factor_to_bigger_better <- NULL
266
267
268
269
270
271
  best_iter <- NULL
  best_score <- NULL
  best_msg <- NULL
  eval_len <- NULL
  
  # Initalization function
Guolin Ke's avatar
Guolin Ke committed
272
  init <- function(env) {
273
274
    
    # Store evaluation length
275
    eval_len <<- length(env$eval_list)
276
277
    
    # Early stopping cannot work without metrics
278
    if (eval_len == 0) {
Guolin Ke's avatar
Guolin Ke committed
279
      stop("For early stopping, valids must have at least one element")
280
    }
281
282
    
    # Check if verbose or not
283
    if (isTRUE(verbose)) {
284
      cat("Will train until there is no improvement in ", stopping_rounds, " rounds.\n\n", sep = "")
285
    }
286
287
    
    # Maximization or minimization task
288
289
290
    factor_to_bigger_better <<- rep.int(1.0, eval_len)
    best_iter <<- rep.int(-1, eval_len)
    best_score <<- rep.int(-Inf, eval_len)
291
292
293
    best_msg <<- list()
    
    # Loop through evaluation elements
294
    for (i in seq_len(eval_len)) {
295
296
      
      # Prepend message
Guolin Ke's avatar
Guolin Ke committed
297
      best_msg <<- c(best_msg, "")
298
299
      
      # Check if maximization or minimization
300
      if (!env$eval_list[[i]]$higher_better) {
Guolin Ke's avatar
Guolin Ke committed
301
302
        factor_to_bigger_better[i] <<- -1.0
      }
303
      
Guolin Ke's avatar
Guolin Ke committed
304
    }
305
    
Guolin Ke's avatar
Guolin Ke committed
306
  }
307
308
  
  # Create callback
Guolin Ke's avatar
Guolin Ke committed
309
  callback <- function(env, finalize = FALSE) {
310
311
312
313
314
315
316
    
    # Check for empty evaluation
    if (is.null(eval_len)) {
      init(env)
    }
    
    # Store iteration
Guolin Ke's avatar
Guolin Ke committed
317
    cur_iter <- env$iteration
318
319
    
    # Loop through evaluation
320
    for (i in seq_len(eval_len)) {
321
322
      
      # Store score
Guolin Ke's avatar
Guolin Ke committed
323
      score <- env$eval_list[[i]]$value * factor_to_bigger_better[i]
324
325
      
      # Check if score is better
326
      if (score > best_score[i]) {
327
328
        
        # Store new scores
Guolin Ke's avatar
Guolin Ke committed
329
        best_score[i] <<- score
330
331
332
        best_iter[i] <<- cur_iter
        
        # Prepare to print if verbose
333
        if (verbose) {
Guolin Ke's avatar
Guolin Ke committed
334
335
          best_msg[[i]] <<- as.character(merge.eval.string(env))
        }
336
        
Guolin Ke's avatar
Guolin Ke committed
337
      } else {
338
339
        
        # Check if early stopping is required
340
        if (cur_iter - best_iter[i] >= stopping_rounds) {
341
342
343
          
          # Check if model is not null
          if (!is.null(env$model)) {
Laurae's avatar
Laurae committed
344
            env$model$best_score <- best_score[i]
345
346
347
348
            env$model$best_iter <- best_iter[i]
          }
          
          # Print message if verbose
349
          if (isTRUE(verbose)) {
350
            
351
352
            cat("Early stopping, best iteration is:", "\n")
            cat(best_msg[[i]], "\n")
353
            
Guolin Ke's avatar
Guolin Ke committed
354
          }
355
356
357
          
          # Store best iteration and stop
          env$best_iter <- best_iter[i]
Guolin Ke's avatar
Guolin Ke committed
358
          env$met_early_stop <- TRUE
359
          
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
    }
365
    
Guolin Ke's avatar
Guolin Ke committed
366
  }
367
368
369
370
371
372
  
  # Set attributes
  attr(callback, "call") <- match.call()
  attr(callback, "name") <- "cb.early.stop"
  
  # Return callback
373
  callback
374
  
Guolin Ke's avatar
Guolin Ke committed
375
376
377
}

# Extract callback names from the list of callbacks
378
callback.names <- function(cb_list) { unlist(lapply(cb_list, attr, "name")) }
Guolin Ke's avatar
Guolin Ke committed
379
380

add.cb <- function(cb_list, cb) {
381
382
  
  # Combine two elements
Guolin Ke's avatar
Guolin Ke committed
383
  cb_list <- c(cb_list, cb)
384
385
  
  # Set names of elements
Guolin Ke's avatar
Guolin Ke committed
386
  names(cb_list) <- callback.names(cb_list)
387
388
389
390
391
392
393
394
395
396
  
  # Check for existence
  if ("cb.early.stop" %in% names(cb_list)) {
    
    # Concatenate existing elements
    cb_list <- c(cb_list, cb_list["cb.early.stop"])
    
    # Remove only the first one
    cb_list["cb.early.stop"] <- NULL
    
Guolin Ke's avatar
Guolin Ke committed
397
  }
398
399
  
  # Return element
Guolin Ke's avatar
Guolin Ke committed
400
  cb_list
401
  
Guolin Ke's avatar
Guolin Ke committed
402
403
404
}

categorize.callbacks <- function(cb_list) {
405
406
  
  # Check for pre-iteration or post-iteration
Guolin Ke's avatar
Guolin Ke committed
407
408
  list(
    pre_iter = Filter(function(x) {
409
        pre <- attr(x, "is_pre_iteration")
410
        !is.null(pre) && pre
Guolin Ke's avatar
Guolin Ke committed
411
412
      }, cb_list),
    post_iter = Filter(function(x) {
413
        pre <- attr(x, "is_pre_iteration")
Guolin Ke's avatar
Guolin Ke committed
414
415
416
        is.null(pre) || !pre
      }, cb_list)
  )
417
  
Guolin Ke's avatar
Guolin Ke committed
418
}