Debian Codegraph @

R/xgb.plot.multi.trees.R

raw
1 #' Project all trees on one tree
2 #'
3 #' Visualization of the ensemble of trees as a single collective unit.
4 #'
5 #' Note that this function does not work with models that were fitted to
6 #' categorical data.
7 #' @details
8 #' This function tries to capture the complexity of a gradient boosted tree model
9 #' in a cohesive way by compressing an ensemble of trees into a single tree-graph representation.
10 #' The goal is to improve the interpretability of a model generally seen as black box.
11 #'
12 #' Note: this function is applicable to tree booster-based models only.
13 #'
14 #' It takes advantage of the fact that the shape of a binary tree is only defined by
15 #' its depth (therefore, in a boosting model, all trees have similar shape).
16 #'
17 #' Moreover, the trees tend to reuse the same features.
18 #'
19 #' The function projects each tree onto one, and keeps for each position the
20 #' `features_keep` first features (based on the Gain per feature measure).
21 #'
22 #' This function is inspired by this blog post:
23 #' <https://wellecks.wordpress.com/2015/02/21/peering-into-the-black-box-visualizing-lambdamart/>
24 #'
25 #' @inheritParams xgb.plot.tree
26 #' @param features_keep Number of features to keep in each position of the multi trees,
27 #' by default 5.
28 #' @param render Should the graph be rendered or not? The default is `TRUE`.
29 #' @inherit xgb.plot.tree return
30 #'
31 #' @examples
32 #'
33 #' data(agaricus.train, package = "xgboost")
34 #'
35 #' ## Keep the number of threads to 2 for examples
36 #' nthread <- 2
37 #' data.table::setDTthreads(nthread)
38 #'
39 #' model <- xgboost(
40 #' agaricus.train$data, factor(agaricus.train$label),
41 #' nrounds = 30,
42 #' verbosity = 0L,
43 #' nthreads = nthread,
44 #' max_depth = 15,
45 #' learning_rate = 1,
46 #' min_child_weight = 50
47 #' )
48 #'
49 #' p <- xgb.plot.multi.trees(model, features_keep = 3)
50 #' print(p)
51 #'
52 #' # Below is an example of how to save this plot to a file.
53 #' if (require("DiagrammeR") && require("DiagrammeRsvg") && require("rsvg")) {
54 #' fname <- file.path(tempdir(), "tree.pdf")
55 #' gr <- xgb.plot.multi.trees(model, features_keep = 3, render = FALSE)
56 #' export_graph(gr, fname, width = 1500, height = 600)
57 #' }
58 #' @export
59 xgb.plot.multi.trees <- function(model, features_keep = 5, plot_width = NULL, plot_height = NULL,
60 render = TRUE, ...) {
61 check.deprecation(deprecated_multitrees_params, match.call(), ...)
62 if (!requireNamespace("DiagrammeR", quietly = TRUE)) {
63 stop("DiagrammeR is required for xgb.plot.multi.trees")
64 }
65 if (xgb.has_categ_features(model)) {
66 stop(
67 "Cannot use 'xgb.plot.multi.trees' for models with categorical features.",
68 " Try 'xgb.plot.tree' instead."
69 )
70 }
71 tree.matrix <- xgb.model.dt.tree(model = model)
72
73 # first number of the path represents the tree, then the following numbers are related to the path to follow
74 # root init
75 root.nodes <- tree.matrix[Node == 0, ID]
76 tree.matrix[ID %in% root.nodes, abs.node.position := root.nodes]
77
78 precedent.nodes <- root.nodes
79
80 while (tree.matrix[, sum(is.na(abs.node.position))] > 0) {
81 yes.row.nodes <- tree.matrix[abs.node.position %in% precedent.nodes & !is.na(Yes)]
82 no.row.nodes <- tree.matrix[abs.node.position %in% precedent.nodes & !is.na(No)]
83 yes.nodes.abs.pos <- paste0(yes.row.nodes[, abs.node.position], "_0")
84 no.nodes.abs.pos <- paste0(no.row.nodes[, abs.node.position], "_1")
85
86 tree.matrix[ID %in% yes.row.nodes[, Yes], abs.node.position := yes.nodes.abs.pos]
87 tree.matrix[ID %in% no.row.nodes[, No], abs.node.position := no.nodes.abs.pos]
88 precedent.nodes <- c(yes.nodes.abs.pos, no.nodes.abs.pos)
89 }
90
91 tree.matrix[!is.na(Yes), Yes := paste0(abs.node.position, "_0")]
92 tree.matrix[!is.na(No), No := paste0(abs.node.position, "_1")]
93
94 for (nm in c("abs.node.position", "Yes", "No"))
95 data.table::set(tree.matrix, j = nm, value = sub("^\\d+-", "", tree.matrix[[nm]]))
96
97 nodes.dt <- tree.matrix[
98 , .(Gain = sum(Gain))
99 , by = .(abs.node.position, Feature)
100 ][, .(Text = paste0(
101 paste0(
102 Feature[seq_len(min(length(Feature), features_keep))],
103 " (",
104 format(Gain[seq_len(min(length(Gain), features_keep))], digits = 5),
105 ")"
106 ),
107 collapse = "\n"
108 )
109 )
110 , by = abs.node.position
111 ]
112
113 edges.dt <- data.table::rbindlist(
114 l = list(
115 tree.matrix[Feature != "Leaf", .(From = abs.node.position, To = Yes)],
116 tree.matrix[Feature != "Leaf", .(From = abs.node.position, To = No)]
117 )
118 )
119 edges.dt <- edges.dt[, .N, .(From, To)]
120 edges.dt[, N := NULL]
121
122 nodes <- DiagrammeR::create_node_df(
123 n = nrow(nodes.dt),
124 label = nodes.dt[, Text]
125 )
126
127 edges <- DiagrammeR::create_edge_df(
128 from = match(edges.dt[, From], nodes.dt[, abs.node.position]),
129 to = match(edges.dt[, To], nodes.dt[, abs.node.position]),
130 rel = "leading_to")
131
132 graph <- DiagrammeR::create_graph(
133 nodes_df = nodes,
134 edges_df = edges,
135 attr_theme = NULL
136 )
137 graph <- DiagrammeR::add_global_graph_attrs(
138 graph = graph,
139 attr_type = "graph",
140 attr = c("layout", "rankdir"),
141 value = c("dot", "LR")
142 )
143 graph <- DiagrammeR::add_global_graph_attrs(
144 graph = graph,
145 attr_type = "node",
146 attr = c("color", "fillcolor", "style", "shape", "fontname"),
147 value = c("DimGray", "beige", "filled", "rectangle", "Helvetica")
148 )
149 graph <- DiagrammeR::add_global_graph_attrs(
150 graph = graph,
151 attr_type = "edge",
152 attr = c("color", "arrowsize", "arrowhead", "fontname"),
153 value = c("DimGray", "1.5", "vee", "Helvetica")
154 )
155
156 if (!render) return(invisible(graph))
157
158 DiagrammeR::render_graph(graph, width = plot_width, height = plot_height)
159 }
160
161 globalVariables(c(".N", "N", "From", "To", "Text", "Feature", "no.nodes.abs.pos",
162 "ID", "Yes", "No", "Tree", "yes.nodes.abs.pos", "abs.node.position"))