Debian Codegraph @

R/xgb.dump.R

raw
1 #' Dump an XGBoost model in text format.
2 #'
3 #' Dump an XGBoost model in text format.
4 #'
5 #' @param model The model object.
6 #' @param fname The name of the text file where to save the model text dump.
7 #' If not provided or set to `NULL`, the model is returned as a character vector.
8 #' @param fmap Feature map file representing feature types. See demo/ for a walkthrough
9 #' example in R, and \url{https://github.com/dmlc/xgboost/blob/master/demo/data/featmap.txt}
10 #' to see an example of the value.
11 #' @param with_stats Whether to dump some additional statistics about the splits.
12 #' When this option is on, the model dump contains two additional values:
13 #' gain is the approximate loss function gain we get in each split;
14 #' cover is the sum of second order gradient in each node.
15 #' @param dump_format Either 'text', 'json', or 'dot' (graphviz) format could be specified.
16 #'
17 #' Format 'dot' for a single tree can be passed directly to packages that consume this format
18 #' for graph visualization, such as function `DiagrammeR::grViz()`
19 #' @inheritParams xgb.train
20 #' @return
21 #' If fname is not provided or set to `NULL` the function will return the model
22 #' as a character vector. Otherwise it will return `TRUE`.
23 #'
24 #' @examples
25 #' \dontshow{RhpcBLASctl::omp_set_num_threads(1)}
26 #' data(agaricus.train, package = "xgboost")
27 #' data(agaricus.test, package = "xgboost")
28 #'
29 #' train <- agaricus.train
30 #' test <- agaricus.test
31 #'
32 #' bst <- xgb.train(
33 #' data = xgb.DMatrix(train$data, label = train$label, nthread = 1),
34 #' nrounds = 2,
35 #' params = xgb.params(
36 #' max_depth = 2,
37 #' nthread = 2,
38 #' objective = "binary:logistic"
39 #' )
40 #' )
41 #'
42 #' # save the model in file 'xgb.model.dump'
43 #' dump_path = file.path(tempdir(), 'model.dump')
44 #' xgb.dump(bst, dump_path, with_stats = TRUE)
45 #'
46 #' # print the model without saving it to a file
47 #' print(xgb.dump(bst, with_stats = TRUE))
48 #'
49 #' # print in JSON format:
50 #' cat(xgb.dump(bst, with_stats = TRUE, dump_format = "json"))
51 #'
52 #' # plot first tree leveraging the 'dot' format
53 #' if (requireNamespace('DiagrammeR', quietly = TRUE)) {
54 #' DiagrammeR::grViz(xgb.dump(bst, dump_format = "dot")[[1L]])
55 #' }
56 #' @export
57 xgb.dump <- function(model, fname = NULL, fmap = "", with_stats = FALSE,
58 dump_format = c("text", "json", "dot"), ...) {
59 check.deprecation(deprecated_dump_params, match.call(), ...)
60 dump_format <- match.arg(dump_format)
61 if (!inherits(model, "xgb.Booster"))
62 stop("model: argument must be of type xgb.Booster")
63 if (!(is.null(fname) || is.character(fname)))
64 stop("fname: argument must be a character string (when provided)")
65 if (!(is.null(fmap) || is.character(fmap)))
66 stop("fmap: argument must be a character string (when provided)")
67
68 model_dump <- .Call(
69 XGBoosterDumpModel_R,
70 xgb.get.handle(model),
71 NVL(fmap, "")[1],
72 as.integer(with_stats),
73 as.character(dump_format)
74 )
75 if (dump_format == "dot") {
76 return(sapply(model_dump, function(x) gsub("^booster\\[\\d+\\]\\n", "\\1", x)))
77 }
78
79 if (is.null(fname))
80 model_dump <- gsub('\t', '', model_dump, fixed = TRUE)
81
82 if (dump_format == "text")
83 model_dump <- unlist(strsplit(model_dump, '\n', fixed = TRUE))
84
85 model_dump <- grep('^\\s*$', model_dump, invert = TRUE, value = TRUE)
86
87 if (is.null(fname)) {
88 return(model_dump)
89 } else {
90 fname <- path.expand(fname)
91 writeLines(model_dump, fname[1])
92 return(TRUE)
93 }
94 }