Debian Codegraph @

R/xgb.model.dt.tree.R

raw
1 #' Parse model text dump
2 #'
3 #' Parse a boosted tree model text dump into a `data.table` structure.
4 #'
5 #' Note that this function does not work with models that were fitted to
6 #' categorical data, and is only applicable to tree-based boosters (not `gblinear`).
7 #' @param model Object of class `xgb.Booster`. If it contains feature names (they can
8 #' be set through [setinfo()]), they will be used in the output from this function.
9 #'
10 #' If the model contains categorical features, an error will be thrown.
11 #' @param trees An integer vector of (base-1) tree indices that should be used. The default
12 #' (`NULL`) uses all trees. Useful, e.g., in multiclass classification to get only
13 #' the trees of one class.
14 #' @param use_int_id A logical flag indicating whether nodes in columns "Yes", "No", and
15 #' "Missing" should be represented as integers (when `TRUE`) or as "Tree-Node"
16 #' character strings (when `FALSE`, default).
17 #' @inheritParams xgb.train
18 #' @return
19 #' A `data.table` with detailed information about tree nodes. It has the following columns:
20 #' - `Tree`: integer ID of a tree in a model (zero-based index).
21 #' - `Node`: integer ID of a node in a tree (zero-based index).
22 #' - `ID`: character identifier of a node in a model (only when `use_int_id = FALSE`).
23 #' - `Feature`: for a branch node, a feature ID or name (when available);
24 #' for a leaf node, it simply labels it as `"Leaf"`.
25 #' - `Split`: location of the split for a branch node (split condition is always "less than").
26 #' - `Yes`: ID of the next node when the split condition is met.
27 #' - `No`: ID of the next node when the split condition is not met.
28 #' - `Missing`: ID of the next node when the branch value is missing.
29 #' - `Gain`: either the split gain (change in loss) or the leaf value.
30 #' - `Cover`: metric related to the number of observations either seen by a split
31 #' or collected by a leaf during training.
32 #'
33 #' When `use_int_id = FALSE`, columns "Yes", "No", and "Missing" point to model-wide node identifiers
34 #' in the "ID" column. When `use_int_id = TRUE`, those columns point to node identifiers from
35 #' the corresponding trees in the "Node" column.
36 #'
37 #' @examples
38 #' # Basic use:
39 #'
40 #' data(agaricus.train, package = "xgboost")
41 #' ## Keep the number of threads to 1 for examples
42 #' nthread <- 1
43 #' data.table::setDTthreads(nthread)
44 #'
45 #' bst <- xgb.train(
46 #' data = xgb.DMatrix(agaricus.train$data, label = agaricus.train$label, nthread = 1),
47 #' nrounds = 2,
48 #' params = xgb.params(
49 #' max_depth = 2,
50 #' nthread = nthread,
51 #' objective = "binary:logistic"
52 #' )
53 #' )
54 #'
55 #' # This bst model already has feature_names stored with it, so those would be used when
56 #' # feature_names is not set:
57 #' dt <- xgb.model.dt.tree(bst)
58 #'
59 #' # How to match feature names of splits that are following a current 'Yes' branch:
60 #' merge(
61 #' dt,
62 #' dt[, .(ID, Y.Feature = Feature)], by.x = "Yes", by.y = "ID", all.x = TRUE
63 #' )[
64 #' order(Tree, Node)
65 #' ]
66 #'
67 #' @export
68 xgb.model.dt.tree <- function(model, trees = NULL, use_int_id = FALSE, ...) {
69 check.deprecation(deprecated_dttree_params, match.call(), ...)
70
71 if (!inherits(model, "xgb.Booster")) {
72 stop("Either 'model' must be an object of class xgb.Booster")
73 }
74
75 if (xgb.has_categ_features(model)) {
76 stop("Cannot produce tables for models having categorical features.")
77 }
78
79 if (!is.null(trees)) {
80 if (!is.vector(trees) || (!is.numeric(trees) && !is.integer(trees))) {
81 stop("trees: must be a vector of integers.")
82 }
83 trees <- trees - 1L
84 if (anyNA(trees) || min(trees) < 0) {
85 stop("Passed invalid tree indices.")
86 }
87 }
88
89 feature_names <- NULL
90 if (inherits(model, "xgb.Booster")) {
91 feature_names <- xgb.feature_names(model)
92 }
93
94 text <- xgb.dump(model = model, with_stats = TRUE)
95
96 if (length(text) < 2 || !any(grepl('leaf=(-?\\d+)', text))) {
97 stop("Non-tree model detected! This function can only be used with tree models.")
98 }
99
100 position <- which(grepl("booster", text, fixed = TRUE))
101
102 add.tree.id <- function(node, tree) if (use_int_id) node else paste(tree, node, sep = "-")
103
104 anynumber_regex <- "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"
105
106 td <- data.table(t = text)
107 td[position, Tree := 1L]
108 td[, Tree := cumsum(ifelse(is.na(Tree), 0L, Tree)) - 1L]
109
110 if (is.null(trees)) {
111 trees <- 0:max(td$Tree)
112 } else {
113 trees <- trees[trees >= 0 & trees <= max(td$Tree)]
114 }
115 td <- td[Tree %in% trees & !is.na(t) & !startsWith(t, 'booster')]
116
117 td[, Node := as.integer(sub("^([0-9]+):.*", "\\1", t))]
118 if (!use_int_id) td[, ID := add.tree.id(Node, Tree)]
119 td[, isLeaf := grepl("leaf", t, fixed = TRUE)]
120
121 # parse branch lines
122 branch_rx_nonames <- paste0("f(\\d+)<(", anynumber_regex, ")\\] yes=(\\d+),no=(\\d+),missing=(\\d+),",
123 "gain=(", anynumber_regex, "),cover=(", anynumber_regex, ")")
124 branch_rx_w_names <- paste0("\\d+:\\[(.+)<(", anynumber_regex, ")\\] yes=(\\d+),no=(\\d+),missing=(\\d+),",
125 "gain=(", anynumber_regex, "),cover=(", anynumber_regex, ")")
126 text_has_feature_names <- FALSE
127 if (NROW(feature_names)) {
128 branch_rx <- branch_rx_w_names
129 text_has_feature_names <- TRUE
130 } else {
131 branch_rx <- branch_rx_nonames
132 }
133 branch_cols <- c("Feature", "Split", "Yes", "No", "Missing", "Gain", "Cover")
134 td[
135 isLeaf == FALSE,
136 (branch_cols) := {
137 matches <- regmatches(t, regexec(branch_rx, t))
138 # skip some indices with spurious capture groups from anynumber_regex
139 xtr <- do.call(rbind, matches)[, c(2, 3, 5, 6, 7, 8, 10), drop = FALSE]
140 xtr[, 3:5] <- add.tree.id(xtr[, 3:5], Tree)
141 if (length(xtr) == 0) {
142 as.data.table(
143 list(Feature = "NA", Split = "NA", Yes = "NA", No = "NA", Missing = "NA", Gain = "NA", Cover = "NA")
144 )
145 } else {
146 as.data.table(xtr)
147 }
148 }
149 ]
150
151 # assign feature_names when available
152 is_stump <- function() {
153 return(length(td$Feature) == 1 && is.na(td$Feature))
154 }
155 if (!text_has_feature_names) {
156 if (!is.null(feature_names) && !is_stump()) {
157 if (length(feature_names) <= max(as.numeric(td$Feature), na.rm = TRUE))
158 stop("feature_names has less elements than there are features used in the model")
159 td[isLeaf == FALSE, Feature := feature_names[as.numeric(Feature) + 1]]
160 }
161 }
162
163 # parse leaf lines
164 leaf_rx <- paste0("leaf=(", anynumber_regex, "),cover=(", anynumber_regex, ")")
165 leaf_cols <- c("Feature", "Gain", "Cover")
166 td[
167 isLeaf == TRUE,
168 (leaf_cols) := {
169 matches <- regmatches(t, regexec(leaf_rx, t))
170 xtr <- do.call(rbind, matches)[, c(2, 4)]
171 if (length(xtr) == 2) {
172 c("Leaf", as.data.table(xtr[1]), as.data.table(xtr[2]))
173 } else {
174 c("Leaf", as.data.table(xtr))
175 }
176 }
177 ]
178
179 # convert some columns to numeric
180 numeric_cols <- c("Split", "Gain", "Cover")
181 td[, (numeric_cols) := lapply(.SD, as.numeric), .SDcols = numeric_cols]
182 if (use_int_id) {
183 int_cols <- c("Yes", "No", "Missing")
184 td[, (int_cols) := lapply(.SD, as.integer), .SDcols = int_cols]
185 }
186
187 td[, t := NULL]
188 td[, isLeaf := NULL]
189
190 td[order(Tree, Node)]
191 }
192
193 # Avoid notes during CRAN check.
194 # The reason is that these variables are never declared
195 # They are mainly column names inferred by Data.table...
196 globalVariables(c("Tree", "Node", "ID", "Feature", "t", "isLeaf", ".SD", ".SDcols"))