Debian Codegraph @

R/xgboost.R

raw
1 prescreen.objective <- function(objective) {
2 if (!is.null(objective)) {
3 if (!is.character(objective) || length(objective) != 1L || is.na(objective)) {
4 stop("'objective' must be a single character/string variable.")
5 }
6
7 if (objective %in% .OBJECTIVES_NON_DEFAULT_MODE()) {
8 stop(
9 "Objectives with non-default prediction mode (",
10 paste(.OBJECTIVES_NON_DEFAULT_MODE(), collapse = ", "),
11 ") are not supported in 'xgboost()'. Try 'xgb.train()'."
12 )
13 }
14
15 if (objective %in% .RANKING_OBJECTIVES()) {
16 stop("Ranking objectives are not supported in 'xgboost()'. Try 'xgb.train()'.")
17 }
18 }
19 }
20
21 process.base.margin <- function(base_margin, nrows, ncols) {
22 if (!NROW(base_margin)) {
23 return(NULL)
24 }
25 if (is.array(base_margin) && length(dim(base_margin)) > 2) {
26 stop(
27 "'base_margin' should not have more than 2 dimensions for any objective (got: ",
28 length(dim(base_margin)),
29 " dimensions)."
30 )
31 }
32 if (inherits(base_margin, c("sparseMatrix", "sparseVector"))) {
33 warning(
34 "Got a sparse matrix type (class: ",
35 paste(class(base_margin), collapse = ", "),
36 ") for 'base_margin'. Will convert to dense matrix."
37 )
38 base_margin <- as.matrix(base_margin)
39 }
40 if (NROW(base_margin) != nrows) {
41 stop(
42 "'base_margin' has incorrect number of rows. Expected: ",
43 nrows,
44 ". Got: ",
45 NROW(base_margin)
46 )
47 }
48
49 if (ncols == 1L) {
50 if (inherits(base_margin, c("matrix", "data.frame"))) {
51 if (ncol(base_margin) != 1L) {
52 stop("'base_margin' should be a 1-d vector for the given objective and data.")
53 }
54 if (is.data.frame(base_margin)) {
55 base_margin <- base_margin[[1L]]
56 } else {
57 base_margin <- base_margin[, 1L]
58 }
59 }
60 if (!is.numeric(base_margin)) {
61 base_margin <- as.numeric(base_margin)
62 }
63 } else {
64 supported_multicol <- c("matrix", "data.frame")
65 if (!inherits(base_margin, supported_multicol)) {
66 stop(
67 "'base_margin' should be a matrix with ",
68 ncols,
69 " columns for the given objective and data. Got class: ",
70 paste(class(base_margin), collapse = ", ")
71 )
72 }
73 if (ncol(base_margin) != ncols) {
74 stop(
75 "'base_margin' has incorrect number of columns. Expected: ",
76 ncols,
77 ". Got: ",
78 ncol(base_margin)
79 )
80 }
81 if (!is.matrix(base_margin)) {
82 base_margin <- as.matrix(base_margin)
83 }
84 }
85
86 return(base_margin)
87 }
88
89 process.y.margin.and.objective <- function(
90 y,
91 base_margin,
92 objective,
93 params
94 ) {
95
96 if (!NROW(y)) {
97 stop("Passed empty 'y'.")
98 }
99
100 if (is.array(y) && length(dim(y)) > 2) {
101 stop(
102 "'y' should not have more than 2 dimensions for any objective (got: ",
103 length(dim(y)),
104 ")."
105 )
106 }
107
108 if (inherits(y, c("sparseMatrix", "sparseVector"))) {
109 warning(
110 "Got a sparse matrix type (class: ",
111 paste(class(y), collapse = ", "),
112 ") for 'y'. Will convert to dense matrix."
113 )
114 y <- as.matrix(y)
115 }
116
117 if (is.character(y)) {
118 if (!is.vector(y)) {
119 if (NCOL(y) > 1L) {
120 stop("Multi-column categorical 'y' is not supported.")
121 }
122 y <- as.vector(y)
123 }
124 y <- factor(y)
125 }
126
127 if (is.logical(y)) {
128 if (!is.vector(y)) {
129 if (NCOL(y) > 1L) {
130 stop("Multi-column logical/boolean 'y' is not supported.")
131 }
132 y <- as.vector(y)
133 }
134 y <- factor(y, c(FALSE, TRUE))
135 }
136
137 if (is.factor(y)) {
138
139 y_levels <- levels(y)
140 if (length(y_levels) < 2) {
141 stop("Factor 'y' has less than 2 levels.")
142 }
143 if (length(y_levels) == 2) {
144 if (is.null(objective)) {
145 objective <- "binary:logistic"
146 } else {
147 if (!(objective %in% .BINARY_CLASSIF_OBJECTIVES())) {
148 stop(
149 "Got binary 'y' - supported objectives for this data are: ",
150 paste(.BINARY_CLASSIF_OBJECTIVES(), collapse = ", "),
151 ". Was passed: ",
152 objective
153 )
154 }
155 }
156
157 if (!is.null(base_margin)) {
158 base_margin <- process.base.margin(base_margin, length(y), 1)
159 }
160
161 out <- list(
162 params = list(
163 objective = objective
164 ),
165 metadata = list(
166 y_levels = y_levels,
167 n_targets = 1
168 )
169 )
170 } else { # length(levels) > 2
171 if (is.null(objective)) {
172 objective <- "multi:softprob"
173 } else {
174 if (!(objective %in% .MULTICLASS_CLASSIF_OBJECTIVES())) {
175 stop(
176 "Got non-binary factor 'y' - supported objectives for this data are: ",
177 paste(.MULTICLASS_CLASSIF_OBJECTIVES(), collapse = ", "),
178 ". Was passed: ",
179 objective
180 )
181 }
182 }
183
184 if (!is.null(base_margin)) {
185 base_margin <- process.base.margin(base_margin, length(y), length(y_levels))
186 }
187
188 out <- list(
189 params = list(
190 objective = objective,
191 num_class = length(y_levels)
192 ),
193 metadata = list(
194 y_levels = y_levels,
195 n_targets = length(y_levels)
196 )
197 )
198 }
199
200 out$dmatrix_args <- list(
201 label = as.numeric(y) - 1,
202 base_margin = base_margin
203 )
204
205 } else if (inherits(y, "Surv")) {
206
207 y_attr <- attributes(y)
208 supported_surv_types <- c("left", "right", "interval")
209 if (!(y_attr$type %in% supported_surv_types)) {
210 stop(
211 "Survival objectives are only supported for types: ",
212 paste(supported_surv_types, collapse = ", "),
213 ". Was passed: ",
214 y_attr$type
215 )
216 }
217
218 if (is.null(objective)) {
219 objective <- "survival:aft"
220 } else {
221 if (y_attr$type == "right") {
222 if (!(objective %in% .SURVIVAL_RIGHT_CENSORING_OBJECTIVES())) {
223 stop(
224 "Got right-censored 'y' variable - supported objectives for this data are: ",
225 paste(.SURVIVAL_RIGHT_CENSORING_OBJECTIVES(), collapse = ", "),
226 ". Was passed: ",
227 objective
228 )
229 }
230 } else {
231 if (!(objective %in% .SURVIVAL_ALL_CENSORING_OBJECTIVES())) {
232 stop(
233 "Got ", y_attr$type, "-censored 'y' variable - supported objectives for this data are:",
234 paste(.SURVIVAL_ALL_CENSORING_OBJECTIVES(), collapse = ", "),
235 ". Was passed: ",
236 objective
237 )
238 }
239 }
240 }
241
242 if (!is.null(base_margin)) {
243 base_margin <- process.base.margin(base_margin, nrow(y), 1)
244 }
245
246 out <- list(
247 params = list(
248 objective = objective
249 ),
250 metadata = list(
251 n_targets = 1
252 )
253 )
254
255 # Note: the 'Surv' object class that is passed as 'y' might have either 2 or 3 columns
256 # depending on the type of censoring, and the last column in both cases is the one that
257 # indicates the observation type (e.g. censored / uncensored).
258 # In the case of interval censoring, the second column will not always have values with
259 # infinites filled in. For more information, see the code behind the 'print.Surv' method.
260
261 if (objective == "survival:cox") {
262 # Can only get here when using right censoring
263 if (y_attr$type != "right") {
264 stop("Internal error.")
265 }
266
267 out$dmatrix_args <- list(
268 label = y[, 1L] * (2 * (y[, 2L] - 0.5))
269 )
270
271 } else {
272 if (y_attr$type == "left") {
273 lb <- ifelse(
274 y[, 2L] == 0,
275 0,
276 y[, 1L]
277 )
278 ub <- y[, 1L]
279 out$dmatrix_args <- list(
280 label_lower_bound = lb,
281 label_upper_bound = ub
282 )
283 } else if (y_attr$type == "right") {
284 lb <- y[, 1L]
285 ub <- ifelse(
286 y[, 2L] == 0,
287 Inf,
288 y[, 1L]
289 )
290 out$dmatrix_args <- list(
291 label_lower_bound = lb,
292 label_upper_bound = ub
293 )
294 } else if (y_attr$type == "interval") {
295 out$dmatrix_args <- list(
296 label_lower_bound = ifelse(y[, 3L] == 2, 0, y[, 1L]),
297 label_upper_bound = ifelse(
298 y[, 3L] == 0, Inf,
299 ifelse(y[, 3L] == 3, y[, 2L], y[, 1L])
300 )
301 )
302 }
303
304 if (min(out$dmatrix_args$label_lower_bound) < 0) {
305 stop("Survival objectives are only defined for non-negative 'y'.")
306 }
307 }
308
309 out$dmatrix_args$base_margin <- base_margin
310
311 } else if (is.vector(y)) {
312
313 if (is.null(objective)) {
314 objective <- "reg:squarederror"
315 } else if (!(objective %in% .REGRESSION_OBJECTIVES())) {
316 stop(
317 "Got numeric 'y' - supported objectives for this data are: ",
318 paste(.REGRESSION_OBJECTIVES(), collapse = ", "),
319 ". Was passed: ",
320 objective
321 )
322 }
323
324 n_targets <- 1L
325 if (objective == "reg:quantileerror" && NROW(params$quantile_alpha) > 1) {
326 n_targets <- NROW(params$quantile_alpha)
327 }
328
329 if (!is.null(base_margin)) {
330 base_margin <- process.base.margin(base_margin, length(y), n_targets)
331 }
332
333 out <- list(
334 params = list(
335 objective = objective
336 ),
337 metadata = list(
338 n_targets = n_targets
339 ),
340 dmatrix_args = list(
341 label = as.numeric(y),
342 base_margin = base_margin
343 )
344 )
345
346 } else if (is.data.frame(y)) {
347 if (ncol(y) == 1L) {
348 return(process.y.margin.and.objective(y[[1L]], base_margin, objective, params))
349 }
350
351 if (is.null(objective)) {
352 objective <- "reg:squarederror"
353 } else if (!(objective %in% .MULTI_TARGET_OBJECTIVES())) {
354 stop(
355 "Got multi-column 'y' - supported objectives for this data are: ",
356 paste(.MULTI_TARGET_OBJECTIVES(), collapse = ", "),
357 ". Was passed: ",
358 objective
359 )
360 }
361
362 y_names <- names(y)
363 y <- lapply(y, function(x) {
364 if (!inherits(x, c("numeric", "integer"))) {
365 stop(
366 "Multi-target 'y' only supports 'numeric' and 'integer' types. Got: ",
367 paste(class(x), collapse = ", ")
368 )
369 }
370 return(as.numeric(x))
371 })
372 y <- as.data.frame(y) |> as.matrix()
373
374 if (!is.null(base_margin)) {
375 base_margin <- process.base.margin(base_margin, length(y), ncol(y))
376 }
377
378 out <- list(
379 params = list(
380 objective = objective
381 ),
382 dmatrix_args = list(
383 label = y,
384 base_margin = base_margin
385 ),
386 metadata = list(
387 y_names = y_names,
388 n_targets = ncol(y)
389 )
390 )
391
392 } else if (is.matrix(y)) {
393 if (ncol(y) == 1L) {
394 return(process.y.margin.and.objective(as.vector(y), base_margin, objective, params))
395 }
396
397 if (!is.null(objective) && !(objective %in% .MULTI_TARGET_OBJECTIVES())) {
398 stop(
399 "Got multi-column 'y' - supported objectives for this data are: ",
400 paste(.MULTI_TARGET_OBJECTIVES(), collapse = ", "),
401 ". Was passed: ",
402 objective
403 )
404 }
405 if (is.null(objective)) {
406 objective <- "reg:squarederror"
407 }
408
409 y_names <- colnames(y)
410 if (storage.mode(y) != "double") {
411 storage.mode(y) <- "double"
412 }
413
414 if (!is.null(base_margin)) {
415 base_margin <- process.base.margin(base_margin, nrow(y), ncol(y))
416 }
417
418 out <- list(
419 params = list(
420 objective = objective
421 ),
422 dmatrix_args = list(
423 label = y,
424 base_margin = base_margin
425 ),
426 metadata = list(
427 n_targets = ncol(y)
428 )
429 )
430
431 if (NROW(y_names) == ncol(y)) {
432 out$metadata$y_names <- y_names
433 }
434
435 } else {
436 stop("Passed 'y' object with unsupported class: ", paste(class(y), collapse = ", "))
437 }
438
439 return(out)
440 }
441
442 process.row.weights <- function(w, lst_args) {
443 if (!is.null(w)) {
444 if ("label" %in% names(lst_args$dmatrix_args)) {
445 nrow_y <- NROW(lst_args$dmatrix_args$label)
446 } else if ("label_lower_bound" %in% names(lst_args$dmatrix_args)) {
447 nrow_y <- length(lst_args$dmatrix_args$label_lower_bound)
448 } else {
449 stop("Internal error.")
450 }
451 if (!is.numeric(w)) {
452 w <- as.numeric(w)
453 }
454 if (length(w) != nrow_y) {
455 stop(
456 "'weights' must be a 1-d vector with the same length as 'y' (",
457 length(w), " vs. ", nrow_y, ")."
458 )
459 }
460 lst_args$dmatrix_args$weight <- w
461 }
462 return(lst_args)
463 }
464
465 check.nthreads <- function(nthreads) {
466 if (is.null(nthreads)) {
467 return(1L)
468 }
469 if (!inherits(nthreads, c("numeric", "integer")) || !NROW(nthreads)) {
470 stop("'nthreads' must be a positive scalar value.")
471 }
472 if (length(nthreads) > 1L) {
473 nthreads <- utils::head(nthreads, 1L)
474 }
475 if (is.na(nthreads) || nthreads < 0) {
476 stop("Passed invalid 'nthreads': ", nthreads)
477 }
478 if (is.numeric(nthreads)) {
479 if (floor(nthreads) != nthreads) {
480 stop("'nthreads' must be an integer.")
481 }
482 }
483 return(as.integer(nthreads))
484 }
485
486 check.can.use.qdm <- function(x, params, eval_set) {
487 if ("booster" %in% names(params)) {
488 if (params$booster == "gblinear") {
489 return(FALSE)
490 }
491 }
492 if ("tree_method" %in% names(params)) {
493 if (params$tree_method %in% c("exact", "approx")) {
494 return(FALSE)
495 }
496 }
497 if (NROW(eval_set)) {
498 return(FALSE)
499 }
500 return(TRUE)
501 }
502
503 process.x.and.col.args <- function(
504 x,
505 monotone_constraints,
506 interaction_constraints,
507 feature_weights,
508 lst_args,
509 use_qdm
510 ) {
511 if (is.null(x)) {
512 stop("'x' cannot be NULL.")
513 }
514 if (inherits(x, "xgb.DMatrix")) {
515 stop("Cannot pass 'xgb.DMatrix' as 'x' to 'xgboost()'. Try 'xgb.train()' instead.")
516 }
517 supported_x_types <- c("data.frame", "matrix", "dgTMatrix", "dgCMatrix", "dgRMatrix")
518 if (!inherits(x, supported_x_types)) {
519 stop(
520 "'x' must be one of the following classes: ",
521 paste(supported_x_types, collapse = ", "),
522 ". Got: ",
523 paste(class(x), collapse = ", ")
524 )
525 }
526 if (use_qdm && inherits(x, "sparseMatrix") && !inherits(x, "dgRMatrix")) {
527 x <- methods::as(x, "RsparseMatrix")
528 if (!inherits(x, "RsparseMatrix")) {
529 stop("Internal error: casting sparse matrix did not yield 'dgRMatrix'.")
530 }
531 }
532
533 if (NROW(feature_weights)) {
534 if (is.list(feature_weights)) {
535 feature_weights <- unlist(feature_weights)
536 }
537 if (!inherits(feature_weights, c("numeric", "integer"))) {
538 stop("'feature_weights' must be a numeric vector or named list matching to columns of 'x'.")
539 }
540 if (NROW(names(feature_weights)) && NROW(colnames(x))) {
541 matched <- match(colnames(x), names(feature_weights))
542 matched <- matched[!is.na(matched)]
543 matched <- matched[!duplicated(matched)]
544 if (length(matched) > 0 && length(matched) < length(feature_weights)) {
545 stop(
546 "'feature_weights' names do not contain all columns of 'x'. Missing: ",
547 utils::head(setdiff(colnames(x), names(feature_weights)))
548 )
549 }
550 if (length(matched)) {
551 feature_weights <- feature_weights[matched]
552 } else {
553 warning("Names of 'feature_weights' do not match with 'x'. Names will be ignored.")
554 }
555 }
556
557 lst_args$dmatrix_args$feature_weights <- unname(feature_weights)
558 }
559
560 if (NROW(monotone_constraints)) {
561
562 if (NROW(monotone_constraints) > ncol(x)) {
563 stop(
564 "'monotone_constraints' contains more entries than there are columns in 'x' (",
565 NROW(monotone_constraints), " vs. ", ncol(x), ")."
566 )
567 }
568
569 if (is.list(monotone_constraints)) {
570
571 if (!NROW(names(monotone_constraints))) {
572 stop(
573 "If passing 'monotone_constraints' as a named list,",
574 " must have names matching to columns of 'x'."
575 )
576 }
577 if (!NROW(colnames(x))) {
578 stop("If passing 'monotone_constraints' as a named list, 'x' must have column names.")
579 }
580 if (anyDuplicated(names(monotone_constraints))) {
581 stop(
582 "'monotone_constraints' contains duplicated names: ",
583 paste(
584 names(monotone_constraints)[duplicated(names(monotone_constraints))] |> utils::head(),
585 collapse = ", "
586 )
587 )
588 }
589 if (NROW(setdiff(names(monotone_constraints), colnames(x)))) {
590 stop(
591 "'monotone_constraints' contains column names not present in 'x': ",
592 paste(utils::head(names(monotone_constraints)), collapse = ", ")
593 )
594 }
595
596 vec_monotone_constr <- rep(0, ncol(x))
597 matched <- match(names(monotone_constraints), colnames(x))
598 vec_monotone_constr[matched] <- unlist(monotone_constraints)
599 lst_args$params$monotone_constraints <- unname(vec_monotone_constr)
600
601 } else if (inherits(monotone_constraints, c("numeric", "integer"))) {
602
603 if (NROW(names(monotone_constraints)) && NROW(colnames(x))) {
604 if (length(monotone_constraints) < ncol(x)) {
605 return(
606 process.x.and.col.args(
607 x,
608 as.list(monotone_constraints),
609 interaction_constraints,
610 feature_weights,
611 lst_args,
612 use_qdm
613 )
614 )
615 } else {
616 matched <- match(names(monotone_constraints), colnames(x))
617 matched <- matched[!is.na(matched)]
618 matched <- matched[!duplicated(matched)]
619 if (length(matched)) {
620 monotone_constraints <- monotone_constraints[matched]
621 } else {
622 warning("Names of 'monotone_constraints' do not match with 'x'. Names will be ignored.")
623 }
624 }
625 } else {
626 if (length(monotone_constraints) != ncol(x)) {
627 stop(
628 "If passing 'monotone_constraints' as unnamed vector or not using column names,",
629 " must have length matching to number of columns in 'x'. Got: ",
630 length(monotone_constraints), " (vs. ", ncol(x), ")"
631 )
632 }
633 }
634
635 lst_args$params$monotone_constraints <- unname(monotone_constraints)
636
637 } else if (is.character(monotone_constraints)) {
638 lst_args$params$monotone_constraints <- monotone_constraints
639 } else {
640 stop(
641 "Passed unsupported type for 'monotone_constraints': ",
642 paste(class(monotone_constraints), collapse = ", ")
643 )
644 }
645 }
646
647 if (NROW(interaction_constraints)) {
648 if (!is.list(interaction_constraints)) {
649 stop("'interaction_constraints' must be a list of vectors.")
650 }
651 cnames <- colnames(x)
652 lst_args$params$interaction_constraints <- lapply(interaction_constraints, function(idx) {
653 if (!NROW(idx)) {
654 stop("Elements in 'interaction_constraints' cannot be empty.")
655 }
656
657 if (is.character(idx)) {
658 if (!NROW(cnames)) {
659 stop(
660 "Passed a character vector for 'interaction_constraints', but 'x' ",
661 "has no column names to match them against."
662 )
663 }
664 out <- match(idx, cnames) - 1L
665 if (anyNA(out)) {
666 stop(
667 "'interaction_constraints' contains column names not present in 'x': ",
668 paste(utils::head(idx[which(is.na(out))]), collapse = ", ")
669 )
670 }
671 return(out)
672 } else if (inherits(idx, c("numeric", "integer"))) {
673 if (anyNA(idx)) {
674 stop("'interaction_constraints' cannot contain NA values.")
675 }
676 if (min(idx) < 1) {
677 stop("Column indices for 'interaction_constraints' must follow base-1 indexing.")
678 }
679 if (max(idx) > ncol(x)) {
680 stop("'interaction_constraints' contains invalid column indices.")
681 }
682 if (is.numeric(idx)) {
683 if (any(idx != floor(idx))) {
684 stop(
685 "'interaction_constraints' must contain only integer indices. Got non-integer: ",
686 paste(utils::head(idx[which(idx != floor(idx))]), collapse = ", ")
687 )
688 }
689 }
690 return(idx - 1L)
691 } else {
692 stop(
693 "Elements in 'interaction_constraints' must be vectors of types ",
694 "'integer', 'numeric', or 'character'. Got: ",
695 paste(class(idx), collapse = ", ")
696 )
697 }
698 })
699 }
700
701 lst_args$dmatrix_args$data <- x
702 return(lst_args)
703 }
704
705 process.eval.set <- function(eval_set, lst_args) {
706 if (!NROW(eval_set)) {
707 return(NULL)
708 }
709 nrows <- nrow(lst_args$dmatrix_args$data)
710 is_classif <- hasName(lst_args$metadata, "y_levels")
711 processed_y <- lst_args$dmatrix_args$label
712 eval_set <- as.vector(eval_set)
713 if (length(eval_set) == 1L) {
714
715 eval_set <- as.numeric(eval_set)
716 if (is.na(eval_set) || eval_set < 0 || eval_set >= 1) {
717 stop("'eval_set' as a fraction must be a number between zero and one (non-inclusive).")
718 }
719 if (eval_set == 0) {
720 return(NULL)
721 }
722 nrow_eval <- as.integer(round(nrows * eval_set, 0))
723 if (nrow_eval < 1) {
724 warning(
725 "Desired 'eval_set' fraction amounts to zero observations.",
726 " Will not create evaluation set."
727 )
728 return(NULL)
729 }
730 nrow_train <- nrows - nrow_eval
731 if (nrow_train < 2L) {
732 stop("Desired 'eval_set' fraction would leave less than 2 observations for training data.")
733 }
734 if (is_classif && nrow_train < length(lst_args$metadata$y_levels)) {
735 stop("Desired 'eval_set' fraction would not leave enough samples for each class of 'y'.")
736 }
737
738 seed <- lst_args$params$seed
739 if (!is.null(seed)) {
740 set.seed(seed)
741 }
742
743 idx_shuffled <- sample(nrows, nrows, replace = FALSE)
744 idx_eval <- idx_shuffled[seq(1L, nrow_eval)]
745 idx_train <- idx_shuffled[seq(nrow_eval + 1L, nrows)]
746 # Here we want the training set to include all of the classes of 'y' for classification
747 # objectives. If that condition doesn't hold with the random sample, then it forcibly
748 # makes a new random selection in such a way that the condition would always hold, by
749 # first sampling one random example of 'y' for training and then choosing the evaluation
750 # set from the remaining rows. The procedure here is quite inefficient, but there aren't
751 # enough random-related functions in base R to be able to construct an efficient version.
752 if (is_classif && length(unique(processed_y[idx_train])) < length(lst_args$metadata$y_levels)) {
753 # These are defined in order to avoid NOTEs from CRAN checks
754 # when using non-standard data.table evaluation with column names.
755 idx <- NULL
756 y <- NULL
757 ranked_idx <- NULL
758 chosen <- NULL
759
760 dt <- data.table::data.table(y = processed_y, idx = seq(1L, nrows))[
761 , .(
762 ranked_idx = seq(1L, .N),
763 chosen = rep(sample(.N, 1L), .N),
764 idx
765 )
766 , by = y
767 ]
768 min_idx_train <- dt[ranked_idx == chosen, idx]
769 rem_idx <- dt[ranked_idx != chosen, idx]
770 if (length(rem_idx) == nrow_eval) {
771 idx_train <- min_idx_train
772 idx_eval <- rem_idx
773 } else {
774 rem_idx <- rem_idx[sample(length(rem_idx), length(rem_idx), replace = FALSE)]
775 idx_eval <- rem_idx[seq(1L, nrow_eval)]
776 idx_train <- c(min_idx_train, rem_idx[seq(nrow_eval + 1L, length(rem_idx))])
777 }
778 }
779
780 } else {
781
782 if (any(eval_set != floor(eval_set))) {
783 stop("'eval_set' as indices must contain only integers.")
784 }
785 eval_set <- as.integer(eval_set)
786 idx_min <- min(eval_set)
787 if (is.na(idx_min) || idx_min < 1L) {
788 stop("'eval_set' contains invalid indices.")
789 }
790 idx_max <- max(eval_set)
791 if (is.na(idx_max) || idx_max > nrows) {
792 stop("'eval_set' contains row indices beyond the size of the input data.")
793 }
794 idx_train <- seq(1L, nrows)[-eval_set]
795 if (is_classif && length(unique(processed_y[idx_train])) < length(lst_args$metadata$y_levels)) {
796 warning("'eval_set' indices will leave some classes of 'y' outside of the training data.")
797 }
798 idx_eval <- eval_set
799
800 }
801
802 # Note: slicing is done in the constructed DMatrix object instead of in the
803 # original input, because objects from 'Matrix' might change class after
804 # being sliced (e.g. 'dgRMatrix' turns into 'dgCMatrix').
805 return(list(idx_train = idx_train, idx_eval = idx_eval))
806 }
807
808 check.early.stopping.rounds <- function(early_stopping_rounds, eval_set) {
809 if (is.null(early_stopping_rounds)) {
810 return(NULL)
811 }
812 if (is.null(eval_set)) {
813 stop("'early_stopping_rounds' requires passing 'eval_set'.")
814 }
815 if (NROW(early_stopping_rounds) != 1L) {
816 stop("'early_stopping_rounds' must be NULL or an integer greater than zero.")
817 }
818 early_stopping_rounds <- as.integer(early_stopping_rounds)
819 if (is.na(early_stopping_rounds) || early_stopping_rounds <= 0L) {
820 stop(
821 "'early_stopping_rounds' must be NULL or an integer greater than zero. Got: ",
822 early_stopping_rounds
823 )
824 }
825 return(early_stopping_rounds)
826 }
827
828 # nolint start: line_length_linter.
829 #' Fit XGBoost Model
830 #'
831 #' @export
832 #' @description
833 #' Fits an XGBoost model (boosted decision tree ensemble) to given x/y data.
834 #'
835 #' See the tutorial [Introduction to Boosted Trees](https://xgboost.readthedocs.io/en/stable/tutorials/model.html)
836 #' for a longer explanation of what XGBoost does, and the rest of the
837 #' [XGBoost Tutorials](https://xgboost.readthedocs.io/en/latest/tutorials/index.html) for further
838 #' explanations XGBoost's features and usage.
839 #'
840 #' This function is intended to provide a user-friendly interface for XGBoost that follows
841 #' R's conventions for model fitting and predictions, but which doesn't expose all of the
842 #' possible functionalities of the core XGBoost library.
843 #'
844 #' See [xgb.train()] for a more flexible low-level alternative which is similar across different
845 #' language bindings of XGBoost and which exposes additional functionalities such as training on
846 #' external memory data and learning-to-rank objectives.
847 #'
848 #' See also the [migration guide](https://xgboost.readthedocs.io/en/latest/R-package/migration_guide.html)
849 #' if coming from a previous version of XGBoost in the 1.x series.
850 #'
851 #' By default, most of the parameters here have a value of `NULL`, which signals XGBoost to use its
852 #' default value. Default values are automatically determined by the XGBoost core library, and are
853 #' subject to change over XGBoost library versions. Some of them might differ according to the
854 #' booster type (e.g. defaults for regularization are different for linear and tree-based boosters).
855 #' See [xgb.params()] and the [online documentation](https://xgboost.readthedocs.io/en/latest/parameter.html)
856 #' for more details about parameters - but note that some of the parameters are not supported in
857 #' the `xgboost()` interface.
858 #' @details
859 #' For package authors using 'xgboost' as a dependency, it is highly recommended to use
860 #' [xgb.train()] in package code instead of [xgboost()], since it has a more stable interface
861 #' and performs fewer data conversions and copies along the way.
862 #' @references
863 #' - Chen, Tianqi, and Carlos Guestrin. "Xgboost: A scalable tree boosting system."
864 #' Proceedings of the 22nd acm sigkdd international conference on knowledge discovery and
865 #' data mining. 2016.
866 #' - \url{https://xgboost.readthedocs.io/en/stable/}
867 #' @param x The features / covariates. Can be passed as:
868 #' - A numeric or integer `matrix`.
869 #' - A `data.frame`, in which all columns are one of the following types:
870 #' - `numeric`
871 #' - `integer`
872 #' - `logical`
873 #' - `factor`
874 #'
875 #' Columns of `factor` type will be assumed to be categorical, while other column types will
876 #' be assumed to be numeric.
877 #' - A sparse matrix from the `Matrix` package, either as `dgCMatrix` or `dgRMatrix` class.
878 #'
879 #' Note that categorical features are only supported for `data.frame` inputs, and are automatically
880 #' determined based on their types. See [xgb.train()] with [xgb.DMatrix()] for more flexible
881 #' variants that would allow something like categorical features on sparse matrices.
882 #' @param y The response variable. Allowed values are:
883 #' - A numeric or integer vector (for regression tasks).
884 #' - A factor or character vector (for binary and multi-class classification tasks).
885 #' - A logical (boolean) vector (for binary classification tasks).
886 #' - A numeric or integer matrix or `data.frame` with numeric/integer columns
887 #' (for multi-task regression tasks).
888 #' - A `Surv` object from the 'survival' package (for survival tasks).
889 #'
890 #' If `objective` is `NULL`, the right task will be determined automatically based on
891 #' the class of `y`.
892 #'
893 #' If `objective` is not `NULL`, it must match with the type of `y` - e.g. `factor` types of `y`
894 #' can only be used with classification objectives and vice-versa.
895 #'
896 #' For binary classification, the last factor level of `y` will be used as the "positive"
897 #' class - that is, the numbers from `predict` will reflect the probabilities of belonging to this
898 #' class instead of to the first factor level. If `y` is a `logical` vector, then `TRUE` will be
899 #' set as the last level.
900 #' @param objective Optimization objective to minimize based on the supplied data, to be passed
901 #' by name as a string / character (e.g. `reg:absoluteerror`). See the
902 #' [Learning Task Parameters](https://xgboost.readthedocs.io/en/stable/parameter.html#learning-task-parameters)
903 #' page and the [xgb.params()] documentation for more detailed information on allowed values.
904 #'
905 #' If `NULL` (the default), will be automatically determined from `y` according to the following
906 #' logic:
907 #' - If `y` is a factor with 2 levels, will use `binary:logistic`.
908 #' - If `y` is a factor with more than 2 levels, will use `multi:softprob` (number of classes
909 #' will be determined automatically, should not be passed under `params`).
910 #' - If `y` is a `Surv` object from the `survival` package, will use `survival:aft` (note that
911 #' the only types supported are left / right / interval censored).
912 #' - Otherwise, will use `reg:squarederror`.
913 #'
914 #' If `objective` is not `NULL`, it must match with the type of `y` - e.g. `factor` types of `y`
915 #' can only be used with classification objectives and vice-versa.
916 #'
917 #' Note that not all possible `objective` values supported by the core XGBoost library are allowed
918 #' here - for example, objectives which are a variation of another but with a different default
919 #' prediction type (e.g. `multi:softmax` vs. `multi:softprob`) are not allowed, and neither are
920 #' ranking objectives, nor custom objectives at the moment.
921 #'
922 #' Supported values are:
923 #' - `"reg:squarederror"`: regression with squared loss.
924 #' - `"reg:squaredlogerror"`: regression with squared log loss \eqn{\frac{1}{2}[log(pred + 1) - log(label + 1)]^2}. All input labels are required to be greater than -1. Also, see metric `rmsle` for possible issue with this objective.
925 #' - `"reg:pseudohubererror"`: regression with Pseudo Huber loss, a twice differentiable alternative to absolute loss.
926 #' - `"reg:absoluteerror"`: Regression with L1 error. When tree model is used, leaf value is refreshed after tree construction. If used in distributed training, the leaf value is calculated as the mean value from all workers, which is not guaranteed to be optimal.
927 #' - `"reg:quantileerror"`: Quantile loss, also known as "pinball loss". See later sections for its parameter and [Quantile Regression](https://xgboost.readthedocs.io/en/latest/python/examples/quantile_regression.html#sphx-glr-python-examples-quantile-regression-py) for a worked example.
928 #' - `"binary:logistic"`: logistic regression for binary classification, output probability
929 #' - `"binary:hinge"`: hinge loss for binary classification. This makes predictions of 0 or 1, rather than producing probabilities.
930 #' - `"count:poisson"`: Poisson regression for count data, output mean of Poisson distribution.
931 #' `"max_delta_step"` is set to 0.7 by default in Poisson regression (used to safeguard optimization)
932 #' - `"survival:cox"`: Cox regression for right censored survival time data (negative values are considered right censored).
933 #'
934 #' Note that predictions are returned on the hazard ratio scale (i.e., as HR = exp(marginal_prediction) in the proportional hazard function `h(t) = h0(t) * HR`).
935 #' - `"survival:aft"`: Accelerated failure time model for censored survival time data.
936 #' See [Survival Analysis with Accelerated Failure Time](https://xgboost.readthedocs.io/en/latest/tutorials/aft_survival_analysis.html) for details.
937 #' - `"multi:softprob"`: multi-class classification throgh multinomial logistic likelihood.
938 #' - `"reg:gamma"`: gamma regression with log-link. Output is a mean of gamma distribution. It might be useful, e.g., for modeling insurance claims severity, or for any outcome that might be [gamma-distributed](https://en.wikipedia.org/wiki/Gamma_distribution#Occurrence_and_applications).
939 #' - `"reg:tweedie"`: Tweedie regression with log-link. It might be useful, e.g., for modeling total loss in insurance, or for any outcome that might be [Tweedie-distributed](https://en.wikipedia.org/wiki/Tweedie_distribution#Occurrence_and_applications).
940 #'
941 #' The following values are \bold{NOT} supported by `xgboost`, but are supported by [xgb.train()]
942 #' (see [xgb.params()] for details):
943 #' - `"reg:logistic"`
944 #' - `"binary:logitraw"`
945 #' - `"multi:softmax"`
946 #' - `"rank:ndcg"`
947 #' - `"rank:map"`
948 #' - `"rank:pairwise"`
949 #' @param nrounds Number of boosting iterations / rounds.
950 #'
951 #' Note that the number of default boosting rounds here is not automatically tuned, and different
952 #' problems will have vastly different optimal numbers of boosting rounds.
953 #' @param weights Sample weights for each row in `x` and `y`. If `NULL` (the default), each row
954 #' will have the same weight.
955 #'
956 #' If not `NULL`, should be passed as a numeric vector with length matching to the number of rows in `x`.
957 #' @param verbosity Verbosity of printing messages. Valid values of 0 (silent), 1 (warning),
958 #' 2 (info), and 3 (debug).
959 #' @param monitor_training Whether to monitor objective optimization progress on the input data.
960 #' Note that same 'x' and 'y' data are used for both model fitting and evaluation.
961 #' @param eval_set Subset of the data to use as evaluation set. Can be passed as:
962 #' - A vector of row indices (base-1 numeration) indicating the observations that are to be designed
963 #' as evaluation data.
964 #' - A number between zero and one indicating a random fraction of the input data to use as
965 #' evaluation data. Note that the selection will be done uniformly at random, regardless of
966 #' argument `weights`.
967 #'
968 #' If passed, this subset of the data will be excluded from the training procedure, and the
969 #' evaluation metric(s) supplied under `eval_metric` will be calculated on this dataset after each
970 #' boosting iteration (pass `verbosity>0` to have these metrics printed during training). If
971 #' `eval_metric` is not passed, a default metric will be selected according to `objective`.
972 #'
973 #' If passing a fraction, in classification problems, the evaluation set will be chosen in such a
974 #' way that at least one observation of each class will be kept in the training data.
975 #'
976 #' For more elaborate evaluation variants (e.g. custom metrics, multiple evaluation sets, etc.),
977 #' one might want to use [xgb.train()] instead.
978 #' @param early_stopping_rounds Number of boosting rounds after which training will be stopped
979 #' if there is no improvement in performance (as measured by the last metric passed under
980 #' `eval_metric`, or by the default metric for the objective if `eval_metric` is not passed) on the
981 #' evaluation data from `eval_set`. Must pass `eval_set` in order to use this functionality.
982 #'
983 #' If `NULL`, early stopping will not be used.
984 #' @param print_every_n When passing `verbosity>0` and either `monitor_training=TRUE` or `eval_set`,
985 #' evaluation logs (metrics calculated on the training and/or evaluation data) will be printed every
986 #' nth iteration according to the value passed here. The first and last iteration are always
987 #' included regardless of this 'n'.
988 #'
989 #' Only has an effect when passing `verbosity>0`.
990 #' @param nthreads Number of parallel threads to use. If passing zero, will use all CPU threads.
991 #' @param seed Seed to use for random number generation. If passing `NULL`, will draw a random
992 #' number using R's PRNG system to use as seed.
993 #' @param monotone_constraints Optional monotonicity constraints for features.
994 #'
995 #' Can be passed either as a named list (when `x` has column names), or as a vector. If passed
996 #' as a vector and `x` has column names, will try to match the elements by name.
997 #'
998 #' A value of `+1` for a given feature makes the model predictions / scores constrained to be
999 #' a monotonically increasing function of that feature (that is, as the value of the feature
1000 #' increases, the model prediction cannot decrease), while a value of `-1` makes it a monotonically
1001 #' decreasing function. A value of zero imposes no constraint.
1002 #'
1003 #' The input for `monotone_constraints` can be a subset of the columns of `x` if named, in which
1004 #' case the columns that are not referred to in `monotone_constraints` will be assumed to have
1005 #' a value of zero (no constraint imposed on the model for those features).
1006 #'
1007 #' See the tutorial [Monotonic Constraints](https://xgboost.readthedocs.io/en/stable/tutorials/monotonic.html)
1008 #' for a more detailed explanation.
1009 #' @param interaction_constraints Constraints for interaction representing permitted interactions.
1010 #' The constraints must be specified in the form of a list of vectors referencing columns in the
1011 #' data, e.g. `list(c(1, 2), c(3, 4, 5))` (with these numbers being column indices, numeration
1012 #' starting at 1 - i.e. the first sublist references the first and second columns) or
1013 #' `list(c("Sepal.Length", "Sepal.Width"), c("Petal.Length", "Petal.Width"))` (references
1014 #' columns by names), where each vector is a group of indices of features that are allowed to
1015 #' interact with each other.
1016 #'
1017 #' See the tutorial [Feature Interaction Constraints](https://xgboost.readthedocs.io/en/stable/tutorials/feature_interaction_constraint.html)
1018 #' for more information.
1019 #' @param feature_weights Feature weights for column sampling.
1020 #'
1021 #' Can be passed either as a vector with length matching to columns of `x`, or as a named
1022 #' list (only if `x` has column names) with names matching to columns of 'x'. If it is a
1023 #' named vector, will try to match the entries to column names of `x` by name.
1024 #'
1025 #' If `NULL` (the default), all columns will have the same weight.
1026 #' @param base_margin Base margin used for boosting from existing model.
1027 #'
1028 #' If passing it, will start the gradient boosting procedure from the scores that are provided
1029 #' here - for example, one can pass the raw scores from a previous model, or some per-observation
1030 #' offset, or similar.
1031 #'
1032 #' Should be either a numeric vector or numeric matrix (for multi-class and multi-target objectives)
1033 #' with the same number of rows as `x` and number of columns corresponding to number of optimization
1034 #' targets, and should be in the untransformed scale (for example, for objective `binary:logistic`,
1035 #' it should have log-odds, not probabilities; and for objective `multi:softprob`, should have
1036 #' number of columns matching to number of classes in the data).
1037 #'
1038 #' Note that, if it contains more than one column, then columns will not be matched by name to
1039 #' the corresponding `y` - `base_margin` should have the same column order that the model will use
1040 #' (for example, for objective `multi:softprob`, columns of `base_margin` will be matched against
1041 #' `levels(y)` by their position, regardless of what `colnames(base_margin)` returns).
1042 #'
1043 #' If `NULL`, will start from zero, but note that for most objectives, an intercept is usually
1044 #' added (controllable through parameter `base_score` instead) when `base_margin` is not passed.
1045 #' @param min_split_loss (for Tree Booster) (default=0, alias: `gamma`)
1046 #' Minimum loss reduction required to make a further partition on a leaf node of the tree. The larger `min_split_loss` is, the more conservative the algorithm will be. Note that a tree where no splits were made might still contain a single terminal node with a non-zero score.
1047 #'
1048 #' range: \eqn{[0, \infty)}
1049 #' @param learning_rate (alias: `eta`)
1050 #' Step size shrinkage used in update to prevent overfitting. After each boosting step, we can directly get the weights of new features, and `learning_rate` shrinks the feature weights to make the boosting process more conservative.
1051 #' - range: \eqn{[0,1]}
1052 #' - default value: 0.3 for tree-based boosters, 0.5 for linear booster.
1053 #' @param reg_lambda (alias: `lambda`)
1054 #' - For tree-based boosters:
1055 #' - L2 regularization term on weights. Increasing this value will make model more conservative.
1056 #' - default: 1
1057 #' - range: \eqn{[0, \infty]}
1058 #' - For linear booster:
1059 #' - L2 regularization term on weights. Increasing this value will make model more conservative. Normalised to number of training examples.
1060 #' - default: 0
1061 #' - range: \eqn{[0, \infty)}
1062 #' @param reg_alpha (alias: `reg_alpha`)
1063 #' - L1 regularization term on weights. Increasing this value will make model more conservative.
1064 #' - For the linear booster, it's normalised to number of training examples.
1065 #' - default: 0
1066 #' - range: \eqn{[0, \infty)}
1067 #' @param updater (for Linear Booster) (default= `"shotgun"`)
1068 #' Choice of algorithm to fit linear model
1069 #' - `"shotgun"`: Parallel coordinate descent algorithm based on shotgun algorithm. Uses 'hogwild' parallelism and therefore produces a nondeterministic solution on each run.
1070 #' - `"coord_descent"`: Ordinary coordinate descent algorithm. Also multithreaded but still produces a deterministic solution. When the `device` parameter is set to `"cuda"` or `"gpu"`, a GPU variant would be used.
1071 #' @inheritParams xgb.params
1072 #' @inheritParams xgb.train
1073 #' @return A model object, inheriting from both `xgboost` and `xgb.Booster`. Compared to the regular
1074 #' `xgb.Booster` model class produced by [xgb.train()], this `xgboost` class will have an
1075 #' additional attribute `metadata` containing information which is used for formatting prediction
1076 #' outputs, such as class names for classification problems.
1077 #'
1078 #' @examples
1079 #' data(mtcars)
1080 #'
1081 #' # Fit a small regression model on the mtcars data
1082 #' model_regression <- xgboost(mtcars[, -1], mtcars$mpg, nthreads = 1, nrounds = 3)
1083 #' predict(model_regression, mtcars, validate_features = TRUE)
1084 #'
1085 #' # Task objective is determined automatically according to the type of 'y'
1086 #' data(iris)
1087 #' model_classif <- xgboost(iris[, -5], iris$Species, nthreads = 1, nrounds = 5)
1088 #' predict(model_classif, iris[1:10,])
1089 #' predict(model_classif, iris[1:10,], type = "class")
1090 #'
1091 #' # Can nevertheless choose a non-default objective if needed
1092 #' model_poisson <- xgboost(
1093 #' mtcars[, -1], mtcars$mpg,
1094 #' objective = "count:poisson",
1095 #' nthreads = 1,
1096 #' nrounds = 3
1097 #' )
1098 #'
1099 #' # Can calculate evaluation metrics during boosting rounds
1100 #' data(ToothGrowth)
1101 #' xgboost(
1102 #' ToothGrowth[, c("len", "dose")],
1103 #' ToothGrowth$supp,
1104 #' eval_metric = c("auc", "logloss"),
1105 #' eval_set = 0.2,
1106 #' monitor_training = TRUE,
1107 #' verbosity = 1,
1108 #' nthreads = 1,
1109 #' nrounds = 3
1110 #' )
1111 xgboost <- function(
1112 x,
1113 y,
1114 objective = NULL,
1115 nrounds = 100L,
1116 max_depth = NULL,
1117 learning_rate = NULL,
1118 min_child_weight = NULL,
1119 min_split_loss = NULL,
1120 reg_lambda = NULL,
1121 weights = NULL,
1122 verbosity = if (is.null(eval_set)) 0L else 1L,
1123 monitor_training = verbosity > 0,
1124 eval_set = NULL,
1125 early_stopping_rounds = NULL,
1126 print_every_n = 1L,
1127 eval_metric = NULL,
1128 nthreads = parallel::detectCores(),
1129 seed = 0L,
1130 base_margin = NULL,
1131 monotone_constraints = NULL,
1132 interaction_constraints = NULL,
1133 reg_alpha = NULL,
1134 max_bin = NULL,
1135 max_leaves = NULL,
1136 booster = NULL,
1137 subsample = NULL,
1138 sampling_method = NULL,
1139 feature_weights = NULL,
1140 colsample_bytree = NULL,
1141 colsample_bylevel = NULL,
1142 colsample_bynode = NULL,
1143 tree_method = NULL,
1144 max_delta_step = NULL,
1145 scale_pos_weight = NULL,
1146 updater = NULL,
1147 grow_policy = NULL,
1148 num_parallel_tree = NULL,
1149 multi_strategy = NULL,
1150 base_score = NULL,
1151 seed_per_iteration = NULL,
1152 device = NULL,
1153 disable_default_eval_metric = NULL,
1154 use_rmm = NULL,
1155 max_cached_hist_node = NULL,
1156 max_cat_to_onehot = NULL,
1157 max_cat_threshold = NULL,
1158 sample_type = NULL,
1159 normalize_type = NULL,
1160 rate_drop = NULL,
1161 one_drop = NULL,
1162 skip_drop = NULL,
1163 feature_selector = NULL,
1164 top_k = NULL,
1165 tweedie_variance_power = NULL,
1166 huber_slope = NULL,
1167 quantile_alpha = NULL,
1168 aft_loss_distribution = NULL,
1169 ...
1170 ) {
1171 # nolint end
1172 check.deprecation(deprecated_xgboost_params, match.call(), ...)
1173 params <- as.list(environment())
1174 params <- params[
1175 (names(params) %in% formalArgs(xgb.params))
1176 & !sapply(params, is.null)
1177 & !(names(params) %in% c( # these undergo additional processing here
1178 "objective", "base_margin", "monotone_constraints", "interaction_constraints"
1179 ))
1180 ]
1181
1182 prescreen.objective(objective)
1183 use_qdm <- check.can.use.qdm(x, params, eval_set)
1184 lst_args <- process.y.margin.and.objective(y, base_margin, objective, params)
1185 lst_args <- process.row.weights(weights, lst_args)
1186 lst_args <- process.x.and.col.args(
1187 x,
1188 monotone_constraints,
1189 interaction_constraints,
1190 feature_weights,
1191 lst_args,
1192 use_qdm
1193 )
1194 eval_set <- process.eval.set(eval_set, lst_args)
1195
1196 if (use_qdm && hasName(params, "max_bin")) {
1197 lst_args$dmatrix_args$max_bin <- params$max_bin
1198 }
1199
1200 nthreads <- check.nthreads(nthreads)
1201 lst_args$dmatrix_args$nthread <- nthreads
1202 lst_args$params$nthread <- nthreads
1203
1204 params <- c(lst_args$params, params)
1205 params$verbosity <- verbosity
1206
1207 fn_dm <- if (use_qdm) xgb.QuantileDMatrix else xgb.DMatrix
1208 dm <- do.call(fn_dm, lst_args$dmatrix_args)
1209 if (!is.null(eval_set)) {
1210 dm_eval <- xgb.slice.DMatrix(dm, eval_set$idx_eval)
1211 dm <- xgb.slice.DMatrix(dm, eval_set$idx_train)
1212 }
1213 evals <- list()
1214 if (monitor_training) {
1215 evals <- list(train = dm)
1216 }
1217 if (!is.null(eval_set)) {
1218 evals <- c(evals, list(eval = dm_eval))
1219 }
1220 model <- xgb.train(
1221 params = params,
1222 data = dm,
1223 nrounds = nrounds,
1224 verbose = verbosity,
1225 print_every_n = print_every_n,
1226 evals = evals
1227 )
1228 attributes(model)$metadata <- lst_args$metadata
1229 attributes(model)$call <- match.call()
1230 class(model) <- c("xgboost", class(model))
1231 return(model)
1232 }
1233
1234 #' @title Compute predictions from XGBoost model on new data
1235 #' @description Predict values on data based on XGBoost model.
1236 #' @param object An XGBoost model object of class `xgboost`, as produced by function [xgboost()].
1237 #'
1238 #' Note that there is also a lower-level [predict.xgb.Booster()] method for models of class
1239 #' `xgb.Booster` as produced by [xgb.train()], which can also be used for `xgboost` class models as
1240 #' an alternative that performs fewer validations and post-processings.
1241 #' @param newdata Data on which to compute predictions from the model passed in `object`. Supported
1242 #' input classes are:
1243 #' - Data Frames (class `data.frame` from base R and subclasses like `data.table`).
1244 #' - Matrices (class `matrix` from base R).
1245 #' - Sparse matrices from package `Matrix`, either as class `dgRMatrix` (CSR) or `dgCMatrix` (CSC).
1246 #' - Sparse vectors from package `Matrix`, which will be interpreted as containing a single
1247 #' observation.
1248 #'
1249 #' In the case of data frames, if there are any categorical features, they should be of class
1250 #' `factor` and should have the same levels as the `factor` columns of the data from which the model
1251 #' was constructed. Any columns with type other than `factor` will be interpreted as numeric.
1252 #'
1253 #' If there are named columns and the model was fitted to data with named columns, they will be
1254 #' matched by name by default (see `validate_features`).
1255 #' @param type Type of prediction to make. Supported options are:
1256 #' - `"response"`: will output model predictions on the scale of the response variable (e.g.
1257 #' probabilities of belonging to the last class in the case of binary classification). Result will
1258 #' be either a numeric vector with length matching to rows in `newdata`, or a numeric matrix with
1259 #' shape `[nrows(newdata), nscores]` (for objectives that produce more than one score per
1260 #' observation such as multi-class classification or multi-quantile regression).
1261 #' - `"raw"`: will output the unprocessed boosting scores (e.g. log-odds in the case of objective
1262 #' `binary:logistic`). Same output shape and type as for `"response"`.
1263 #' - `"class"`: will output the class with the highest predicted probability, returned as a `factor`
1264 #' (only applicable to classification objectives) with length matching to rows in `newdata`.
1265 #' - `"leaf"`: will output the terminal node indices of each observation across each tree, as an
1266 #' integer matrix of shape `[nrows(newdata), ntrees]`, or as an integer array with an extra one or
1267 #' two dimensions, up to `[nrows(newdata), ntrees, nscores, n_parallel_trees]` for models that
1268 #' produce more than one score per tree and/or which have more than one parallel tree (e.g.
1269 #' random forests).
1270 #'
1271 #' Only applicable to tree-based boosters (not `gblinear`).
1272 #' - `"contrib"`: will produce per-feature contribution estimates towards the model score for a
1273 #' given observation, based on SHAP values. The contribution values are on the scale of
1274 #' untransformed margin (e.g., for binary classification, the values are log-odds deviations from
1275 #' the baseline).
1276 #'
1277 #' Output will be a numeric matrix with shape `[nrows, nfeatures+1]`, with the intercept being the
1278 #' last feature, or a numeric array with shape `[nrows, nscores, nfeatures+1]` if the model
1279 #' produces more than one score per observation.
1280 #' - `"interaction"`: similar to `"contrib"`, but computing SHAP values of contributions of
1281 #' interaction of each pair of features. Note that this operation might be rather expensive in
1282 #' terms of compute and memory.
1283 #'
1284 #' Since it quadratically depends on the number of features, it is recommended to perform
1285 #' selection of the most important features first.
1286 #'
1287 #' Output will be a numeric array of shape `[nrows, nfeatures+1, nfeatures+1]`, or shape
1288 #' `[nrows, nscores, nfeatures+1, nfeatures+1]` (for objectives that produce more than one score
1289 #' per observation).
1290 #' @param base_margin Base margin used for boosting from existing model (raw score that gets added to
1291 #' all observations independently of the trees in the model).
1292 #'
1293 #' If supplied, should be either a vector with length equal to the number of rows in `newdata`
1294 #' (for objectives which produces a single score per observation), or a matrix with number of
1295 #' rows matching to the number rows in `newdata` and number of columns matching to the number
1296 #' of scores estimated by the model (e.g. number of classes for multi-class classification).
1297 #' @param iteration_range Sequence of rounds/iterations from the model to use for prediction, specified by passing
1298 #' a two-dimensional vector with the start and end numbers in the sequence (same format as R's `seq` - i.e.
1299 #' base-1 indexing, and inclusive of both ends).
1300 #'
1301 #' For example, passing `c(1,20)` will predict using the first twenty iterations, while passing `c(1,1)` will
1302 #' predict using only the first one.
1303 #'
1304 #' If passing `NULL`, will either stop at the best iteration if the model used early stopping, or use all
1305 #' of the iterations (rounds) otherwise.
1306 #'
1307 #' If passing "all", will use all of the rounds regardless of whether the model had early stopping or not.
1308 #'
1309 #' Not applicable to `gblinear` booster.
1310 #' @param validate_features Validate that the feature names in the data match to the feature names
1311 #' in the column, and reorder them in the data otherwise.
1312 #'
1313 #' If passing `FALSE`, it is assumed that the feature names and types are the same,
1314 #' and come in the same order as in the training data.
1315 #'
1316 #' Be aware that this only applies to column names and not to factor levels in categorical columns.
1317 #'
1318 #' Note that this check might add some sizable latency to the predictions, so it's
1319 #' recommended to disable it for performance-sensitive applications.
1320 #' @param ... Not used.
1321 #' @return Either a numeric vector (for 1D outputs), numeric matrix (for 2D outputs), numeric array
1322 #' (for 3D and higher), or `factor` (for class predictions). See documentation for parameter `type`
1323 #' for details about what the output type and shape will be.
1324 #' @method predict xgboost
1325 #' @export
1326 #' @examples
1327 #' data("ToothGrowth")
1328 #' y <- ToothGrowth$supp
1329 #' x <- ToothGrowth[, -2L]
1330 #' model <- xgboost(x, y, nthreads = 1L, nrounds = 3L, max_depth = 2L)
1331 #' pred_prob <- predict(model, x[1:5, ], type = "response")
1332 #' pred_raw <- predict(model, x[1:5, ], type = "raw")
1333 #' pred_class <- predict(model, x[1:5, ], type = "class")
1334 #'
1335 #' # Relationships between these
1336 #' manual_probs <- 1 / (1 + exp(-pred_raw))
1337 #' manual_class <- ifelse(manual_probs < 0.5, levels(y)[1], levels(y)[2])
1338 #'
1339 #' # They should match up to numerical precision
1340 #' round(pred_prob, 6) == round(manual_probs, 6)
1341 #' pred_class == manual_class
1342 predict.xgboost <- function(
1343 object,
1344 newdata,
1345 type = "response",
1346 base_margin = NULL,
1347 iteration_range = NULL,
1348 validate_features = TRUE,
1349 ...
1350 ) {
1351 if (inherits(newdata, "xgb.DMatrix")) {
1352 stop(
1353 "Predictions on 'xgb.DMatrix' objects are not supported with 'xgboost' class.",
1354 " Try 'xgb.train' or 'predict.xgb.Booster'."
1355 )
1356 }
1357
1358 outputmargin <- FALSE
1359 predleaf <- FALSE
1360 predcontrib <- FALSE
1361 predinteraction <- FALSE
1362 pred_class <- FALSE
1363 strict_shape <- FALSE
1364 allowed_types <- c(
1365 "response",
1366 "raw",
1367 "class",
1368 "leaf",
1369 "contrib",
1370 "interaction"
1371 )
1372 type <- head(type, 1L)
1373 if (!is.character(type) || !(type %in% allowed_types)) {
1374 stop("'type' must be one of: ", paste(allowed_types, collapse = ", "))
1375 }
1376
1377 if (type != "response") {
1378 switch(
1379 type,
1380 "raw" = {
1381 outputmargin <- TRUE
1382 }, "class" = {
1383 if (is.null(attributes(object)$metadata$y_levels)) {
1384 stop("Prediction type 'class' is only for classification objectives.")
1385 }
1386 pred_class <- TRUE
1387 outputmargin <- TRUE
1388 }, "leaf" = {
1389 predleaf <- TRUE
1390 strict_shape <- TRUE # required for 3D and 4D outputs
1391 }, "contrib" = {
1392 predcontrib <- TRUE
1393 }, "interaction" = {
1394 predinteraction <- TRUE
1395 }
1396 )
1397 }
1398 out <- predict.xgb.Booster(
1399 object,
1400 newdata,
1401 outputmargin = outputmargin,
1402 predleaf = predleaf,
1403 predcontrib = predcontrib,
1404 predinteraction = predinteraction,
1405 iterationrange = iteration_range,
1406 strict_shape = strict_shape,
1407 validate_features = validate_features,
1408 base_margin = base_margin
1409 )
1410
1411 if (strict_shape) {
1412 # Should only end up here for leaf predictions
1413 out_dims <- dim(out)
1414 dims_remove <- integer()
1415 if (out_dims[3L] == 1L) {
1416 dims_remove <- c(dims_remove, -3L)
1417 }
1418 if (length(out_dims) >= 4L && out_dims[4L] == 1L) {
1419 dims_remove <- c(dims_remove, -4L)
1420 }
1421 if (length(dims_remove)) {
1422 new_dimnames <- dimnames(out)[dims_remove]
1423 dim(out) <- out_dims[dims_remove]
1424 dimnames(out) <- new_dimnames
1425 }
1426 }
1427
1428 if (pred_class) {
1429
1430 if (is.null(dim(out))) {
1431 out <- as.integer(out >= 0) + 1L
1432 } else {
1433 out <- max.col(out, ties.method = "first")
1434 }
1435 attr_out <- attributes(out)
1436 attr_out$class <- "factor"
1437 attr_out$levels <- attributes(object)$metadata$y_levels
1438 attributes(out) <- attr_out
1439
1440 } else if (NCOL(out) > 1L || (strict_shape && length(dim(out)) >= 3L)) {
1441
1442 names_use <- NULL
1443 if (NROW(attributes(object)$metadata$y_levels) > 2L) {
1444 names_use <- attributes(object)$metadata$y_levels
1445 } else if (NROW(attributes(object)$metadata$y_names)) {
1446 names_use <- attributes(object)$metadata$y_names
1447 } else if (NROW(attributes(object)$params$quantile_alpha) > 1L) {
1448 names_use <- paste0("q", attributes(object)$params$quantile_alpha)
1449 if (anyDuplicated(names_use)) {
1450 warning("Cannot add quantile names to output due to clashes in their character conversions")
1451 names_use <- NULL
1452 }
1453 }
1454 if (NROW(names_use)) {
1455 dimnames_out <- dimnames(out)
1456 dim_with_names <- if (type == "leaf") 3L else 2L
1457 dimnames_out[[dim_with_names]] <- names_use
1458 .Call(XGSetArrayDimNamesInplace_R, out, dimnames_out)
1459 }
1460
1461 }
1462
1463 return(out)
1464 }
1465
1466 #' @title Print info from XGBoost model
1467 #' @description Prints basic properties of an XGBoost model object.
1468 #' @param x An XGBoost model object of class `xgboost`, as produced by function [xgboost()].
1469 #' @param ... Not used.
1470 #' @return Same object `x`, after printing its info.
1471 #' @method print xgboost
1472 #' @export
1473 print.xgboost <- function(x, ...) {
1474 cat("XGBoost model object\n")
1475 cat("Call:\n ")
1476 print(attributes(x)$call)
1477 cat("Objective: ", attributes(x)$params$objective, "\n", sep = "")
1478 cat("Number of iterations: ", xgb.get.num.boosted.rounds(x), "\n", sep = "")
1479 cat("Number of features: ", xgb.num_feature(x), "\n", sep = "")
1480
1481 printable_head <- function(v) {
1482 v_sub <- utils::head(v, 5L)
1483 return(
1484 sprintf(
1485 "%s%s",
1486 paste(v_sub, collapse = ", "),
1487 ifelse(length(v_sub) < length(v), ", ...", "")
1488 )
1489 )
1490 }
1491
1492 if (NROW(attributes(x)$metadata$y_levels)) {
1493 cat(
1494 "Classes: ",
1495 printable_head(attributes(x)$metadata$y_levels),
1496 "\n",
1497 sep = ""
1498 )
1499 } else if (NROW(attributes(x)$params$quantile_alpha)) {
1500 cat(
1501 "Prediction quantile",
1502 ifelse(length(attributes(x)$params$quantile_alpha) > 1L, "s", ""),
1503 ": ",
1504 printable_head(attributes(x)$params$quantile_alpha),
1505 "\n",
1506 sep = ""
1507 )
1508 } else if (NROW(attributes(x)$metadata$y_names)) {
1509 cat(
1510 "Prediction targets: ",
1511 printable_head(attributes(x)$metadata$y_names),
1512 "\n",
1513 sep = ""
1514 )
1515 } else if (attributes(x)$metadata$n_targets > 1L) {
1516 cat(
1517 "Number of predition targets: ",
1518 attributes(x)$metadata$n_targets,
1519 "\n",
1520 sep = ""
1521 )
1522 }
1523
1524 return(x)
1525 }
1526
1527
1528 #' Training part from Mushroom Data Set
1529 #'
1530 #' This data set is originally from the Mushroom data set,
1531 #' UCI Machine Learning Repository.
1532 #'
1533 #' It includes the following fields:
1534 #' - `label`: The label for each record.
1535 #' - `data`: A sparse Matrix of 'dgCMatrix' class with 126 columns.
1536 #'
1537 #' @references
1538 #' <https://archive.ics.uci.edu/ml/datasets/Mushroom>
1539 #'
1540 #' Bache, K. & Lichman, M. (2013). UCI Machine Learning Repository
1541 #' <http://archive.ics.uci.edu/ml>. Irvine, CA: University of California,
1542 #' School of Information and Computer Science.
1543 #'
1544 #' @docType data
1545 #' @keywords datasets
1546 #' @name agaricus.train
1547 #' @usage data(agaricus.train)
1548 #' @format A list containing a label vector, and a dgCMatrix object with 6513
1549 #' rows and 127 variables
1550 NULL
1551
1552 #' Test part from Mushroom Data Set
1553 #'
1554 #' This data set is originally from the Mushroom data set,
1555 #' UCI Machine Learning Repository.
1556 #'
1557 #' It includes the following fields:
1558 #' - `label`: The label for each record.
1559 #' - `data`: A sparse Matrix of 'dgCMatrix' class with 126 columns.
1560 #'
1561 #' @references
1562 #' <https://archive.ics.uci.edu/ml/datasets/Mushroom>
1563 #'
1564 #' Bache, K. & Lichman, M. (2013). UCI Machine Learning Repository
1565 #' <http://archive.ics.uci.edu/ml>. Irvine, CA: University of California,
1566 #' School of Information and Computer Science.
1567 #'
1568 #' @docType data
1569 #' @keywords datasets
1570 #' @name agaricus.test
1571 #' @usage data(agaricus.test)
1572 #' @format A list containing a label vector, and a dgCMatrix object with 1611
1573 #' rows and 126 variables
1574 NULL
1575
1576 # Various imports
1577 #' @importClassesFrom Matrix dgCMatrix dgRMatrix CsparseMatrix
1578 #' @importFrom Matrix sparse.model.matrix
1579 #' @importFrom data.table data.table
1580 #' @importFrom data.table is.data.table
1581 #' @importFrom data.table as.data.table
1582 #' @importFrom data.table :=
1583 #' @importFrom data.table rbindlist
1584 #' @importFrom data.table setkey
1585 #' @importFrom data.table setkeyv
1586 #' @importFrom data.table setnames
1587 #' @importFrom jsonlite fromJSON
1588 #' @importFrom jsonlite toJSON
1589 #' @importFrom methods new
1590 #' @importFrom utils object.size str tail
1591 #' @importFrom stats coef
1592 #' @importFrom stats predict
1593 #' @importFrom stats median
1594 #' @importFrom stats sd
1595 #' @importFrom stats variable.names
1596 #' @importFrom utils head
1597 #' @importFrom utils hasName
1598 #' @importFrom graphics barplot
1599 #' @importFrom graphics lines
1600 #' @importFrom graphics points
1601 #' @importFrom graphics grid
1602 #' @importFrom graphics par
1603 #' @importFrom graphics title
1604 #' @importFrom grDevices rgb
1605 #'
1606 #' @import methods
1607 #' @useDynLib xgboost, .registration = TRUE
1608 NULL