Debian Codegraph @

R/xgb.plot.deepness.R

raw
1 #' Plot model tree depth
2 #'
3 #' Visualizes distributions related to the depth of tree leaves.
4 #' - `xgb.plot.deepness()` uses base R graphics, while
5 #' - `xgb.ggplot.deepness()` uses "ggplot2".
6 #'
7 #' @param model Either an `xgb.Booster` model, or the "data.table" returned
8 #' by [xgb.model.dt.tree()].
9 #' @param which Which distribution to plot (see details).
10 #' @param plot Should the plot be shown? Default is `TRUE`.
11 #' @param ... Other parameters passed to [graphics::barplot()] or [graphics::plot()].
12 #'
13 #' @details
14 #'
15 #' When `which = "2x1"`, two distributions with respect to the leaf depth
16 #' are plotted on top of each other:
17 #' 1. The distribution of the number of leaves in a tree model at a certain depth.
18 #' 2. The distribution of the average weighted number of observations ("cover")
19 #' ending up in leaves at a certain depth.
20 #'
21 #' Those could be helpful in determining sensible ranges of the `max_depth`
22 #' and `min_child_weight` parameters.
23 #'
24 #' When `which = "max.depth"` or `which = "med.depth"`, plots of either maximum or
25 #' median depth per tree with respect to the tree number are created.
26 #'
27 #' Finally, `which = "med.weight"` allows to see how
28 #' a tree's median absolute leaf weight changes through the iterations.
29 #'
30 #' These functions have been inspired by the blog post
31 #' <https://github.com/aysent/random-forest-leaf-visualization>.
32 #'
33 #' @return
34 #' The return value of the two functions is as follows:
35 #' - `xgb.plot.deepness()`: A "data.table" (invisibly).
36 #' Each row corresponds to a terminal leaf in the model. It contains its information
37 #' about depth, cover, and weight (used in calculating predictions).
38 #' If `plot = TRUE`, also a plot is shown.
39 #' - `xgb.ggplot.deepness()`: When `which = "2x1"`, a list of two "ggplot" objects,
40 #' and a single "ggplot" object otherwise.
41 #'
42 #' @seealso [xgb.train()] and [xgb.model.dt.tree()].
43 #'
44 #' @examples
45 #'
46 #' data(agaricus.train, package = "xgboost")
47 #' ## Keep the number of threads to 2 for examples
48 #' nthread <- 2
49 #' data.table::setDTthreads(nthread)
50 #'
51 #' ## Change max_depth to a higher number to get a more significant result
52 #' model <- xgboost(
53 #' agaricus.train$data, factor(agaricus.train$label),
54 #' nrounds = 50,
55 #' max_depth = 6,
56 #' nthreads = nthread,
57 #' subsample = 0.5,
58 #' min_child_weight = 2
59 #' )
60 #'
61 #' xgb.plot.deepness(model)
62 #' xgb.ggplot.deepness(model)
63 #'
64 #' xgb.plot.deepness(
65 #' model, which = "max.depth", pch = 16, col = rgb(0, 0, 1, 0.3), cex = 2
66 #' )
67 #'
68 #' xgb.plot.deepness(
69 #' model, which = "med.weight", pch = 16, col = rgb(0, 0, 1, 0.3), cex = 2
70 #' )
71 #'
72 #' @rdname xgb.plot.deepness
73 #' @export
74 xgb.plot.deepness <- function(model = NULL, which = c("2x1", "max.depth", "med.depth", "med.weight"),
75 plot = TRUE, ...) {
76
77 if (!(inherits(model, "xgb.Booster") || is.data.table(model)))
78 stop("model: Has to be either an xgb.Booster model generaged by the xgb.train function\n",
79 "or a data.table result of the xgb.importance function")
80
81 if (!requireNamespace("igraph", quietly = TRUE))
82 stop("igraph package is required for plotting the graph deepness.", call. = FALSE)
83
84 which <- match.arg(which)
85
86 dt_tree <- model
87 if (inherits(model, "xgb.Booster"))
88 dt_tree <- xgb.model.dt.tree(model = model)
89
90 if (!all(c("Feature", "Tree", "ID", "Yes", "No", "Cover") %in% colnames(dt_tree)))
91 stop("Model tree columns are not as expected!\n",
92 " Note that this function works only for tree models.")
93
94 dt_depths <- merge(get.leaf.depth(dt_tree), dt_tree[, .(ID, Cover, Weight = Gain)], by = "ID")
95 setkeyv(dt_depths, c("Tree", "ID"))
96 # count by depth levels, and also calculate average cover at a depth
97 dt_summaries <- dt_depths[, .(.N, Cover = mean(Cover)), Depth]
98 setkey(dt_summaries, "Depth")
99
100 if (plot) {
101 if (which == "2x1") {
102 op <- par(no.readonly = TRUE)
103 par(mfrow = c(2, 1),
104 oma = c(3, 1, 3, 1) + 0.1,
105 mar = c(1, 4, 1, 0) + 0.1)
106
107 dt_summaries[, barplot(N, border = NA, ylab = 'Number of leafs', ...)]
108
109 dt_summaries[, barplot(Cover, border = NA, ylab = "Weighted cover", names.arg = Depth, ...)]
110
111 title("Model complexity", xlab = "Leaf depth", outer = TRUE, line = 1)
112 par(op)
113 } else if (which == "max.depth") {
114 dt_depths[, max(Depth), Tree][
115 , plot(jitter(V1, amount = 0.1) ~ Tree, ylab = 'Max tree leaf depth', xlab = "tree #", ...)]
116 } else if (which == "med.depth") {
117 dt_depths[, median(as.numeric(Depth)), Tree][
118 , plot(jitter(V1, amount = 0.1) ~ Tree, ylab = 'Median tree leaf depth', xlab = "tree #", ...)]
119 } else if (which == "med.weight") {
120 dt_depths[, median(abs(Weight)), Tree][
121 , plot(V1 ~ Tree, ylab = 'Median absolute leaf weight', xlab = "tree #", ...)]
122 }
123 }
124 invisible(dt_depths)
125 }
126
127 # Extract path depths from root to leaf
128 # from data.table containing the nodes and edges of the trees.
129 # internal utility function
130 get.leaf.depth <- function(dt_tree) {
131 # extract tree graph's edges
132 dt_edges <- rbindlist(list(
133 dt_tree[Feature != "Leaf", .(ID, To = Yes, Tree)],
134 dt_tree[Feature != "Leaf", .(ID, To = No, Tree)]
135 ))
136 # whether "To" is a leaf:
137 dt_edges <-
138 merge(dt_edges,
139 dt_tree[Feature == "Leaf", .(ID, Leaf = TRUE)],
140 all.x = TRUE, by.x = "To", by.y = "ID")
141 dt_edges[is.na(Leaf), Leaf := FALSE]
142
143 dt_edges[, {
144 graph <- igraph::graph_from_data_frame(.SD[, .(ID, To)])
145 # min(ID) in a tree is a root node
146 paths_tmp <- igraph::shortest_paths(graph, from = min(ID), to = To[Leaf == TRUE])
147 # list of paths to each leaf in a tree
148 paths <- lapply(paths_tmp$vpath, names)
149 # combine into a resulting path lengths table for a tree
150 data.table(Depth = lengths(paths), ID = To[Leaf == TRUE])
151 }, by = Tree]
152 }
153
154 # Avoid error messages during CRAN check.
155 # The reason is that these variables are never declared
156 # They are mainly column names inferred by Data.table...
157 globalVariables(
158 c(
159 ".N", "N", "Depth", "Gain", "Cover", "Tree", "ID", "Yes", "No", "Feature", "Leaf", "Weight"
160 )
161 )