Debian Codegraph @

tests/testthat/test_basic.R

raw
1 context("basic functions")
2
3 data(agaricus.train, package = "xgboost")
4 data(agaricus.test, package = "xgboost")
5 train <- agaricus.train
6 test <- agaricus.test
7 set.seed(1994)
8
9 # disable some tests for Win32
10 windows_flag <- .Platform$OS.type == "windows" &&
11 .Machine$sizeof.pointer != 8
12 solaris_flag <- (Sys.info()["sysname"] == "SunOS")
13 n_threads <- 1
14
15
16 test_that("train and predict binary classification", {
17 nrounds <- 2
18 expect_output(
19 bst <- xgb.train(
20 data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
21 nrounds = nrounds,
22 params = xgb.params(
23 max_depth = 2,
24 learning_rate = 1,
25 nthread = n_threads,
26 objective = "binary:logistic",
27 eval_metric = "error"
28 ),
29 evals = list(train = xgb.DMatrix(train$data, label = train$label, nthread = 1))
30 ),
31 "train-error"
32 )
33 expect_equal(class(bst), "xgb.Booster")
34 expect_equal(xgb.get.num.boosted.rounds(bst), nrounds)
35 expect_false(is.null(attributes(bst)$evaluation_log))
36 expect_equal(nrow(attributes(bst)$evaluation_log), nrounds)
37 expect_lt(attributes(bst)$evaluation_log[, min(train_error)], 0.03)
38
39 pred <- predict(bst, test$data)
40 expect_length(pred, 1611)
41
42 pred1 <- predict(bst, train$data, iterationrange = c(1, 1))
43 expect_length(pred1, 6513)
44 err_pred1 <- sum((pred1 > 0.5) != train$label) / length(train$label)
45 err_log <- attributes(bst)$evaluation_log[1, train_error]
46 expect_lt(abs(err_pred1 - err_log), 10e-6)
47 })
48
49 test_that("parameter validation works", {
50 p <- list(foo = "bar")
51 nrounds <- 1
52 set.seed(1994)
53
54 d <- cbind(
55 x1 = rnorm(10),
56 x2 = rnorm(10),
57 x3 = rnorm(10)
58 )
59 y <- d[, "x1"] + d[, "x2"]^2 +
60 ifelse(d[, "x3"] > .5, d[, "x3"]^2, 2^d[, "x3"]) +
61 rnorm(10)
62 dtrain <- xgb.DMatrix(data = d, label = y, nthread = n_threads)
63
64 correct <- function() {
65 params <- list(
66 max_depth = 2,
67 booster = "dart",
68 rate_drop = 0.5,
69 one_drop = TRUE,
70 nthread = n_threads,
71 objective = "reg:squarederror"
72 )
73 xgb.train(params = params, data = dtrain, nrounds = nrounds)
74 }
75 expect_silent(correct())
76 incorrect <- function() {
77 params <- list(
78 max_depth = 2,
79 booster = "dart",
80 rate_drop = 0.5,
81 one_drop = TRUE,
82 objective = "reg:squarederror",
83 nthread = n_threads,
84 foo = "bar",
85 bar = "foo"
86 )
87 output <- capture.output(
88 xgb.train(params = params, data = dtrain, nrounds = nrounds),
89 type = "message"
90 )
91 print(output)
92 }
93 expect_output(incorrect(), '\\\\"bar\\\\", \\\\"foo\\\\"')
94 })
95
96
97 test_that("dart prediction works", {
98 nrounds <- 32
99 set.seed(1994)
100
101 d <- cbind(
102 x1 = rnorm(100),
103 x2 = rnorm(100),
104 x3 = rnorm(100)
105 )
106 y <- d[, "x1"] + d[, "x2"]^2 +
107 ifelse(d[, "x3"] > .5, d[, "x3"]^2, 2^d[, "x3"]) +
108 rnorm(100)
109
110 set.seed(1994)
111 booster_by_xgboost <- xgb.train(
112 data = xgb.DMatrix(d, label = y, nthread = 1),
113 nrounds = nrounds,
114 params = xgb.params(
115 max_depth = 2,
116 booster = "dart",
117 rate_drop = 0.5,
118 one_drop = TRUE,
119 learning_rate = 1,
120 nthread = n_threads,
121 objective = "reg:squarederror"
122 )
123 )
124 pred_by_xgboost_0 <- predict(booster_by_xgboost, newdata = d, iterationrange = NULL)
125 pred_by_xgboost_1 <- predict(booster_by_xgboost, newdata = d, iterationrange = c(1, nrounds))
126 expect_true(all(matrix(pred_by_xgboost_0, byrow = TRUE) == matrix(pred_by_xgboost_1, byrow = TRUE)))
127
128 pred_by_xgboost_2 <- predict(booster_by_xgboost, newdata = d, training = TRUE)
129 expect_false(all(matrix(pred_by_xgboost_0, byrow = TRUE) == matrix(pred_by_xgboost_2, byrow = TRUE)))
130
131 set.seed(1994)
132 dtrain <- xgb.DMatrix(data = d, label = y, nthread = n_threads)
133 booster_by_train <- xgb.train(
134 params = xgb.params(
135 booster = "dart",
136 max_depth = 2,
137 learning_rate = 1,
138 rate_drop = 0.5,
139 one_drop = TRUE,
140 nthread = n_threads,
141 objective = "reg:squarederror"
142 ),
143 data = dtrain,
144 nrounds = nrounds
145 )
146 pred_by_train_0 <- predict(booster_by_train, newdata = dtrain, iterationrange = NULL)
147 pred_by_train_1 <- predict(booster_by_train, newdata = dtrain, iterationrange = c(1, nrounds))
148 pred_by_train_2 <- predict(booster_by_train, newdata = dtrain, training = TRUE)
149
150 expect_equal(pred_by_train_0, pred_by_xgboost_0, tolerance = 1e-6)
151 expect_equal(pred_by_train_1, pred_by_xgboost_1, tolerance = 1e-6)
152 expect_true(all(matrix(pred_by_train_2, byrow = TRUE) == matrix(pred_by_xgboost_2, byrow = TRUE)))
153 })
154
155 test_that("train and predict softprob", {
156 lb <- as.numeric(iris$Species) - 1
157 set.seed(11)
158 expect_output(
159 bst <- xgb.train(
160 data = xgb.DMatrix(as.matrix(iris[, -5]), label = lb, nthread = 1),
161 nrounds = 5,
162 params = xgb.params(
163 max_depth = 3, learning_rate = 0.5, nthread = n_threads,
164 objective = "multi:softprob", num_class = 3, eval_metric = "merror"
165 ),
166 evals = list(train = xgb.DMatrix(as.matrix(iris[, -5]), label = lb, nthread = 1))
167 ),
168 "train-merror"
169 )
170 expect_false(is.null(attributes(bst)$evaluation_log))
171 expect_lt(attributes(bst)$evaluation_log[, min(train_merror)], 0.025)
172 expect_equal(xgb.get.num.boosted.rounds(bst), 5)
173 pred <- predict(bst, as.matrix(iris[, -5]))
174 expect_length(pred, nrow(iris) * 3)
175 # row sums add up to total probability of 1:
176 expect_equal(rowSums(pred), rep(1, nrow(iris)), tolerance = 1e-7)
177 # manually calculate error at the last iteration:
178 mpred <- predict(bst, as.matrix(iris[, -5]))
179 expect_equal(mpred, pred)
180 pred_labels <- max.col(mpred) - 1
181 err <- sum(pred_labels != lb) / length(lb)
182 expect_equal(attributes(bst)$evaluation_log[5, train_merror], err, tolerance = 5e-6)
183 # manually calculate error at the 1st iteration:
184 mpred <- predict(bst, as.matrix(iris[, -5]), iterationrange = c(1, 1))
185 pred_labels <- max.col(mpred) - 1
186 err <- sum(pred_labels != lb) / length(lb)
187 expect_equal(attributes(bst)$evaluation_log[1, train_merror], err, tolerance = 5e-6)
188
189 mpred1 <- predict(bst, as.matrix(iris[, -5]), iterationrange = c(1, 1))
190 expect_equal(mpred, mpred1)
191
192 d <- cbind(
193 x1 = rnorm(100),
194 x2 = rnorm(100),
195 x3 = rnorm(100)
196 )
197 y <- sample.int(10, 100, replace = TRUE) - 1
198 dtrain <- xgb.DMatrix(data = d, label = y, nthread = n_threads)
199 booster <- xgb.train(
200 params = xgb.params(
201 objective = "multi:softprob",
202 num_class = 10,
203 tree_method = "hist",
204 nthread = n_threads
205 ),
206 data = dtrain,
207 nrounds = 4
208 )
209 predt <- predict(booster, as.matrix(d), strict_shape = FALSE)
210 expect_equal(ncol(predt), 10)
211 expect_equal(rowSums(predt), rep(1, 100), tolerance = 1e-7)
212 })
213
214 test_that("train and predict softmax", {
215 lb <- as.numeric(iris$Species) - 1
216 set.seed(11)
217 expect_output(
218 bst <- xgb.train(
219 data = xgb.DMatrix(as.matrix(iris[, -5]), label = lb, nthread = 1),
220 nrounds = 5,
221 params = xgb.params(
222 max_depth = 3, learning_rate = 0.5, nthread = n_threads,
223 objective = "multi:softmax", num_class = 3, eval_metric = "merror"
224 ),
225 evals = list(train = xgb.DMatrix(as.matrix(iris[, -5]), label = lb, nthread = 1))
226 ),
227 "train-merror"
228 )
229 expect_false(is.null(attributes(bst)$evaluation_log))
230 expect_lt(attributes(bst)$evaluation_log[, min(train_merror)], 0.025)
231 expect_equal(xgb.get.num.boosted.rounds(bst), 5)
232
233 pred <- predict(bst, as.matrix(iris[, -5]))
234 expect_length(pred, nrow(iris))
235 err <- sum(pred != lb) / length(lb)
236 expect_equal(attributes(bst)$evaluation_log[5, train_merror], err, tolerance = 5e-6)
237 })
238
239 test_that("train and predict RF", {
240 set.seed(11)
241 lb <- train$label
242 # single iteration
243 bst <- xgb.train(
244 data = xgb.DMatrix(train$data, label = lb, nthread = 1),
245 nrounds = 1,
246 params = xgb.params(
247 max_depth = 5,
248 nthread = n_threads,
249 objective = "binary:logistic", eval_metric = "error",
250 num_parallel_tree = 20, subsample = 0.6, colsample_bytree = 0.1
251 ),
252 evals = list(train = xgb.DMatrix(train$data, label = lb, nthread = 1)),
253 verbose = 0
254 )
255 expect_equal(xgb.get.num.boosted.rounds(bst), 1)
256
257 pred <- predict(bst, train$data)
258 pred_err <- sum((pred > 0.5) != lb) / length(lb)
259 expect_lt(abs(attributes(bst)$evaluation_log[1, train_error] - pred_err), 10e-6)
260 # expect_lt(pred_err, 0.03)
261
262 pred <- predict(bst, train$data, iterationrange = c(1, 1))
263 pred_err_20 <- sum((pred > 0.5) != lb) / length(lb)
264 expect_equal(pred_err_20, pred_err)
265 })
266
267 test_that("train and predict RF with softprob", {
268 lb <- as.numeric(iris$Species) - 1
269 nrounds <- 15
270 set.seed(11)
271 bst <- xgb.train(
272 data = xgb.DMatrix(as.matrix(iris[, -5]), label = lb, nthread = 1),
273 nrounds = nrounds,
274 verbose = 0,
275 params = xgb.params(
276 max_depth = 3,
277 learning_rate = 0.9,
278 nthread = n_threads,
279 objective = "multi:softprob",
280 eval_metric = "merror",
281 num_class = 3,
282 num_parallel_tree = 4,
283 subsample = 0.5,
284 colsample_bytree = 0.5
285 ),
286 evals = list(train = xgb.DMatrix(as.matrix(iris[, -5]), label = lb, nthread = 1))
287 )
288 expect_equal(xgb.get.num.boosted.rounds(bst), 15)
289 # predict for all iterations:
290 pred <- predict(bst, as.matrix(iris[, -5]))
291 expect_equal(dim(pred), c(nrow(iris), 3))
292 pred_labels <- max.col(pred) - 1
293 err <- sum(pred_labels != lb) / length(lb)
294 expect_equal(attributes(bst)$evaluation_log[nrounds, train_merror], err, tolerance = 5e-6)
295 # predict for 7 iterations and adjust for 4 parallel trees per iteration
296 pred <- predict(bst, as.matrix(iris[, -5]), iterationrange = c(1, 7))
297 err <- sum((max.col(pred) - 1) != lb) / length(lb)
298 expect_equal(attributes(bst)$evaluation_log[7, train_merror], err, tolerance = 5e-6)
299 })
300
301 test_that("use of multiple eval metrics works", {
302 expect_output(
303 bst <- xgb.train(
304 data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
305 nrounds = 2,
306 params = list(
307 max_depth = 2,
308 learning_rate = 1, nthread = n_threads, objective = "binary:logistic",
309 eval_metric = "error", eval_metric = "auc", eval_metric = "logloss"
310 ),
311 evals = list(train = xgb.DMatrix(train$data, label = train$label, nthread = 1))
312 ),
313 "train-error.*train-auc.*train-logloss"
314 )
315 expect_false(is.null(attributes(bst)$evaluation_log))
316 expect_equal(dim(attributes(bst)$evaluation_log), c(2, 4))
317 expect_equal(colnames(attributes(bst)$evaluation_log), c("iter", "train_error", "train_auc", "train_logloss"))
318 expect_output(
319 bst2 <- xgb.train(
320 data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
321 nrounds = 2,
322 params = xgb.params(
323 max_depth = 2,
324 learning_rate = 1,
325 nthread = n_threads,
326 objective = "binary:logistic",
327 eval_metric = list("error", "auc", "logloss")
328 ),
329 evals = list(train = xgb.DMatrix(train$data, label = train$label, nthread = 1))
330 ),
331 "train-error.*train-auc.*train-logloss"
332 )
333 expect_false(is.null(attributes(bst2)$evaluation_log))
334 expect_equal(dim(attributes(bst2)$evaluation_log), c(2, 4))
335 expect_equal(colnames(attributes(bst2)$evaluation_log), c("iter", "train_error", "train_auc", "train_logloss"))
336 })
337
338
339 test_that("training continuation works", {
340 dtrain <- xgb.DMatrix(train$data, label = train$label, nthread = n_threads)
341 evals <- list(train = dtrain)
342 params <- xgb.params(
343 objective = "binary:logistic", max_depth = 2, learning_rate = 1, nthread = n_threads
344 )
345
346 # for the reference, use 4 iterations at once:
347 set.seed(11)
348 bst <- xgb.train(params, dtrain, nrounds = 4, evals = evals, verbose = 0)
349 # first two iterations:
350 set.seed(11)
351 bst1 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0)
352 # continue for two more:
353 bst2 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0, xgb_model = bst1)
354 if (!windows_flag && !solaris_flag) {
355 expect_equal(xgb.save.raw(bst), xgb.save.raw(bst2))
356 }
357 expect_false(is.null(attributes(bst2)$evaluation_log))
358 expect_equal(dim(attributes(bst2)$evaluation_log), c(4, 2))
359 expect_equal(attributes(bst2)$evaluation_log, attributes(bst)$evaluation_log)
360 # test continuing from raw model data
361 bst2 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0, xgb_model = xgb.save.raw(bst1))
362 if (!windows_flag && !solaris_flag) {
363 expect_equal(xgb.save.raw(bst), xgb.save.raw(bst2))
364 }
365 expect_equal(dim(attributes(bst2)$evaluation_log), c(2, 2))
366 # test continuing from a model in file
367 fname <- file.path(tempdir(), "xgboost.json")
368 xgb.save(bst1, fname)
369 bst2 <- xgb.train(params, dtrain, nrounds = 2, evals = evals, verbose = 0, xgb_model = fname)
370 if (!windows_flag && !solaris_flag) {
371 expect_equal(xgb.save.raw(bst), xgb.save.raw(bst2))
372 }
373 expect_equal(dim(attributes(bst2)$evaluation_log), c(2, 2))
374 })
375
376 test_that("xgb.cv works", {
377 set.seed(11)
378 expect_output(
379 cv <- xgb.cv(
380 data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
381 nfold = 5,
382 nrounds = 2,
383 params = xgb.params(
384 max_depth = 2,
385 learning_rate = 1.,
386 nthread = n_threads,
387 objective = "binary:logistic",
388 eval_metric = "error"
389 ),
390 verbose = TRUE
391 ),
392 "train-error:"
393 )
394 expect_is(cv, "xgb.cv.synchronous")
395 expect_false(is.null(cv$evaluation_log))
396 expect_lt(cv$evaluation_log[, min(test_error_mean)], 0.03)
397 expect_lt(cv$evaluation_log[, min(test_error_std)], 0.0085)
398 expect_equal(cv$niter, 2)
399 expect_false(is.null(cv$folds) && is.list(cv$folds))
400 expect_length(cv$folds, 5)
401 expect_false(is.null(cv$params) && is.list(cv$params))
402 expect_false(is.null(cv$call))
403 })
404
405 test_that("xgb.cv invalid inputs", {
406 data("mtcars")
407 y <- mtcars$mpg
408 x_df <- mtcars[, -1]
409
410 expect_error(
411 cv <- xgb.cv(
412 data = xgb.QuantileDMatrix(x_df, label = y),
413 nfold = 5,
414 nrounds = 2,
415 params = xgb.params(
416 max_depth = 2,
417 nthread = n_threads
418 )
419 ),
420 regexp = ".*QuantileDMatrix.*"
421 )
422 expect_error(
423 cv <- xgb.cv(
424 data = xgb.DMatrix(x_df, label = y),
425 nfold = 5,
426 nrounds = 2,
427 params = xgb.params(
428 max_depth = 2,
429 nthread = n_threads,
430 ),
431 callbacks = list(
432 xgb.cb.early.stop(stopping_rounds = 3, save_best = TRUE)
433 )
434 ),
435 regexp = ".*save_best.*"
436 )
437 })
438
439 test_that("xgb.cv works with stratified folds", {
440 dtrain <- xgb.DMatrix(train$data, label = train$label, nthread = n_threads)
441 set.seed(314159)
442 cv <- xgb.cv(
443 data = dtrain,
444 nrounds = 2,
445 nfold = 5,
446 params = xgb.params(
447 max_depth = 2,
448 nthread = n_threads,
449 objective = "binary:logistic"
450 ),
451 verbose = FALSE, stratified = FALSE
452 )
453 set.seed(314159)
454 cv2 <- xgb.cv(
455 data = dtrain,
456 nfold = 5,
457 nrounds = 2,
458 params = xgb.params(
459 max_depth = 2,
460 nthread = n_threads,
461 objective = "binary:logistic"
462 ),
463 verbose = FALSE, stratified = TRUE
464 )
465 # Stratified folds should result in a different evaluation logs
466 expect_true(all(cv$evaluation_log[, test_logloss_mean] != cv2$evaluation_log[, test_logloss_mean]))
467 })
468
469 test_that("train and predict with non-strict classes", {
470 # standard dense matrix input
471 train_dense <- as.matrix(train$data)
472 bst <- xgb.train(
473 data = xgb.DMatrix(train_dense, label = train$label, nthread = 1),
474 nrounds = 2,
475 params = xgb.params(
476 max_depth = 2,
477 nthread = n_threads,
478 objective = "binary:logistic"
479 ),
480 verbose = 0
481 )
482 pr0 <- predict(bst, train_dense)
483
484 # dense matrix-like input of non-matrix class
485 class(train_dense) <- "shmatrix"
486 expect_true(is.matrix(train_dense))
487 expect_error(
488 bst <- xgb.train(
489 data = xgb.DMatrix(train_dense, label = train$label, nthread = 1),
490 nrounds = 2,
491 params = xgb.params(
492 max_depth = 2,
493 nthread = n_threads,
494 objective = "binary:logistic"
495 ),
496 verbose = 0
497 ),
498 regexp = NA
499 )
500 expect_error(pr <- predict(bst, train_dense), regexp = NA)
501 expect_equal(pr0, pr)
502
503 # dense matrix-like input of non-matrix class with some inheritance
504 class(train_dense) <- c("pphmatrix", "shmatrix")
505 expect_true(is.matrix(train_dense))
506 expect_error(
507 bst <- xgb.train(
508 data = xgb.DMatrix(train_dense, label = train$label, nthread = 1),
509 nrounds = 2,
510 params = xgb.params(
511 max_depth = 2,
512 nthread = n_threads,
513 objective = "binary:logistic"
514 ),
515 verbose = 0
516 ),
517 regexp = NA
518 )
519 expect_error(pr <- predict(bst, train_dense), regexp = NA)
520 expect_equal(pr0, pr)
521
522 # when someone inherits from xgb.Booster, it should still be possible to use it as xgb.Booster
523 class(bst) <- c("super.Booster", "xgb.Booster")
524 expect_error(pr <- predict(bst, train_dense), regexp = NA)
525 expect_equal(pr0, pr)
526 })
527
528 test_that("max_delta_step works", {
529 dtrain <- xgb.DMatrix(
530 agaricus.train$data, label = agaricus.train$label, nthread = n_threads
531 )
532 evals <- list(train = dtrain)
533 params <- xgb.params(
534 objective = "binary:logistic", eval_metric = "logloss", max_depth = 2,
535 nthread = n_threads,
536 learning_rate = 0.5
537 )
538 nrounds <- 5
539 # model with no restriction on max_delta_step
540 bst1 <- xgb.train(params, dtrain, nrounds, evals = evals, verbose = 0)
541 # model with restricted max_delta_step
542 bst2 <- xgb.train(c(params, list(max_delta_step = 1)), dtrain, nrounds, evals = evals, verbose = 0)
543 # the no-restriction model is expected to have consistently lower loss during the initial iterations
544 expect_true(all(attributes(bst1)$evaluation_log$train_logloss < attributes(bst2)$evaluation_log$train_logloss))
545 expect_lt(mean(attributes(bst1)$evaluation_log$train_logloss) / mean(attributes(bst2)$evaluation_log$train_logloss), 0.8)
546 })
547
548 test_that("colsample_bytree works", {
549 # Randomly generate data matrix by sampling from uniform distribution [-1, 1]
550 set.seed(1)
551 train_x <- matrix(runif(1000, min = -1, max = 1), ncol = 100)
552 train_y <- as.numeric(rowSums(train_x) > 0)
553 test_x <- matrix(runif(1000, min = -1, max = 1), ncol = 100)
554 test_y <- as.numeric(rowSums(test_x) > 0)
555 colnames(train_x) <- paste0("Feature_", sprintf("%03d", 1:100))
556 colnames(test_x) <- paste0("Feature_", sprintf("%03d", 1:100))
557 dtrain <- xgb.DMatrix(train_x, label = train_y, nthread = n_threads)
558 dtest <- xgb.DMatrix(test_x, label = test_y, nthread = n_threads)
559 evals <- list(train = dtrain, eval = dtest)
560 ## Use colsample_bytree = 0.01, so that roughly one out of 100 features is chosen for
561 ## each tree
562 params <- xgb.params(
563 max_depth = 2, learning_rate = 0, nthread = n_threads,
564 colsample_bytree = 0.01, objective = "binary:logistic",
565 eval_metric = "auc"
566 )
567 set.seed(2)
568 bst <- xgb.train(params, dtrain, nrounds = 100, evals = evals, verbose = 0)
569 xgb.importance(model = bst)
570 # If colsample_bytree works properly, a variety of features should be used
571 # in the 100 trees
572 expect_gte(nrow(xgb.importance(model = bst)), 28)
573 })
574
575 test_that("Configuration works", {
576 bst <- xgb.train(
577 data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
578 nrounds = 2,
579 params = xgb.params(
580 max_depth = 2,
581 nthread = n_threads,
582 objective = "binary:logistic"
583 )
584 )
585 config <- xgb.config(bst)
586 xgb.config(bst) <- config
587 reloaded_config <- xgb.config(bst)
588 expect_equal(config, reloaded_config)
589 })
590
591 test_that("strict_shape works", {
592 n_rounds <- 2
593
594 test_strict_shape <- function(bst, X, n_groups) {
595 predt <- predict(bst, X, strict_shape = TRUE)
596 margin <- predict(bst, X, outputmargin = TRUE, strict_shape = TRUE)
597 contri <- predict(bst, X, predcontrib = TRUE, strict_shape = TRUE)
598 interact <- predict(bst, X, predinteraction = TRUE, strict_shape = TRUE)
599 leaf <- predict(bst, X, predleaf = TRUE, strict_shape = TRUE)
600
601 n_rows <- nrow(X)
602 n_cols <- ncol(X)
603
604 expect_equal(dim(predt), c(n_rows, n_groups))
605 expect_equal(dim(margin), c(n_rows, n_groups))
606 expect_equal(dim(contri), c(n_rows, n_groups, n_cols + 1))
607 expect_equal(dim(interact), c(n_rows, n_groups, n_cols + 1, n_cols + 1))
608 expect_equal(dim(leaf), c(n_rows, n_rounds, n_groups, 1))
609
610 if (n_groups != 1) {
611 for (g in seq_len(n_groups)) {
612 expect_lt(max(abs(rowSums(contri[, g, ]) - margin[, g])), 1e-5)
613 }
614
615 leaf_no_strict <- predict(bst, X, strict_shape = FALSE, predleaf = TRUE)
616 for (g in seq_len(n_groups)) {
617 g_mask <- rep(FALSE, n_groups)
618 g_mask[g] <- TRUE
619 expect_equal(
620 leaf[, , g, 1L],
621 leaf_no_strict[, g_mask]
622 )
623 }
624 }
625 }
626
627 test_iris <- function() {
628 y <- as.numeric(iris$Species) - 1
629 X <- as.matrix(iris[, -5])
630
631 bst <- xgb.train(
632 data = xgb.DMatrix(X, label = y, nthread = 1),
633 nrounds = n_rounds,
634 params = xgb.params(
635 max_depth = 2, nthread = n_threads,
636 objective = "multi:softprob", num_class = 3
637 )
638 )
639
640 test_strict_shape(bst, X, 3)
641 }
642
643
644 test_agaricus <- function() {
645 data(agaricus.train, package = "xgboost")
646 X <- agaricus.train$data
647 y <- agaricus.train$label
648
649 bst <- xgb.train(
650 data = xgb.DMatrix(X, label = y, nthread = 1),
651 nrounds = n_rounds,
652 params = xgb.params(
653 max_depth = 2, nthread = n_threads,
654 objective = "binary:logistic"
655 )
656 )
657
658 test_strict_shape(bst, X, 1)
659 }
660
661 test_iris()
662 test_agaricus()
663 })
664
665 test_that("'predict' accepts CSR data", {
666 X <- agaricus.train$data
667 y <- agaricus.train$label
668 x_csc <- as(X[1L, , drop = FALSE], "CsparseMatrix")
669 x_csr <- as(x_csc, "RsparseMatrix")
670 x_spv <- as(x_csc, "sparseVector")
671 bst <- xgb.train(
672 data = xgb.DMatrix(X, label = y, nthread = 1),
673 nrounds = 5L, verbose = FALSE,
674 params = xgb.params(
675 objective = "binary:logistic",
676 nthread = n_threads
677 )
678 )
679 p_csc <- predict(bst, x_csc)
680 p_csr <- predict(bst, x_csr)
681 p_spv <- predict(bst, x_spv)
682 expect_equal(p_csc, p_csr)
683 expect_equal(p_csc, p_spv)
684 })
685
686 test_that("Quantile regression accepts multiple quantiles", {
687 data(mtcars)
688 y <- mtcars[, 1]
689 x <- as.matrix(mtcars[, -1])
690 dm <- xgb.DMatrix(data = x, label = y, nthread = 1)
691 model <- xgb.train(
692 data = dm,
693 params = xgb.params(
694 objective = "reg:quantileerror",
695 tree_method = "exact",
696 quantile_alpha = c(0.05, 0.5, 0.95),
697 nthread = n_threads
698 ),
699 nrounds = 15
700 )
701 pred <- predict(model, x)
702
703 expect_equal(dim(pred)[1], nrow(x))
704 expect_equal(dim(pred)[2], 3)
705 expect_true(all(pred[, 1] <= pred[, 3]))
706
707 cors <- cor(y, pred)
708 expect_true(cors[2] > cors[1])
709 expect_true(cors[2] > cors[3])
710 expect_true(cors[2] > 0.85)
711 })
712
713 test_that("Can use multi-output labels with built-in objectives", {
714 data("mtcars")
715 y <- mtcars$mpg
716 x <- as.matrix(mtcars[, -1])
717 y_mirrored <- cbind(y, -y)
718 dm <- xgb.DMatrix(x, label = y_mirrored, nthread = n_threads)
719 model <- xgb.train(
720 params = xgb.params(
721 tree_method = "hist",
722 multi_strategy = "multi_output_tree",
723 objective = "reg:squarederror",
724 nthread = n_threads
725 ),
726 data = dm,
727 nrounds = 5
728 )
729 pred <- predict(model, x)
730 expect_equal(pred[, 1], -pred[, 2])
731 expect_true(cor(y, pred[, 1]) > 0.9)
732 expect_true(cor(y, pred[, 2]) < -0.9)
733 })
734
735 test_that("Can use multi-output labels with custom objectives", {
736 data("mtcars")
737 y <- mtcars$mpg
738 x <- as.matrix(mtcars[, -1])
739 y_mirrored <- cbind(y, -y)
740 dm <- xgb.DMatrix(x, label = y_mirrored, nthread = n_threads)
741 model <- xgb.train(
742 params = xgb.params(
743 tree_method = "hist",
744 multi_strategy = "multi_output_tree",
745 base_score = 0,
746 objective = function(pred, dtrain) {
747 y <- getinfo(dtrain, "label")
748 grad <- pred - y
749 hess <- rep(1, nrow(grad) * ncol(grad))
750 hess <- matrix(hess, nrow = nrow(grad))
751 return(list(grad = grad, hess = hess))
752 },
753 nthread = n_threads
754 ),
755 data = dm,
756 nrounds = 5
757 )
758 pred <- predict(model, x)
759 expect_equal(pred[, 1], -pred[, 2])
760 expect_true(cor(y, pred[, 1]) > 0.9)
761 expect_true(cor(y, pred[, 2]) < -0.9)
762 })
763
764 test_that("Can use ranking objectives with either 'qid' or 'group'", {
765 set.seed(123)
766 x <- matrix(rnorm(100 * 10), nrow = 100)
767 y <- sample(2, size = 100, replace = TRUE) - 1
768 qid <- c(rep(1, 20), rep(2, 20), rep(3, 60))
769 gr <- c(20, 20, 60)
770
771 dmat_qid <- xgb.DMatrix(x, label = y, qid = qid, nthread = 1)
772 dmat_gr <- xgb.DMatrix(x, label = y, group = gr, nthread = 1)
773
774 params <- xgb.params(
775 tree_method = "hist",
776 lambdarank_num_pair_per_sample = 8,
777 objective = "rank:ndcg",
778 lambdarank_pair_method = "topk",
779 nthread = n_threads
780 )
781 set.seed(123)
782 model_qid <- xgb.train(params, dmat_qid, nrounds = 5)
783 set.seed(123)
784 model_gr <- xgb.train(params, dmat_gr, nrounds = 5)
785
786 pred_qid <- predict(model_qid, x)
787 pred_gr <- predict(model_gr, x)
788 expect_equal(pred_qid, pred_gr)
789 })
790
791 test_that("Can predict on data.frame objects", {
792 data("mtcars")
793 y <- mtcars$mpg
794 x_df <- mtcars[, -1]
795 x_mat <- as.matrix(x_df)
796 dm <- xgb.DMatrix(x_mat, label = y, nthread = n_threads)
797 model <- xgb.train(
798 params = xgb.params(
799 tree_method = "hist",
800 objective = "reg:squarederror",
801 nthread = n_threads
802 ),
803 data = dm,
804 nrounds = 5
805 )
806
807 pred_mat <- predict(model, xgb.DMatrix(x_mat, nthread = 1))
808 pred_df <- predict(model, x_df)
809 expect_equal(pred_mat, unname(pred_df))
810 })
811
812 test_that("'base_margin' gives the same result in DMatrix as in inplace_predict", {
813 data("mtcars")
814 y <- mtcars$mpg
815 x <- as.matrix(mtcars[, -1])
816 dm <- xgb.DMatrix(x, label = y, nthread = n_threads)
817 model <- xgb.train(
818 params = xgb.params(
819 tree_method = "hist",
820 objective = "reg:squarederror",
821 nthread = n_threads
822 ),
823 data = dm,
824 nrounds = 5
825 )
826
827 set.seed(123)
828 base_margin <- rnorm(nrow(x))
829 dm_w_base <- xgb.DMatrix(data = x, base_margin = base_margin, nthread = 1)
830 pred_from_dm <- predict(model, dm_w_base)
831 pred_from_mat <- predict(model, x, base_margin = base_margin)
832
833 expect_equal(pred_from_dm, unname(pred_from_mat))
834 })
835
836 test_that("Coefficients from gblinear have the expected shape and names", {
837 # Single-column coefficients
838 data(mtcars)
839 y <- mtcars$mpg
840 x <- as.matrix(mtcars[, -1])
841 mm <- model.matrix(~., data = mtcars[, -1])
842 dm <- xgb.DMatrix(x, label = y, nthread = 1)
843 model <- xgb.train(
844 data = dm,
845 params = xgb.params(
846 booster = "gblinear",
847 nthread = 1
848 ),
849 nrounds = 3
850 )
851 coefs <- coef(model)
852 expect_equal(length(coefs), ncol(x) + 1)
853 expect_equal(names(coefs), c("(Intercept)", colnames(x)))
854 pred_auto <- predict(model, x)
855 pred_manual <- as.numeric(mm %*% coefs)
856 expect_equal(pred_manual, unname(pred_auto), tolerance = 1e-5)
857
858 # Multi-column coefficients
859 data(iris)
860 y <- as.numeric(iris$Species) - 1
861 x <- as.matrix(iris[, -5])
862 dm <- xgb.DMatrix(x, label = y, nthread = 1)
863 mm <- model.matrix(~., data = iris[, -5])
864 model <- xgb.train(
865 data = dm,
866 params = xgb.params(
867 booster = "gblinear",
868 objective = "multi:softprob",
869 num_class = 3,
870 nthread = 1
871 ),
872 nrounds = 3
873 )
874 coefs <- coef(model)
875 expect_equal(nrow(coefs), ncol(x) + 1)
876 expect_equal(ncol(coefs), 3)
877 expect_equal(row.names(coefs), c("(Intercept)", colnames(x)))
878 pred_auto <- predict(model, x, outputmargin = TRUE)
879 pred_manual <- unname(mm %*% coefs)
880 expect_equal(pred_manual, pred_auto, tolerance = 1e-7)
881
882 # xgboost() with additional metadata
883 model <- xgboost(
884 iris[, -5],
885 iris$Species,
886 booster = "gblinear",
887 objective = "multi:softprob",
888 nrounds = 3,
889 nthread = 1
890 )
891 coefs <- coef(model)
892 expect_equal(row.names(coefs), c("(Intercept)", colnames(x)))
893 expect_equal(colnames(coefs), levels(iris$Species))
894 })
895
896 test_that("Deep copies work as expected", {
897 data(mtcars)
898 y <- mtcars$mpg
899 x <- mtcars[, -1]
900 dm <- xgb.DMatrix(x, label = y, nthread = 1)
901 model <- xgb.train(
902 data = dm,
903 params = xgb.params(nthread = 1),
904 nrounds = 3
905 )
906
907 xgb.attr(model, "my_attr") <- 100
908 model_shallow_copy <- model
909 xgb.attr(model_shallow_copy, "my_attr") <- 333
910 attr_orig <- xgb.attr(model, "my_attr")
911 attr_shallow <- xgb.attr(model_shallow_copy, "my_attr")
912 expect_equal(attr_orig, attr_shallow)
913
914 model_deep_copy <- xgb.copy.Booster(model)
915 xgb.attr(model_deep_copy, "my_attr") <- 444
916 attr_orig <- xgb.attr(model, "my_attr")
917 attr_deep <- xgb.attr(model_deep_copy, "my_attr")
918 expect_false(attr_orig == attr_deep)
919 })
920
921 test_that("Pointer comparison works as expected", {
922 library(xgboost)
923 y <- mtcars$mpg
924 x <- as.matrix(mtcars[, -1])
925 model <- xgb.train(
926 params = xgb.params(nthread = 1),
927 data = xgb.DMatrix(x, label = y, nthread = 1),
928 nrounds = 3
929 )
930
931 model_shallow_copy <- model
932 expect_true(xgb.is.same.Booster(model, model_shallow_copy))
933
934 model_deep_copy <- xgb.copy.Booster(model)
935 expect_false(xgb.is.same.Booster(model, model_deep_copy))
936
937 xgb.attr(model_shallow_copy, "my_attr") <- 111
938 expect_equal(xgb.attr(model, "my_attr"), "111")
939 expect_null(xgb.attr(model_deep_copy, "my_attr"))
940 })
941
942 test_that("DMatrix field are set to booster when training", {
943 set.seed(123)
944 y <- rnorm(100)
945 x <- matrix(rnorm(100 * 3), nrow = 100)
946 x[, 2] <- abs(as.integer(x[, 2]))
947
948 dm_unnamed <- xgb.DMatrix(x, label = y, nthread = 1)
949 dm_feature_names <- xgb.DMatrix(x, label = y, feature_names = c("a", "b", "c"), nthread = 1)
950 dm_feature_types <- xgb.DMatrix(x, label = y, nthread = 1)
951 setinfo(dm_feature_types, "feature_type", c("q", "c", "q"))
952 dm_both <- xgb.DMatrix(x, label = y, feature_names = c("a", "b", "c"), nthread = 1)
953 setinfo(dm_both, "feature_type", c("q", "c", "q"))
954
955 params <- xgb.params(nthread = 1)
956 model_unnamed <- xgb.train(data = dm_unnamed, params = params, nrounds = 3)
957 model_feature_names <- xgb.train(data = dm_feature_names, params = params, nrounds = 3)
958 model_feature_types <- xgb.train(data = dm_feature_types, params = params, nrounds = 3)
959 model_both <- xgb.train(data = dm_both, params = params, nrounds = 3)
960
961 expect_null(getinfo(model_unnamed, "feature_name"))
962 expect_equal(getinfo(model_feature_names, "feature_name"), c("a", "b", "c"))
963 expect_null(getinfo(model_feature_types, "feature_name"))
964 expect_equal(getinfo(model_both, "feature_name"), c("a", "b", "c"))
965
966 expect_null(variable.names(model_unnamed))
967 expect_equal(variable.names(model_feature_names), c("a", "b", "c"))
968 expect_null(variable.names(model_feature_types))
969 expect_equal(variable.names(model_both), c("a", "b", "c"))
970
971 expect_null(getinfo(model_unnamed, "feature_type"))
972 expect_null(getinfo(model_feature_names, "feature_type"))
973 expect_equal(getinfo(model_feature_types, "feature_type"), c("q", "c", "q"))
974 expect_equal(getinfo(model_both, "feature_type"), c("q", "c", "q"))
975 })
976
977 test_that("Seed in params override PRNG from R", {
978 set.seed(123)
979 model1 <- xgb.train(
980 data = xgb.DMatrix(
981 agaricus.train$data,
982 label = agaricus.train$label, nthread = 1L
983 ),
984 params = xgb.params(
985 objective = "binary:logistic",
986 max_depth = 3L,
987 subsample = 0.1,
988 colsample_bytree = 0.1,
989 seed = 111L
990 ),
991 nrounds = 3L
992 )
993
994 set.seed(456)
995 model2 <- xgb.train(
996 data = xgb.DMatrix(
997 agaricus.train$data,
998 label = agaricus.train$label, nthread = 1L
999 ),
1000 params = xgb.params(
1001 objective = "binary:logistic",
1002 max_depth = 3L,
1003 subsample = 0.1,
1004 colsample_bytree = 0.1,
1005 seed = 111L
1006 ),
1007 nrounds = 3L
1008 )
1009
1010 expect_equal(
1011 xgb.save.raw(model1, raw_format = "json"),
1012 xgb.save.raw(model2, raw_format = "json")
1013 )
1014
1015 set.seed(123)
1016 model3 <- xgb.train(
1017 data = xgb.DMatrix(
1018 agaricus.train$data,
1019 label = agaricus.train$label, nthread = 1L
1020 ),
1021 params = xgb.params(
1022 objective = "binary:logistic",
1023 max_depth = 3L,
1024 subsample = 0.1,
1025 colsample_bytree = 0.1,
1026 seed = 222L
1027 ),
1028 nrounds = 3L
1029 )
1030 expect_false(
1031 isTRUE(
1032 all.equal(
1033 xgb.save.raw(model1, raw_format = "json"),
1034 xgb.save.raw(model3, raw_format = "json")
1035 )
1036 )
1037 )
1038 })
1039
1040 test_that("xgb.cv works for AFT", {
1041 X <- matrix(c(1, -1, -1, 1, 0, 1, 1, 0), nrow = 4, byrow = TRUE) # 4x2 matrix
1042 dtrain <- xgb.DMatrix(X, nthread = n_threads)
1043
1044 params <- xgb.params(objective = 'survival:aft', learning_rate = 0.2, max_depth = 2L, nthread = n_threads)
1045
1046 # data must have bounds
1047 expect_error(
1048 xgb.cv(
1049 params = params,
1050 data = dtrain,
1051 nround = 5L,
1052 nfold = 4L
1053 )
1054 )
1055
1056 setinfo(dtrain, 'label_lower_bound', c(2, 3, 0, 4))
1057 setinfo(dtrain, 'label_upper_bound', c(2, Inf, 4, 5))
1058
1059 # automatic stratified splitting is turned off
1060 expect_warning(
1061 xgb.cv(
1062 params = params, data = dtrain, nround = 5L, nfold = 4L,
1063 stratified = TRUE, verbose = FALSE
1064 )
1065 )
1066
1067 # this works without any issue
1068 expect_no_warning(
1069 xgb.cv(params = params, data = dtrain, nround = 5L, nfold = 4L, verbose = FALSE)
1070 )
1071 })
1072
1073 test_that("xgb.cv works for ranking", {
1074 data(iris)
1075 x <- iris[, -(4:5)]
1076 y <- as.integer(iris$Petal.Width)
1077 group <- rep(50, 3)
1078 dm <- xgb.DMatrix(x, label = y, group = group, nthread = 1)
1079 res <- xgb.cv(
1080 data = dm,
1081 params = xgb.params(
1082 objective = "rank:pairwise",
1083 max_depth = 3,
1084 nthread = 1L
1085 ),
1086 nrounds = 3,
1087 nfold = 2,
1088 verbose = FALSE,
1089 stratified = FALSE
1090 )
1091 expect_equal(length(res$folds), 2L)
1092 })
1093
1094 test_that("Row names are preserved in outputs", {
1095 data(iris)
1096 x <- iris[, -5]
1097 y <- as.numeric(iris$Species) - 1
1098 dm <- xgb.DMatrix(x, label = y, nthread = 1)
1099 model <- xgb.train(
1100 data = dm,
1101 params = xgb.params(
1102 objective = "multi:softprob",
1103 num_class = 3,
1104 max_depth = 2,
1105 nthread = 1
1106 ),
1107 nrounds = 3
1108 )
1109 row.names(x) <- paste0("r", seq(1, nrow(x)))
1110 pred <- predict(model, x)
1111 expect_equal(row.names(pred), row.names(x))
1112 pred <- predict(model, x, avoid_transpose = TRUE)
1113 expect_equal(colnames(pred), row.names(x))
1114
1115 data(mtcars)
1116 y <- mtcars[, 1]
1117 x <- as.matrix(mtcars[, -1])
1118 dm <- xgb.DMatrix(data = x, label = y, nthread = 1)
1119 model <- xgb.train(
1120 data = dm,
1121 params = xgb.params(
1122 max_depth = 2,
1123 nthread = 1
1124 ),
1125 nrounds = 3
1126 )
1127 row.names(x) <- paste0("r", seq(1, nrow(x)))
1128 pred <- predict(model, x)
1129 expect_equal(names(pred), row.names(x))
1130 pred <- predict(model, x, avoid_transpose = TRUE)
1131 expect_equal(names(pred), row.names(x))
1132 pred <- predict(model, x, predleaf = TRUE)
1133 expect_equal(row.names(pred), row.names(x))
1134 pred <- predict(model, x, predleaf = TRUE, avoid_transpose = TRUE)
1135 expect_equal(colnames(pred), row.names(x))
1136 })
1137
1138 test_that("xgb.train works with nrounds=0 (serialization, continuation, callbacks)", {
1139 # Reuse global data variable 'train' defined at the top of test_basic.R
1140 dtrain <- xgb.DMatrix(train$data, label = train$label)
1141 watchlist <- list(train = dtrain)
1142
1143 # --- Case 1: Basic check & Serialization symmetry ---
1144 bst_0 <- xgb.train(
1145 params = list(objective = "binary:logistic", nthread = 1),
1146 data = dtrain,
1147 nrounds = 0,
1148 verbose = 0
1149 )
1150
1151 # Check niter is 0 (handling NULL case common for empty boosters)
1152 iter_0 <- bst_0$niter
1153 if (is.null(iter_0)) {
1154 iter_0 <- 0
1155 }
1156 expect_equal(iter_0, 0)
1157
1158 # Check that 0-round model provides a valid "base score" prediction
1159 preds_0 <- predict(bst_0, dtrain)
1160 expect_true(all((preds_0 >= 0) & (preds_0 <= 1)))
1161
1162 # Serialize via RAM (Raw) instead of disk (tempfile) for cleaner tests
1163 raw <- xgb.save.raw(bst_0)
1164 bst_loaded <- xgb.load.raw(raw)
1165
1166 # Verify predictions match before/after serialization
1167 preds_loaded <- predict(bst_loaded, dtrain)
1168 expect_equal(preds_0, preds_loaded, tolerance = 1e-6)
1169
1170 # --- Case 2: Training Continuation Numeric Consistency ---
1171 # Initialize empty model with fixed seed & single thread
1172 bst_init <- xgb.train(
1173 params = list(objective = "binary:logistic", seed = 123, nthread = 1),
1174 data = dtrain,
1175 nrounds = 0,
1176 verbose = 0
1177 )
1178
1179 # Continue training for 10 rounds from empty booster
1180 bst_cont <- xgb.train(
1181 params = list(objective = "binary:logistic", seed = 123, nthread = 1),
1182 data = dtrain,
1183 nrounds = 10,
1184 xgb_model = bst_init,
1185 verbose = 0
1186 )
1187
1188 # Reference training from scratch
1189 bst_ref <- xgb.train(
1190 params = list(objective = "binary:logistic", seed = 123, nthread = 1),
1191 data = dtrain,
1192 nrounds = 10,
1193 verbose = 0
1194 )
1195
1196 # Predictions must be numerically identical within 1e-6
1197 p_cont <- predict(bst_cont, dtrain)
1198 p_ref <- predict(bst_ref, dtrain)
1199 expect_equal(p_cont, p_ref, tolerance = 1e-6)
1200
1201 # --- Case 3: Callback Robustness ---
1202 # Verify early stopping and evals work with nrounds=0
1203 bst_cb <- xgb.train(
1204 params = list(objective = "binary:logistic", seed = 456, nthread = 1),
1205 data = dtrain,
1206 nrounds = 0,
1207 evals = watchlist,
1208 early_stopping_rounds = 3,
1209 verbose = 0
1210 )
1211
1212 # Verify that continuation works
1213 bst_cb_cont <- xgb.train(
1214 params = list(objective = "binary:logistic", seed = 456, nthread = 1),
1215 data = dtrain,
1216 nrounds = 5,
1217 evals = watchlist,
1218 early_stopping_rounds = 3,
1219 xgb_model = bst_cb,
1220 verbose = 0
1221 )
1222
1223 # Handle NULL niter for continued model with early stopping
1224 iter_cb <- bst_cb_cont$niter
1225 if (is.null(iter_cb)) {
1226 # Verify the continued model works and learned signal
1227 preds_cb <- predict(bst_cb_cont, dtrain)
1228 expect_true(stats::sd(preds_cb) > 0)
1229 expect_equal(length(preds_cb), nrow(train$data))
1230 } else {
1231 expect_equal(iter_cb, 5)
1232 }
1233 })