Debian Codegraph @

tests/testthat/test_callbacks.R

raw
1 # More specific testing of callbacks
2 context("callbacks")
3
4 data(agaricus.train, package = 'xgboost')
5 data(agaricus.test, package = 'xgboost')
6 train <- agaricus.train
7 test <- agaricus.test
8
9 n_threads <- 2
10
11 # add some label noise for early stopping tests
12 add.noise <- function(label, frac) {
13 inoise <- sample(length(label), length(label) * frac)
14 label[inoise] <- !label[inoise]
15 label
16 }
17 set.seed(11)
18 ltrain <- add.noise(train$label, 0.2)
19 ltest <- add.noise(test$label, 0.2)
20 dtrain <- xgb.DMatrix(train$data, label = ltrain, nthread = n_threads)
21 dtest <- xgb.DMatrix(test$data, label = ltest, nthread = n_threads)
22 evals <- list(train = dtrain, test = dtest)
23
24
25 err <- function(label, pr) sum((pr > 0.5) != label) / length(label)
26
27 params <- xgb.params(
28 objective = "binary:logistic", eval_metric = "error",
29 max_depth = 2, nthread = n_threads
30 )
31
32
33 test_that("xgb.cb.print.evaluation works as expected for xgb.train", {
34 logs1 <- capture.output({
35 model <- xgb.train(
36 data = dtrain,
37 params = xgb.params(
38 objective = "binary:logistic",
39 eval_metric = "auc",
40 max_depth = 2,
41 nthread = n_threads
42 ),
43 nrounds = 10,
44 evals = list(train = dtrain, test = dtest),
45 callbacks = list(xgb.cb.print.evaluation(period = 1))
46 )
47 })
48 expect_equal(length(logs1), 10)
49 expect_true(all(grepl("^\\[\\d{1,2}\\]\ttrain-auc:0\\.\\d+\ttest-auc:0\\.\\d+\\s*$", logs1)))
50 lapply(seq(1, 10), function(x) expect_true(grepl(paste0("^\\[", x), logs1[x])))
51
52 logs2 <- capture.output({
53 model <- xgb.train(
54 data = dtrain,
55 params = xgb.params(
56 objective = "binary:logistic",
57 eval_metric = "auc",
58 max_depth = 2,
59 nthread = n_threads
60 ),
61 nrounds = 10,
62 evals = list(train = dtrain, test = dtest),
63 callbacks = list(xgb.cb.print.evaluation(period = 2))
64 )
65 })
66 expect_equal(length(logs2), 6)
67 expect_true(all(grepl("^\\[\\d{1,2}\\]\ttrain-auc:0\\.\\d+\ttest-auc:0\\.\\d+\\s*$", logs2)))
68 seq_matches <- c(seq(1, 10, 2), 10)
69 lapply(seq_along(seq_matches), function(x) expect_true(grepl(paste0("^\\[", seq_matches[x]), logs2[x])))
70 })
71
72 test_that("xgb.cb.print.evaluation works as expected for xgb.cv", {
73 logs1 <- capture.output({
74 model <- xgb.cv(
75 data = dtrain,
76 params = xgb.params(
77 objective = "binary:logistic",
78 eval_metric = "auc",
79 max_depth = 2,
80 nthread = n_threads
81 ),
82 nrounds = 10,
83 nfold = 3,
84 callbacks = list(xgb.cb.print.evaluation(period = 1, showsd = TRUE))
85 )
86 })
87 expect_equal(length(logs1), 10)
88 expect_true(all(grepl("^\\[\\d{1,2}\\]\ttrain-auc:0\\.\\d+±0\\.\\d+\ttest-auc:0\\.\\d+±0\\.\\d+\\s*$", logs1)))
89 lapply(seq(1, 10), function(x) expect_true(grepl(paste0("^\\[", x), logs1[x])))
90
91 logs2 <- capture.output({
92 model <- xgb.cv(
93 data = dtrain,
94 params = xgb.params(
95 objective = "binary:logistic",
96 eval_metric = "auc",
97 max_depth = 2,
98 nthread = n_threads
99 ),
100 nrounds = 10,
101 nfold = 3,
102 callbacks = list(xgb.cb.print.evaluation(period = 2, showsd = TRUE))
103 )
104 })
105 expect_equal(length(logs2), 6)
106 expect_true(all(grepl("^\\[\\d{1,2}\\]\ttrain-auc:0\\.\\d+±0\\.\\d+\ttest-auc:0\\.\\d+±0\\.\\d+\\s*$", logs2)))
107 seq_matches <- c(seq(1, 10, 2), 10)
108 lapply(seq_along(seq_matches), function(x) expect_true(grepl(paste0("^\\[", seq_matches[x]), logs2[x])))
109 })
110
111 test_that("xgb.cb.evaluation.log works as expected for xgb.train", {
112 model <- xgb.train(
113 data = dtrain,
114 params = xgb.params(
115 objective = "binary:logistic",
116 eval_metric = "auc",
117 max_depth = 2,
118 nthread = n_threads
119 ),
120 nrounds = 10,
121 verbose = FALSE,
122 evals = list(train = dtrain, test = dtest),
123 callbacks = list(xgb.cb.evaluation.log())
124 )
125 logs <- attributes(model)$evaluation_log
126
127 expect_equal(nrow(logs), 10)
128 expect_equal(colnames(logs), c("iter", "train_auc", "test_auc"))
129 })
130
131 test_that("xgb.cb.evaluation.log works as expected for xgb.cv", {
132 model <- xgb.cv(
133 data = dtrain,
134 params = xgb.params(
135 objective = "binary:logistic",
136 eval_metric = "auc",
137 max_depth = 2,
138 nthread = n_threads
139 ),
140 nrounds = 10,
141 verbose = FALSE,
142 nfold = 3,
143 callbacks = list(xgb.cb.evaluation.log())
144 )
145 logs <- model$evaluation_log
146
147 expect_equal(nrow(logs), 10)
148 expect_equal(
149 colnames(logs),
150 c("iter", "train_auc_mean", "train_auc_std", "test_auc_mean", "test_auc_std")
151 )
152 })
153
154
155 params <- xgb.params(
156 objective = "binary:logistic", eval_metric = "error",
157 max_depth = 4, nthread = n_threads
158 )
159
160 test_that("can store evaluation_log without printing", {
161 expect_silent(
162 bst <- xgb.train(params, dtrain, nrounds = 10, evals = evals, verbose = 0)
163 )
164 expect_false(is.null(attributes(bst)$evaluation_log))
165 expect_false(is.null(attributes(bst)$evaluation_log$train_error))
166 expect_lt(attributes(bst)$evaluation_log[, min(train_error)], 0.2)
167 })
168
169 test_that("xgb.cb.reset.parameters works as expected", {
170
171 # fixed learning_rate
172 params <- c(params, list(learning_rate = 0.9))
173 set.seed(111)
174 bst0 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0)
175 expect_false(is.null(attributes(bst0)$evaluation_log))
176 expect_false(is.null(attributes(bst0)$evaluation_log$train_error))
177
178 # same learning_rate but re-set as a vector parameter in the callback
179 set.seed(111)
180 my_par <- list(learning_rate = c(0.9, 0.9))
181 bst1 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0,
182 callbacks = list(xgb.cb.reset.parameters(my_par)))
183 expect_false(is.null(attributes(bst1)$evaluation_log$train_error))
184 expect_equal(attributes(bst0)$evaluation_log$train_error,
185 attributes(bst1)$evaluation_log$train_error)
186
187 # same learning_rate but re-set via a function in the callback
188 set.seed(111)
189 my_par <- list(learning_rate = function(itr, itr_end) 0.9)
190 bst2 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0,
191 callbacks = list(xgb.cb.reset.parameters(my_par)))
192 expect_false(is.null(attributes(bst2)$evaluation_log$train_error))
193 expect_equal(attributes(bst0)$evaluation_log$train_error,
194 attributes(bst2)$evaluation_log$train_error)
195
196 # different learning_rate re-set as a vector parameter in the callback
197 set.seed(111)
198 my_par <- list(learning_rate = c(0.6, 0.5))
199 bst3 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0,
200 callbacks = list(xgb.cb.reset.parameters(my_par)))
201 expect_false(is.null(attributes(bst3)$evaluation_log$train_error))
202 expect_false(all(attributes(bst0)$evaluation_log$train_error == attributes(bst3)$evaluation_log$train_error))
203
204 # resetting multiple parameters at the same time runs with no error
205 my_par <- list(learning_rate = c(1., 0.5), min_split_loss = c(1, 2), max_depth = c(4, 8))
206 expect_error(
207 bst4 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0,
208 callbacks = list(xgb.cb.reset.parameters(my_par)))
209 , NA) # NA = no error
210 # CV works as well
211 expect_error(
212 bst4 <- xgb.cv(params, dtrain, nfold = 2, nrounds = 2, verbose = 0,
213 callbacks = list(xgb.cb.reset.parameters(my_par)))
214 , NA) # NA = no error
215
216 # expect no learning with 0 learning rate
217 my_par <- list(learning_rate = c(0., 0.))
218 bstX <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0,
219 callbacks = list(xgb.cb.reset.parameters(my_par)))
220 expect_false(is.null(attributes(bstX)$evaluation_log$train_error))
221 er <- unique(attributes(bstX)$evaluation_log$train_error)
222 expect_length(er, 1)
223 expect_gt(er, 0.4)
224 })
225
226 test_that("xgb.cb.save.model works as expected", {
227 files <- c('xgboost_01.json', 'xgboost_02.json', 'xgboost.json')
228 files <- unname(sapply(files, function(f) file.path(tempdir(), f)))
229 for (f in files) if (file.exists(f)) file.remove(f)
230
231 bst <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0,
232 save_period = 1, save_name = file.path(tempdir(), "xgboost_%02d.json"))
233 expect_true(file.exists(files[1]))
234 expect_true(file.exists(files[2]))
235 b1 <- xgb.load(files[1])
236 xgb.model.parameters(b1) <- list(nthread = 2)
237 expect_equal(xgb.get.num.boosted.rounds(b1), 1)
238 b2 <- xgb.load(files[2])
239 xgb.model.parameters(b2) <- list(nthread = 2)
240 expect_equal(xgb.get.num.boosted.rounds(b2), 2)
241
242 xgb.config(b2) <- xgb.config(bst)
243 expect_equal(xgb.config(bst), xgb.config(b2))
244 expect_equal(xgb.save.raw(bst), xgb.save.raw(b2))
245
246 # save_period = 0 saves the last iteration's model
247 bst <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0,
248 save_period = 0, save_name = file.path(tempdir(), 'xgboost.json'))
249 expect_true(file.exists(files[3]))
250 b2 <- xgb.load(files[3])
251 xgb.config(b2) <- xgb.config(bst)
252 expect_equal(xgb.save.raw(bst), xgb.save.raw(b2))
253
254 for (f in files) if (file.exists(f)) file.remove(f)
255 })
256
257 test_that("early stopping xgb.train works", {
258 params <- c(params, list(learning_rate = 0.3))
259 set.seed(11)
260 expect_output(
261 bst <- xgb.train(params, dtrain, nrounds = 20, evals = evals,
262 early_stopping_rounds = 3, maximize = FALSE)
263 , "Stopping. Best iteration")
264 expect_false(is.null(xgb.attr(bst, "best_iteration")))
265 expect_lt(xgb.attr(bst, "best_iteration"), 19)
266
267 pred <- predict(bst, dtest)
268 expect_equal(length(pred), 1611)
269 err_pred <- err(ltest, pred)
270 err_log <- attributes(bst)$evaluation_log[xgb.attr(bst, "best_iteration") + 1, test_error]
271 expect_equal(err_log, err_pred, tolerance = 5e-6)
272
273 set.seed(11)
274 expect_silent(
275 bst0 <- xgb.train(params, dtrain, nrounds = 20, evals = evals,
276 early_stopping_rounds = 3, maximize = FALSE, verbose = 0)
277 )
278 expect_equal(attributes(bst)$evaluation_log, attributes(bst0)$evaluation_log)
279
280 fname <- file.path(tempdir(), "model.ubj")
281 xgb.save(bst, fname)
282 loaded <- xgb.load(fname)
283
284 expect_false(is.null(xgb.attr(loaded, "best_iteration")))
285 expect_equal(xgb.attr(loaded, "best_iteration"), xgb.attr(bst, "best_iteration"))
286 })
287
288 test_that("early stopping using a specific metric works", {
289 set.seed(11)
290 expect_output(
291 bst <- xgb.train(
292 c(
293 within(params, rm("eval_metric")),
294 list(
295 learning_rate = 0.6,
296 eval_metric = "logloss",
297 eval_metric = "auc"
298 )
299 ),
300 dtrain,
301 nrounds = 20,
302 evals = evals,
303 callbacks = list(
304 xgb.cb.early.stop(stopping_rounds = 3, maximize = FALSE, metric_name = 'test_logloss')
305 )
306 )
307 , "Stopping. Best iteration")
308 expect_false(is.null(xgb.attr(bst, "best_iteration")))
309 expect_lt(xgb.attr(bst, "best_iteration"), 19)
310
311 pred <- predict(bst, dtest, iterationrange = c(1, xgb.attr(bst, "best_iteration") + 1))
312 expect_equal(length(pred), 1611)
313 logloss_pred <- sum(-ltest * log(pred) - (1 - ltest) * log(1 - pred)) / length(ltest)
314 logloss_log <- attributes(bst)$evaluation_log[xgb.attr(bst, "best_iteration") + 1, test_logloss]
315 expect_equal(logloss_log, logloss_pred, tolerance = 1e-5)
316 })
317
318 test_that("early stopping works with titanic", {
319 if (!requireNamespace("titanic")) {
320 testthat::skip("Optional testing dependency 'titanic' not found.")
321 }
322 # This test was inspired by https://github.com/dmlc/xgboost/issues/5935
323 # It catches possible issues on noLD R
324 titanic <- titanic::titanic_train
325 titanic$Pclass <- as.factor(titanic$Pclass)
326 dtx <- model.matrix(~ 0 + ., data = titanic[, c("Pclass", "Sex")])
327 dty <- titanic$Survived
328
329 xgb.train(
330 data = xgb.DMatrix(dtx, label = dty, nthread = 1),
331 params = xgb.params(
332 objective = "binary:logistic",
333 eval_metric = "auc",
334 nthread = n_threads
335 ),
336 nrounds = 100,
337 early_stopping_rounds = 3,
338 verbose = 0,
339 evals = list(train = xgb.DMatrix(dtx, label = dty, nthread = 1))
340 )
341
342 expect_true(TRUE) # should not crash
343 })
344
345 test_that("early stopping xgb.cv works", {
346 set.seed(11)
347 expect_output(
348 {
349 cv <- xgb.cv(
350 c(params, list(learning_rate = 0.3)),
351 dtrain,
352 nfold = 5,
353 nrounds = 20,
354 early_stopping_rounds = 3,
355 maximize = FALSE
356 )
357 },
358 "Stopping. Best iteration"
359 )
360 expect_false(is.null(cv$early_stop$best_iteration))
361 expect_lt(cv$early_stop$best_iteration, 19)
362 # the best error is min error:
363 expect_true(cv$evaluation_log[, test_error_mean[cv$early_stop$best_iteration] == min(test_error_mean)])
364 })
365
366 test_that("prediction in xgb.cv works", {
367 params <- c(params, list(learning_rate = 0.5))
368 set.seed(11)
369 nrounds <- 4
370 cv <- xgb.cv(params, dtrain, nfold = 5, nrounds = nrounds, prediction = TRUE, verbose = 0)
371 expect_false(is.null(cv$evaluation_log))
372 expect_false(is.null(cv$cv_predict$pred))
373 expect_length(cv$cv_predict$pred, nrow(train$data))
374 err_pred <- mean(sapply(cv$folds, function(f) mean(err(ltrain[f], cv$cv_predict$pred[f]))))
375 err_log <- cv$evaluation_log[nrounds, test_error_mean]
376 expect_equal(err_pred, err_log, tolerance = 1e-6)
377
378 # save CV models
379 set.seed(11)
380 cvx <- xgb.cv(params, dtrain, nfold = 5, nrounds = nrounds, prediction = TRUE, verbose = 0,
381 callbacks = list(xgb.cb.cv.predict(save_models = TRUE)))
382 expect_equal(cv$evaluation_log, cvx$evaluation_log)
383 expect_length(cvx$cv_predict$models, 5)
384 expect_true(all(sapply(cvx$cv_predict$models, class) == 'xgb.Booster'))
385 })
386
387 test_that("prediction in xgb.cv works for gblinear too", {
388 set.seed(11)
389 p <- xgb.params(
390 booster = 'gblinear',
391 objective = "reg:logistic",
392 learning_rate = 0.5,
393 nthread = n_threads
394 )
395 cv <- xgb.cv(p, dtrain, nfold = 5, nrounds = 2, prediction = TRUE, verbose = 0)
396 expect_false(is.null(cv$evaluation_log))
397 expect_false(is.null(cv$cv_predict$pred))
398 expect_length(cv$cv_predict$pred, nrow(train$data))
399 })
400
401 test_that("prediction in early-stopping xgb.cv works", {
402 params <- c(params, list(learning_rate = 0.1, base_score = 0.5))
403 set.seed(11)
404 expect_output(
405 cv <- xgb.cv(params, dtrain, nfold = 5, nrounds = 20,
406 early_stopping_rounds = 5, maximize = FALSE, stratified = FALSE,
407 prediction = TRUE, verbose = TRUE)
408 , "Stopping. Best iteration")
409
410 expect_false(is.null(cv$early_stop$best_iteration))
411 expect_lt(cv$early_stop$best_iteration, 19)
412 expect_false(is.null(cv$evaluation_log))
413 expect_false(is.null(cv$cv_predict$pred))
414 expect_length(cv$cv_predict$pred, nrow(train$data))
415
416 err_pred <- mean(sapply(cv$folds, function(f) mean(err(ltrain[f], cv$cv_predict$pred[f]))))
417 err_log <- cv$evaluation_log[cv$early_stop$best_iteration, test_error_mean]
418 expect_equal(err_pred, err_log, tolerance = 1e-6)
419 err_log_last <- cv$evaluation_log[cv$niter, test_error_mean]
420 expect_gt(abs(err_pred - err_log_last), 1e-4)
421 })
422
423 test_that("prediction in xgb.cv for softprob works", {
424 lb <- as.numeric(iris$Species) - 1
425 set.seed(11)
426 expect_warning(
427 {
428 cv <- xgb.cv(
429 data = xgb.DMatrix(as.matrix(iris[, -5]), label = lb, nthread = 1),
430 nfold = 4,
431 nrounds = 5,
432 params = xgb.params(
433 objective = "multi:softprob",
434 num_class = 3,
435 learning_rate = 0.5,
436 max_depth = 3,
437 nthread = n_threads,
438 subsample = 0.8,
439 min_split_loss = 2
440 ),
441 verbose = 0,
442 prediction = TRUE
443 )
444 },
445 NA
446 )
447 expect_false(is.null(cv$cv_predict$pred))
448 expect_equal(dim(cv$cv_predict$pred), c(nrow(iris), 3))
449 expect_lt(diff(range(rowSums(cv$cv_predict$pred))), 1e-6)
450 })
451
452 test_that("prediction in xgb.cv works for multi-quantile", {
453 data(mtcars)
454 y <- mtcars$mpg
455 x <- as.matrix(mtcars[, -1])
456 dm <- xgb.DMatrix(x, label = y, nthread = 1)
457 cv <- xgb.cv(
458 data = dm,
459 params = xgb.params(
460 objective = "reg:quantileerror",
461 quantile_alpha = c(0.1, 0.2, 0.5, 0.8, 0.9),
462 nthread = 1
463 ),
464 nrounds = 5,
465 nfold = 3,
466 prediction = TRUE,
467 verbose = 0
468 )
469 expect_equal(dim(cv$cv_predict$pred), c(nrow(x), 5))
470 })
471
472 test_that("prediction in xgb.cv works for multi-output", {
473 data(mtcars)
474 y <- mtcars$mpg
475 x <- as.matrix(mtcars[, -1])
476 dm <- xgb.DMatrix(x, label = cbind(y, -y), nthread = 1)
477 cv <- xgb.cv(
478 data = dm,
479 params = xgb.params(
480 tree_method = "hist",
481 multi_strategy = "multi_output_tree",
482 objective = "reg:squarederror",
483 nthread = n_threads
484 ),
485 nrounds = 5,
486 nfold = 3,
487 prediction = TRUE,
488 verbose = 0
489 )
490 expect_equal(dim(cv$cv_predict$pred), c(nrow(x), 2))
491 })
492
493 test_that("prediction in xgb.cv works for multi-quantile", {
494 data(mtcars)
495 y <- mtcars$mpg
496 x <- as.matrix(mtcars[, -1])
497 dm <- xgb.DMatrix(x, label = y, nthread = 1)
498 cv <- xgb.cv(
499 data = dm,
500 params = xgb.params(
501 objective = "reg:quantileerror",
502 quantile_alpha = c(0.1, 0.2, 0.5, 0.8, 0.9),
503 nthread = 1
504 ),
505 nrounds = 5,
506 nfold = 3,
507 prediction = TRUE,
508 verbose = 0
509 )
510 expect_equal(dim(cv$cv_predict$pred), c(nrow(x), 5))
511 })
512
513 test_that("prediction in xgb.cv works for multi-output", {
514 data(mtcars)
515 y <- mtcars$mpg
516 x <- as.matrix(mtcars[, -1])
517 dm <- xgb.DMatrix(x, label = cbind(y, -y), nthread = 1)
518 cv <- xgb.cv(
519 data = dm,
520 params = xgb.params(
521 tree_method = "hist",
522 multi_strategy = "multi_output_tree",
523 objective = "reg:squarederror",
524 nthread = n_threads
525 ),
526 nrounds = 5,
527 nfold = 3,
528 prediction = TRUE,
529 verbose = 0
530 )
531 expect_equal(dim(cv$cv_predict$pred), c(nrow(x), 2))
532 })