Debian Codegraph @

tests/testthat/test_xgboost.R

raw
1 library(survival)
2 library(data.table)
3 data("iris")
4 data("mtcars")
5 data("ToothGrowth")
6
7 test_that("Auto determine objective", {
8 y_num <- seq(1, 10)
9 res_num <- process.y.margin.and.objective(y_num, NULL, NULL, NULL)
10 expect_equal(res_num$params$objective, "reg:squarederror")
11
12 y_bin <- factor(c('a', 'b', 'a', 'b'), c('a', 'b'))
13 res_bin <- process.y.margin.and.objective(y_bin, NULL, NULL, NULL)
14 expect_equal(res_bin$params$objective, "binary:logistic")
15
16 y_multi <- factor(c('a', 'b', 'a', 'b', 'c'), c('a', 'b', 'c'))
17 res_multi <- process.y.margin.and.objective(y_multi, NULL, NULL, NULL)
18 expect_equal(res_multi$params$objective, "multi:softprob")
19
20 y_surv <- Surv(1:10, rep(c(0, 1), 5), type = "right")
21 res_surv <- process.y.margin.and.objective(y_surv, NULL, NULL, NULL)
22 expect_equal(res_surv$params$objective, "survival:aft")
23
24 y_multicol <- matrix(seq(1, 20), nrow = 5)
25 res_multicol <- process.y.margin.and.objective(y_multicol, NULL, NULL, NULL)
26 expect_equal(res_multicol$params$objective, "reg:squarederror")
27 })
28
29 test_that("Process vectors", {
30 y <- seq(1, 10)
31 for (y_inp in list(as.integer(y), as.numeric(y))) {
32 res <- process.y.margin.and.objective(y_inp, NULL, "reg:pseudohubererror", NULL)
33 expect_equal(
34 res$dmatrix_args$label,
35 y
36 )
37 expect_equal(
38 res$params$objective,
39 "reg:pseudohubererror"
40 )
41 }
42 })
43
44 test_that("Process factors", {
45 y_bin <- factor(c('a', 'b', 'a', 'b'), c('a', 'b'))
46 expect_error({
47 process.y.margin.and.objective(y_bin, NULL, "multi:softprob", NULL)
48 })
49 for (bin_obj in c("binary:logistic", "binary:hinge")) {
50 for (y_inp in list(y_bin, as.ordered(y_bin))) {
51 res_bin <- process.y.margin.and.objective(y_inp, NULL, bin_obj, NULL)
52 expect_equal(
53 res_bin$dmatrix_args$label,
54 c(0, 1, 0, 1)
55 )
56 expect_equal(
57 res_bin$metadata$y_levels,
58 c('a', 'b')
59 )
60 expect_equal(
61 res_bin$params$objective,
62 bin_obj
63 )
64 }
65 }
66
67 y_bin2 <- factor(c(1, 0, 1, 0), c(1, 0))
68 res_bin <- process.y.margin.and.objective(y_bin2, NULL, "binary:logistic", NULL)
69 expect_equal(
70 res_bin$dmatrix_args$label,
71 c(0, 1, 0, 1)
72 )
73 expect_equal(
74 res_bin$metadata$y_levels,
75 c("1", "0")
76 )
77
78 y_bin3 <- c(TRUE, FALSE, TRUE)
79 res_bin <- process.y.margin.and.objective(y_bin3, NULL, "binary:logistic", NULL)
80 expect_equal(
81 res_bin$dmatrix_args$label,
82 c(1, 0, 1)
83 )
84 expect_equal(
85 res_bin$metadata$y_levels,
86 c("FALSE", "TRUE")
87 )
88
89 y_multi <- factor(c('a', 'b', 'c', 'd', 'a', 'b'), c('a', 'b', 'c', 'd'))
90 expect_error({
91 process.y.margin.and.objective(y_multi, NULL, "binary:logistic", NULL)
92 })
93 expect_error({
94 process.y.margin.and.objective(y_multi, NULL, "binary:logistic", NULL)
95 })
96 res_multi <- process.y.margin.and.objective(y_multi, NULL, "multi:softprob", NULL)
97 expect_equal(
98 res_multi$dmatrix_args$label,
99 c(0, 1, 2, 3, 0, 1)
100 )
101 expect_equal(
102 res_multi$metadata$y_levels,
103 c('a', 'b', 'c', 'd')
104 )
105 expect_equal(
106 res_multi$params$num_class,
107 4
108 )
109 expect_equal(
110 res_multi$params$objective,
111 "multi:softprob"
112 )
113 })
114
115 test_that("Process survival objects", {
116 data(cancer, package = "survival")
117 y_right <- Surv(cancer$time, cancer$status - 1, type = "right")
118 res_cox <- process.y.margin.and.objective(y_right, NULL, "survival:cox", NULL)
119 expect_equal(
120 res_cox$dmatrix_args$label,
121 ifelse(cancer$status == 2, cancer$time, -cancer$time)
122 )
123 expect_equal(
124 res_cox$params$objective,
125 "survival:cox"
126 )
127
128 res_aft <- process.y.margin.and.objective(y_right, NULL, "survival:aft", NULL)
129 expect_equal(
130 res_aft$dmatrix_args$label_lower_bound,
131 cancer$time
132 )
133 expect_equal(
134 res_aft$dmatrix_args$label_upper_bound,
135 ifelse(cancer$status == 2, cancer$time, Inf)
136 )
137 expect_equal(
138 res_aft$params$objective,
139 "survival:aft"
140 )
141
142 y_left <- Surv(seq(1, 4), c(1, 0, 1, 0), type = "left")
143 expect_error({
144 process.y.margin.and.objective(y_left, NULL, "survival:cox", NULL)
145 })
146 res_aft <- process.y.margin.and.objective(y_left, NULL, "survival:aft", NULL)
147 expect_equal(
148 res_aft$dmatrix_args$label_lower_bound,
149 c(1, 0, 3, 0)
150 )
151 expect_equal(
152 res_aft$dmatrix_args$label_upper_bound,
153 seq(1, 4)
154 )
155 expect_equal(
156 res_aft$params$objective,
157 "survival:aft"
158 )
159
160 y_interval <- Surv(
161 time = c(1, 5, 2, 10, 3),
162 time2 = c(2, 5, 2.5, 10, 3),
163 event = c(3, 1, 3, 0, 2),
164 type = "interval"
165 )
166 expect_error({
167 process.y.margin.and.objective(y_interval, NULL, "survival:cox", NULL)
168 })
169 res_aft <- process.y.margin.and.objective(y_interval, NULL, "survival:aft", NULL)
170 expect_equal(
171 res_aft$dmatrix_args$label_lower_bound,
172 c(1, 5, 2, 10, 0)
173 )
174 expect_equal(
175 res_aft$dmatrix_args$label_upper_bound,
176 c(2, 5, 2.5, Inf, 3)
177 )
178 expect_equal(
179 res_aft$params$objective,
180 "survival:aft"
181 )
182
183 y_interval_neg <- Surv(
184 time = c(1, -5, 2, 10, 3),
185 time2 = c(2, -5, 2.5, 10, 3),
186 event = c(3, 1, 3, 0, 2),
187 type = "interval"
188 )
189 expect_error({
190 process.y.margin.and.objective(y_interval_neg, NULL, "survival:aft", NULL)
191 })
192 })
193
194 test_that("Process multi-target", {
195 data(mtcars)
196 y_multi <- data.frame(
197 y1 = mtcars$mpg,
198 y2 = mtcars$mpg ^ 2
199 )
200 for (y_inp in list(y_multi, as.matrix(y_multi), data.table::as.data.table(y_multi))) {
201 res_multi <- process.y.margin.and.objective(y_inp, NULL, "reg:pseudohubererror", NULL)
202 expect_equal(
203 res_multi$dmatrix_args$label,
204 as.matrix(y_multi)
205 )
206 expect_equal(
207 res_multi$metadata$y_names,
208 c("y1", "y2")
209 )
210 expect_equal(
211 res_multi$params$objective,
212 "reg:pseudohubererror"
213 )
214 }
215
216 expect_error({
217 process.y.margin.and.objective(y_multi, NULL, "count:poisson", NULL)
218 })
219
220 y_bad <- data.frame(
221 c1 = seq(1, 3),
222 c2 = rep(as.Date("2024-01-01"), 3)
223 )
224 expect_error({
225 process.y.margin.and.objective(y_bad, NULL, "reg:squarederror", NULL)
226 })
227
228 y_bad <- data.frame(
229 c1 = seq(1, 3),
230 c2 = factor(c('a', 'b', 'a'), c('a', 'b'))
231 )
232 expect_error({
233 process.y.margin.and.objective(y_bad, NULL, "reg:squarederror", NULL)
234 })
235
236 y_bad <- seq(1, 20)
237 dim(y_bad) <- c(5, 2, 2)
238 expect_error({
239 process.y.margin.and.objective(y_bad, NULL, "reg:squarederror", NULL)
240 })
241 })
242
243 test_that("Process base_margin", {
244 y <- seq(101, 110)
245 bm_good <- seq(1, 10)
246 for (bm in list(bm_good, as.matrix(bm_good), as.data.frame(as.matrix(bm_good)))) {
247 res <- process.y.margin.and.objective(y, bm, "reg:squarederror", NULL)
248 expect_equal(
249 res$dmatrix_args$base_margin,
250 seq(1, 10)
251 )
252 }
253 expect_error({
254 process.y.margin.and.objective(y, 5, "reg:squarederror", NULL)
255 })
256 expect_error({
257 process.y.margin.and.objective(y, seq(1, 5), "reg:squarederror", NULL)
258 })
259 expect_error({
260 process.y.margin.and.objective(y, matrix(seq(1, 20), ncol = 2), "reg:squarederror", NULL)
261 })
262 expect_error({
263 process.y.margin.and.objective(
264 y,
265 as.data.frame(matrix(seq(1, 20), ncol = 2)),
266 "reg:squarederror",
267 NULL
268 )
269 })
270
271 y <- factor(c('a', 'b', 'c', 'a'))
272 bm_good <- matrix(seq(1, 12), ncol = 3)
273 for (bm in list(bm_good, as.data.frame(bm_good))) {
274 res <- process.y.margin.and.objective(y, bm, "multi:softprob", NULL)
275 expect_equal(
276 res$dmatrix_args$base_margin |> unname(),
277 matrix(seq(1, 12), ncol = 3)
278 )
279 }
280 expect_error({
281 process.y.margin.and.objective(y, as.numeric(bm_good), "multi:softprob", NULL)
282 })
283 expect_error({
284 process.y.margin.and.objective(y, 5, "multi:softprob", NULL)
285 })
286 expect_error({
287 process.y.margin.and.objective(y, bm_good[, 1], "multi:softprob", NULL)
288 })
289 expect_error({
290 process.y.margin.and.objective(y, bm_good[, c(1, 2)], "multi:softprob", NULL)
291 })
292 expect_error({
293 process.y.margin.and.objective(y, bm_good[c(1, 2), ], "multi:softprob", NULL)
294 })
295
296 y <- seq(101, 110)
297 bm_good <- matrix(seq(1, 30), ncol = 3)
298 params <- list(quantile_alpha = c(0.1, 0.5, 0.9))
299 for (bm in list(bm_good, as.data.frame(bm_good))) {
300 res <- process.y.margin.and.objective(y, bm, "reg:quantileerror", params)
301 expect_equal(
302 res$dmatrix_args$base_margin |> unname(),
303 matrix(seq(1, 30), ncol = 3)
304 )
305 }
306 expect_error({
307 process.y.margin.and.objective(y, as.numeric(bm_good), "reg:quantileerror", params)
308 })
309 expect_error({
310 process.y.margin.and.objective(y, 5, "reg:quantileerror", params)
311 })
312 expect_error({
313 process.y.margin.and.objective(y, bm_good[, 1], "reg:quantileerror", params)
314 })
315 expect_error({
316 process.y.margin.and.objective(y, bm_good[, c(1, 2)], "reg:quantileerror", params)
317 })
318 expect_error({
319 process.y.margin.and.objective(y, bm_good[c(1, 2, 3), ], "reg:quantileerror", params)
320 })
321
322 y <- matrix(seq(101, 130), ncol = 3)
323 for (bm in list(bm_good, as.data.frame(bm_good))) {
324 res <- process.y.margin.and.objective(y, bm, "reg:squarederror", params)
325 expect_equal(
326 res$dmatrix_args$base_margin |> unname(),
327 matrix(seq(1, 30), ncol = 3)
328 )
329 }
330 expect_error({
331 process.y.margin.and.objective(y, as.numeric(bm_good), "reg:squarederror", params)
332 })
333 expect_error({
334 process.y.margin.and.objective(y, 5, "reg:squarederror", params)
335 })
336 expect_error({
337 process.y.margin.and.objective(y, bm_good[, 1], "reg:squarederror", params)
338 })
339 expect_error({
340 process.y.margin.and.objective(y, bm_good[, c(1, 2)], "reg:squarederror", params)
341 })
342 expect_error({
343 process.y.margin.and.objective(y, bm_good[c(1, 2, 3), ], "reg:squarederror", params)
344 })
345 })
346
347 test_that("Process monotone constraints", {
348 data(iris)
349 mc_list <- list(Sepal.Width = 1)
350 res <- process.x.and.col.args(
351 iris,
352 monotone_constraints = mc_list,
353 interaction_constraints = NULL,
354 feature_weights = NULL,
355 lst_args = list(),
356 use_qdm = FALSE
357 )
358 expect_equal(
359 res$params$monotone_constraints,
360 c(0, 1, 0, 0, 0)
361 )
362
363 mc_list2 <- list(Sepal.Width = 1, Petal.Width = -1)
364 res <- process.x.and.col.args(
365 iris,
366 monotone_constraints = mc_list2,
367 interaction_constraints = NULL,
368 feature_weights = NULL,
369 lst_args = list(),
370 use_qdm = FALSE
371 )
372 expect_equal(
373 res$params$monotone_constraints,
374 c(0, 1, 0, -1, 0)
375 )
376
377 mc_vec <- c(0, 1, -1, 0, 0)
378 res <- process.x.and.col.args(
379 iris,
380 monotone_constraints = mc_vec,
381 interaction_constraints = NULL,
382 feature_weights = NULL,
383 lst_args = list(),
384 use_qdm = FALSE
385 )
386 expect_equal(
387 res$params$monotone_constraints,
388 c(0, 1, -1, 0, 0)
389 )
390
391 mc_named_vec <- c(1, 1)
392 names(mc_named_vec) <- names(iris)[1:2]
393 res <- process.x.and.col.args(
394 iris,
395 monotone_constraints = mc_named_vec,
396 interaction_constraints = NULL,
397 feature_weights = NULL,
398 lst_args = list(),
399 use_qdm = FALSE
400 )
401 expect_equal(
402 res$params$monotone_constraints,
403 c(1, 1, 0, 0, 0)
404 )
405
406 mc_named_all <- c(0, -1, 1, 0, -1)
407 names(mc_named_all) <- rev(names(iris))
408 res <- process.x.and.col.args(
409 iris,
410 monotone_constraints = mc_named_all,
411 interaction_constraints = NULL,
412 feature_weights = NULL,
413 lst_args = list(),
414 use_qdm = FALSE
415 )
416 expect_equal(
417 res$params$monotone_constraints,
418 rev(mc_named_all) |> unname()
419 )
420
421 expect_error({
422 process.x.and.col.args(
423 iris,
424 monotone_constraints = list(
425 Sepal.Width = 1,
426 Petal.Width = -1,
427 Sepal.Width = -1
428 ),
429 interaction_constraints = NULL,
430 feature_weights = NULL,
431 lst_args = list(),
432 use_qdm = FALSE
433 )
434 })
435
436 expect_error({
437 process.x.and.col.args(
438 iris,
439 monotone_constraints = rep(0, 6),
440 interaction_constraints = NULL,
441 feature_weights = NULL,
442 lst_args = list(),
443 use_qdm = FALSE
444 )
445 })
446 })
447
448 test_that("Process interaction_constraints", {
449 data(iris)
450 res <- process.x.and.col.args(iris, NULL, list(c(1L, 2L)), NULL, NULL, FALSE)
451 expect_equal(
452 res$params$interaction_constraints,
453 list(c(0, 1))
454 )
455 res <- process.x.and.col.args(iris, NULL, list(c(1.0, 2.0)), NULL, NULL, FALSE)
456 expect_equal(
457 res$params$interaction_constraints,
458 list(c(0, 1))
459 )
460 res <- process.x.and.col.args(iris, NULL, list(c(1, 2), c(3, 4)), NULL, NULL, FALSE)
461 expect_equal(
462 res$params$interaction_constraints,
463 list(c(0, 1), c(2, 3))
464 )
465 res <- process.x.and.col.args(
466 iris, NULL, list(c("Sepal.Length", "Sepal.Width")), NULL, NULL, FALSE
467 )
468 expect_equal(
469 res$params$interaction_constraints,
470 list(c(0, 1))
471 )
472 res <- process.x.and.col.args(
473 as.matrix(iris),
474 NULL,
475 list(c("Sepal.Length", "Sepal.Width")),
476 NULL,
477 NULL,
478 FALSE
479 )
480 expect_equal(
481 res$params$interaction_constraints,
482 list(c(0, 1))
483 )
484 res <- process.x.and.col.args(
485 iris,
486 NULL,
487 list(c("Sepal.Width", "Petal.Length"), c("Sepal.Length", "Petal.Width", "Species")),
488 NULL,
489 NULL,
490 FALSE
491 )
492 expect_equal(
493 res$params$interaction_constraints,
494 list(c(1, 2), c(0, 3, 4))
495 )
496
497 expect_error({
498 process.x.and.col.args(iris, NULL, list(c(1L, 20L)), NULL, NULL, FALSE)
499 })
500 expect_error({
501 process.x.and.col.args(iris, NULL, list(c(0L, 2L)), NULL, NULL, FALSE)
502 })
503 expect_error({
504 process.x.and.col.args(iris, NULL, list(c("1", "2")), NULL, NULL, FALSE)
505 })
506 expect_error({
507 process.x.and.col.args(iris, NULL, list(c("Sepal", "Petal")), NULL, NULL, FALSE)
508 })
509 expect_error({
510 process.x.and.col.args(iris, NULL, c(1L, 2L), NULL, NULL, FALSE)
511 })
512 expect_error({
513 process.x.and.col.args(iris, NULL, matrix(c(1L, 2L)), NULL, NULL, FALSE)
514 })
515 expect_error({
516 process.x.and.col.args(iris, NULL, list(c(1, 2.5)), NULL, NULL, FALSE)
517 })
518 })
519
520 test_that("Sparse matrices are casted to CSR for QDM", {
521 data(agaricus.test, package = "xgboost")
522 x <- agaricus.test$data
523 for (x_in in list(x, methods::as(x, "TsparseMatrix"))) {
524 res <- process.x.and.col.args(
525 x_in,
526 NULL,
527 NULL,
528 NULL,
529 NULL,
530 TRUE
531 )
532 expect_s4_class(res$dmatrix_args$data, "dgRMatrix")
533 }
534 })
535
536 test_that("Process feature_weights", {
537 data(iris)
538 w_vector <- seq(1, 5)
539 res <- process.x.and.col.args(
540 iris,
541 monotone_constraints = NULL,
542 interaction_constraints = NULL,
543 feature_weights = w_vector,
544 lst_args = list(),
545 use_qdm = FALSE
546 )
547 expect_equal(
548 res$dmatrix_args$feature_weights,
549 seq(1, 5)
550 )
551
552 w_named_vector <- seq(1, 5)
553 names(w_named_vector) <- rev(names(iris))
554 res <- process.x.and.col.args(
555 iris,
556 monotone_constraints = NULL,
557 interaction_constraints = NULL,
558 feature_weights = w_named_vector,
559 lst_args = list(),
560 use_qdm = FALSE
561 )
562 expect_equal(
563 res$dmatrix_args$feature_weights,
564 rev(seq(1, 5))
565 )
566
567 w_list <- list(
568 Species = 5,
569 Sepal.Length = 1,
570 Sepal.Width = 2,
571 Petal.Length = 3,
572 Petal.Width = 4
573 )
574 res <- process.x.and.col.args(
575 iris,
576 monotone_constraints = NULL,
577 interaction_constraints = NULL,
578 feature_weights = w_list,
579 lst_args = list(),
580 use_qdm = FALSE
581 )
582 expect_equal(
583 res$dmatrix_args$feature_weights,
584 seq(1, 5)
585 )
586 })
587
588 test_that("Whole function works", {
589 data(cancer, package = "survival")
590 y <- Surv(cancer$time, cancer$status - 1, type = "right")
591 x <- as.data.table(cancer)[, -c("time", "status")]
592 model <- xgboost(
593 x,
594 y,
595 monotone_constraints = list(age = -1),
596 nthreads = 1L,
597 nrounds = 5L,
598 learning_rate = 3
599 )
600 expect_equal(
601 attributes(model)$params$objective,
602 "survival:aft"
603 )
604 expect_equal(
605 attributes(model)$metadata$n_targets,
606 1L
607 )
608 expect_equal(
609 attributes(model)$params$monotone_constraints,
610 "(0,-1,0,0,0,0,0,0)"
611 )
612 expect_false(
613 "interaction_constraints" %in% names(attributes(model)$params)
614 )
615 expect_equal(
616 attributes(model)$params$learning_rate,
617 3
618 )
619 txt <- capture.output({
620 print(model)
621 })
622 expect_true(any(grepl("Objective: survival:aft", txt, fixed = TRUE)))
623 expect_true(any(grepl("monotone_constraints", txt, fixed = TRUE)))
624 expect_true(any(grepl("Number of iterations: 5", txt, fixed = TRUE)))
625 expect_true(any(grepl("Number of features: 8", txt, fixed = TRUE)))
626 })
627
628 test_that("Can predict probabilities and raw scores", {
629 y <- ToothGrowth$supp
630 x <- ToothGrowth[, -2L]
631 model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
632 pred_prob <- predict(model, x, type = "response")
633 pred_raw <- predict(model, x, type = "raw")
634 expect_true(is.vector(pred_prob))
635 expect_equal(length(pred_prob), nrow(x))
636 expect_true(min(pred_prob) >= 0)
637 expect_true(max(pred_prob) <= 1)
638
639 expect_equal(length(pred_raw), nrow(x))
640 expect_true(is.vector(pred_raw))
641 expect_true(min(pred_raw) < 0)
642 expect_true(max(pred_raw) > 0)
643
644 expect_equal(
645 pred_prob,
646 1 / (1 + exp(-pred_raw)),
647 tolerance = 1e-6
648 )
649 })
650
651 test_that("Can predict class", {
652 y <- iris$Species
653 x <- iris[, -5L]
654 model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
655 pred_class <- predict(model, x, type = "class")
656 expect_true(is.factor(pred_class))
657 expect_equal(levels(pred_class), levels(y))
658
659 y <- ToothGrowth$supp
660 x <- ToothGrowth[, -2L]
661 model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
662 pred_class <- predict(model, x, type = "class")
663 expect_true(is.factor(pred_class))
664 expect_equal(levels(pred_class), levels(y))
665
666 probs <- predict(model, x, type = "response")
667 expect_true(all(pred_class[probs >= 0.5] == levels(y)[[2L]]))
668 expect_true(all(pred_class[probs < 0.5] == levels(y)[[1L]]))
669
670 # Check that it fails for regression models
671 y <- mtcars$mpg
672 x <- mtcars[, -1L]
673 model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
674 expect_error({
675 predict(model, x, type = "class")
676 })
677 })
678
679 test_that("Metadata survives serialization", {
680 y <- iris$Species
681 x <- iris[, -5L]
682 model_fresh <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
683 temp_file <- file.path(tempdir(), "xgb_model.Rds")
684 saveRDS(model_fresh, temp_file)
685 model <- readRDS(temp_file)
686 pred_class <- predict(model, x, type = "class")
687 expect_true(is.factor(pred_class))
688 expect_equal(levels(pred_class), levels(y))
689 })
690
691 test_that("Column names aren't added when not appropriate", {
692 pred_types <- c(
693 "response",
694 "raw",
695 "leaf"
696 )
697 for (pred_type in pred_types) {
698 y <- mtcars$mpg
699 x <- mtcars[, -1L]
700 model <- xgboost(
701 x,
702 y,
703 nthreads = 1L,
704 nrounds = 3L,
705 max_depth = 2L,
706 objective = "reg:quantileerror",
707 quantile_alpha = 0.5
708 )
709 pred <- predict(model, x, type = pred_type)
710 if (pred_type %in% c("raw", "response")) {
711 expect_true(is.vector(pred))
712 } else {
713 expect_true(length(dim(pred)) >= 2L)
714 expect_null(colnames(pred))
715 }
716
717 y <- ToothGrowth$supp
718 x <- ToothGrowth[, -2L]
719 model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
720 pred <- predict(model, x, type = pred_type)
721 if (pred_type %in% c("raw", "response")) {
722 expect_true(is.vector(pred))
723 } else {
724 expect_true(length(dim(pred)) >= 2L)
725 expect_null(colnames(pred))
726 }
727 }
728 })
729
730 test_that("Column names from multiclass are added to non-class predictions", {
731 y <- iris$Species
732 x <- iris[, -5L]
733 model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
734
735 pred_types_with_colnames <- c(
736 "response",
737 "raw",
738 "contrib",
739 "interaction"
740 )
741
742 for (pred_type in pred_types_with_colnames) {
743 pred <- predict(model, x, type = pred_type)
744 expect_equal(nrow(pred), nrow(x))
745 expect_equal(ncol(pred), 3L)
746 expect_equal(colnames(pred), levels(y))
747 }
748 })
749
750 test_that("Column names from multitarget are added to predictions", {
751 y <- data.frame(
752 ylog = log(mtcars$mpg),
753 ysqrt = sqrt(mtcars$mpg)
754 )
755 x <- mtcars[, -1L]
756 model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
757
758 pred_types_with_colnames <- c(
759 "response",
760 "raw",
761 "contrib",
762 "interaction"
763 )
764
765 for (pred_type in pred_types_with_colnames) {
766 pred <- predict(model, x, type = pred_type)
767 expect_equal(nrow(pred), nrow(x))
768 expect_equal(ncol(pred), 2L)
769 expect_equal(colnames(pred), colnames(y))
770 }
771 })
772
773 test_that("Column names from multiquantile are added to predictions", {
774 y <- mtcars$mpg
775 x <- mtcars[, -1L]
776 model <- xgboost(
777 x,
778 y,
779 nthreads = 1L,
780 nrounds = 3L,
781 max_depth = 2L,
782 objective = "reg:quantileerror",
783 quantile_alpha = c(0.25, 0.5, 0.75)
784 )
785
786 pred_types_with_colnames <- c(
787 "response",
788 "raw",
789 "contrib",
790 "interaction"
791 )
792
793 for (pred_type in pred_types_with_colnames) {
794 pred <- predict(model, x, type = pred_type)
795 expect_equal(nrow(pred), nrow(x))
796 expect_equal(ncol(pred), 3L)
797 expect_equal(colnames(pred), c("q0.25", "q0.5", "q0.75"))
798 }
799 })
800
801 test_that("Leaf predictions have multiple dimensions when needed", {
802 # single score, multiple trees
803 y <- mtcars$mpg
804 x <- mtcars[, -1L]
805 model <- xgboost(
806 x,
807 y,
808 nthreads = 1L,
809 nrounds = 4L,
810 max_depth = 2L,
811 objective = "reg:quantileerror",
812 quantile_alpha = 0.5
813 )
814 pred <- predict(model, x, type = "leaf")
815 expect_equal(dim(pred), c(nrow(x), 4L))
816 expect_equal(row.names(pred), row.names(x))
817 expect_null(colnames(pred))
818
819 # single score, single tree
820 model <- xgboost(
821 x,
822 y,
823 nthreads = 1L,
824 nrounds = 1L,
825 max_depth = 2L,
826 objective = "reg:quantileerror",
827 quantile_alpha = 0.5
828 )
829 pred <- predict(model, x, type = "leaf")
830 expect_equal(dim(pred), c(nrow(x), 1L))
831 expect_equal(row.names(pred), row.names(x))
832 expect_null(colnames(pred))
833
834 # multiple score, multiple trees
835 model <- xgboost(
836 x,
837 y,
838 nthreads = 1L,
839 nrounds = 4L,
840 max_depth = 2L,
841 objective = "reg:quantileerror",
842 quantile_alpha = c(0.25, 0.5, 0.75)
843 )
844 pred <- predict(model, x, type = "leaf")
845 expect_equal(dim(pred), c(nrow(x), 4L, 3L))
846 expect_equal(row.names(pred), row.names(x))
847 expect_null(colnames(pred))
848 expect_equal(dimnames(pred)[[3L]], c("q0.25", "q0.5", "q0.75"))
849
850 # multiple score, single tree
851 model <- xgboost(
852 x,
853 y,
854 nthreads = 1L,
855 nrounds = 1L,
856 max_depth = 2L,
857 objective = "reg:quantileerror",
858 quantile_alpha = c(0.25, 0.5, 0.75)
859 )
860 pred <- predict(model, x, type = "leaf")
861 expect_equal(dim(pred), c(nrow(x), 1L, 3L))
862 expect_equal(row.names(pred), row.names(x))
863 expect_null(colnames(pred))
864 expect_equal(dimnames(pred)[[3L]], c("q0.25", "q0.5", "q0.75"))
865
866 # parallel trees, single tree, single score
867 model <- xgboost(
868 x,
869 y,
870 nthreads = 1L,
871 nrounds = 1L,
872 max_depth = 2L,
873 objective = "count:poisson",
874 num_parallel_tree = 2L
875 )
876 pred <- predict(model, x, type = "leaf")
877 expect_equal(dim(pred), c(nrow(x), 1L, 2L))
878 expect_equal(row.names(pred), row.names(x))
879 expect_null(colnames(pred))
880 expect_null(dimnames(pred)[[3L]])
881
882 # num_parallel_tree>1 + multiple scores is not supported at the moment so no test for it.
883 })
884
885 test_that("Column names from multiclass are added to leaf predictions", {
886 y <- iris$Species
887 x <- iris[, -5L]
888 model <- xgboost(x, y, nthreads = 1L, nrounds = 4L, max_depth = 2L)
889 pred <- predict(model, x, type = "leaf")
890 expect_equal(dim(pred), c(nrow(x), 4L, 3L))
891 expect_equal(dimnames(pred)[[3L]], levels(y))
892
893 # Check also for a single tree
894 model <- xgboost(x, y, nthreads = 1L, nrounds = 1L, max_depth = 2L)
895 pred <- predict(model, x, type = "leaf")
896 expect_equal(dim(pred), c(nrow(x), 1L, 3L))
897 expect_equal(dimnames(pred)[[3L]], levels(y))
898 })
899
900 test_that("Column names from multitarget are added to leaf predictions", {
901 y <- data.frame(
902 ylog = log(mtcars$mpg),
903 ysqrt = sqrt(mtcars$mpg)
904 )
905 x <- mtcars[, -1L]
906 model <- xgboost(x, y, nthreads = 1L, nrounds = 4L, max_depth = 2L)
907 pred <- predict(model, x, type = "leaf")
908 expect_equal(dim(pred), c(nrow(x), 4L, 2L))
909 expect_equal(dimnames(pred)[[3L]], colnames(y))
910
911 # Check also for a single tree
912 model <- xgboost(x, y, nthreads = 1L, nrounds = 1L, max_depth = 2L)
913 pred <- predict(model, x, type = "leaf")
914 expect_equal(dim(pred), c(nrow(x), 1L, 2L))
915 expect_equal(dimnames(pred)[[3L]], colnames(y))
916 })
917
918 test_that("Column names from multiquantile are added to leaf predictions", {
919 y <- mtcars$mpg
920 x <- mtcars[, -1L]
921 model <- xgboost(
922 x,
923 y,
924 nthreads = 1L,
925 nrounds = 4L,
926 max_depth = 2L,
927 objective = "reg:quantileerror",
928 quantile_alpha = c(0.25, 0.5, 0.75)
929 )
930 pred <- predict(model, x, type = "leaf")
931 expect_equal(dim(pred), c(nrow(x), 4L, 3L))
932 expect_equal(dimnames(pred)[[3L]], c("q0.25", "q0.5", "q0.75"))
933
934 # Check also for a single tree
935 model <- xgboost(
936 x,
937 y,
938 nthreads = 1L,
939 nrounds = 1L,
940 max_depth = 2L,
941 objective = "reg:quantileerror",
942 quantile_alpha = c(0.25, 0.5, 0.75)
943 )
944 pred <- predict(model, x, type = "leaf")
945 expect_equal(dim(pred), c(nrow(x), 1L, 3L))
946 expect_equal(dimnames(pred)[[3L]], c("q0.25", "q0.5", "q0.75"))
947 })
948
949 test_that("Evaluation fraction leaves examples of all classes for training", {
950 # With minimal sample leave no remainder
951 lst_args <- list(
952 dmatrix_args = list(
953 data = matrix(seq(1, 4), ncol = 1L),
954 label = c(0, 0, 1, 1)
955 ),
956 metadata = list(
957 y_levels = c("a", "b")
958 ),
959 params = list(
960 seed = 123
961 )
962 )
963 for (retry in seq_len(10)) {
964 lst_args$params$seed <- retry
965 res <- process.eval.set(0.5, lst_args)
966 expect_equal(length(intersect(res$idx_train, res$idx_eval)), 0)
967 expect_equal(length(res$idx_train), 2L)
968 expect_equal(length(res$idx_eval), 2L)
969 expect_true(length(intersect(c(1L, 2L), res$idx_train)) >= 1L)
970 expect_true(length(intersect(c(3L, 4L), res$idx_train)) >= 1L)
971 }
972
973 # With minimal sample leaving some remainder
974 lst_args <- list(
975 dmatrix_args = list(
976 data = matrix(seq(1, 5), ncol = 1L),
977 label = c(0, 0, 1, 1, 1)
978 ),
979 metadata = list(
980 y_levels = c("a", "b")
981 ),
982 params = list(
983 seed = 123
984 )
985 )
986 for (retry in seq_len(20)) {
987 lst_args$params$seed <- retry
988 res <- process.eval.set(0.4, lst_args)
989 expect_equal(length(intersect(res$idx_train, res$idx_eval)), 0)
990 expect_equal(length(res$idx_train), 3L)
991 expect_equal(length(res$idx_eval), 2L)
992 expect_true(length(intersect(c(1L, 2L), res$idx_train)) >= 1L)
993 expect_true(length(intersect(c(3L, 4L, 5L), res$idx_train)) >= 1L)
994 }
995 })
996
997 test_that("'eval_set' as fraction works", {
998 y <- iris$Species
999 x <- iris[, -5L]
1000 model <- xgboost(
1001 x,
1002 y,
1003 base_margin = matrix(0.1, nrow = nrow(x), ncol = 3L),
1004 eval_set = 0.2,
1005 nthreads = 1L,
1006 nrounds = 4L,
1007 max_depth = 2L,
1008 verbosity = 0L
1009 )
1010 expect_true(hasName(attributes(model), "evaluation_log"))
1011 evaluation_log <- attributes(model)$evaluation_log
1012 expect_equal(nrow(evaluation_log), 4L)
1013 expect_true(hasName(evaluation_log, "eval_mlogloss"))
1014 expect_equal(length(attributes(model)$metadata$y_levels), 3L)
1015 })
1016
1017 test_that("Linear booster importance uses class names", {
1018 y <- iris$Species
1019 x <- iris[, -5L]
1020 model <- xgboost(
1021 x,
1022 y,
1023 nthreads = 1L,
1024 nrounds = 4L,
1025 verbosity = 0L,
1026 booster = "gblinear",
1027 learning_rate = 0.2
1028 )
1029 imp <- xgb.importance(model)
1030 expect_true(is.factor(imp$Class))
1031 expect_equal(levels(imp$Class), levels(y))
1032 })