Debian Codegraph @

R/xgb.plot.importance.R

raw
1 #' Plot feature importance
2 #'
3 #' Represents previously calculated feature importance as a bar graph.
4 #' - `xgb.plot.importance()` uses base R graphics, while
5 #' - `xgb.ggplot.importance()` uses "ggplot".
6 #'
7 #' @details
8 #' The graph represents each feature as a horizontal bar of length proportional to the
9 #' importance of a feature. Features are sorted by decreasing importance.
10 #' It works for both "gblinear" and "gbtree" models.
11 #'
12 #' When `rel_to_first = FALSE`, the values would be plotted as in `importance_matrix`.
13 #' For a "gbtree" model, that would mean being normalized to the total of 1
14 #' ("what is feature's importance contribution relative to the whole model?").
15 #' For linear models, `rel_to_first = FALSE` would show actual values of the coefficients.
16 #' Setting `rel_to_first = TRUE` allows to see the picture from the perspective of
17 #' "what is feature's importance contribution relative to the most important feature?"
18 #'
19 #' The "ggplot" backend performs 1-D clustering of the importance values,
20 #' with bar colors corresponding to different clusters having similar importance values.
21 #'
22 #' @param importance_matrix A `data.table` as returned by [xgb.importance()].
23 #' @param top_n Maximal number of top features to include into the plot.
24 #' @param measure The name of importance measure to plot.
25 #' When `NULL`, 'Gain' would be used for trees and 'Weight' would be used for gblinear.
26 #' @param rel_to_first Whether importance values should be represented as relative to
27 #' the highest ranked feature, see Details.
28 #' @param left_margin Adjust the left margin size to fit feature names.
29 #' When `NULL`, the existing `par("mar")` is used.
30 #' @param cex Passed as `cex.names` parameter to [graphics::barplot()].
31 #' @param plot Should the barplot be shown? Default is `TRUE`.
32 #' @param n_clusters A numeric vector containing the min and the max range
33 #' of the possible number of clusters of bars.
34 #' @param ... Other parameters passed to [graphics::barplot()]
35 #' (except `horiz`, `border`, `cex.names`, `names.arg`, and `las`).
36 #' Only used in `xgb.plot.importance()`.
37 #' @return
38 #' The return value depends on the function:
39 #' - `xgb.plot.importance()`: Invisibly, a "data.table" with `n_top` features sorted
40 #' by importance. If `plot = TRUE`, the values are also plotted as barplot.
41 #' - `xgb.ggplot.importance()`: A customizable "ggplot" object.
42 #' E.g., to change the title, set `+ ggtitle("A GRAPH NAME")`.
43 #'
44 #' @seealso [graphics::barplot()]
45 #'
46 #' @examples
47 #' data(agaricus.train)
48 #'
49 #' ## Keep the number of threads to 2 for examples
50 #' nthread <- 2
51 #' data.table::setDTthreads(nthread)
52 #'
53 #' model <- xgboost(
54 #' agaricus.train$data, factor(agaricus.train$label),
55 #' nrounds = 2,
56 #' max_depth = 3,
57 #' nthreads = nthread
58 #' )
59 #'
60 #' importance_matrix <- xgb.importance(model)
61 #' xgb.plot.importance(
62 #' importance_matrix, rel_to_first = TRUE, xlab = "Relative importance"
63 #' )
64 #'
65 #' gg <- xgb.ggplot.importance(
66 #' importance_matrix, measure = "Frequency", rel_to_first = TRUE
67 #' )
68 #' gg
69 #' gg + ggplot2::ylab("Frequency")
70 #'
71 #' @rdname xgb.plot.importance
72 #' @export
73 xgb.plot.importance <- function(importance_matrix = NULL, top_n = NULL, measure = NULL,
74 rel_to_first = FALSE, left_margin = 10, cex = NULL, plot = TRUE, ...) {
75 check.deprecation(deprecated_plotimp_params, match.call(), ..., allow_unrecognized = TRUE)
76 if (!is.data.table(importance_matrix)) {
77 stop("importance_matrix: must be a data.table")
78 }
79
80 imp_names <- colnames(importance_matrix)
81 if (is.null(measure)) {
82 if (all(c("Feature", "Gain") %in% imp_names)) {
83 measure <- "Gain"
84 } else if (all(c("Feature", "Weight") %in% imp_names)) {
85 measure <- "Weight"
86 } else {
87 stop("Importance matrix column names are not as expected!")
88 }
89 } else {
90 if (!measure %in% imp_names)
91 stop("Invalid `measure`")
92 if (!"Feature" %in% imp_names)
93 stop("Importance matrix column names are not as expected!")
94 }
95
96 # also aggregate, just in case when the values were not yet summed up by feature
97 importance_matrix <- importance_matrix[
98 , lapply(.SD, sum)
99 , .SDcols = setdiff(names(importance_matrix), "Feature")
100 , by = Feature
101 ][
102 , Importance := get(measure)
103 ]
104
105 # make sure it's ordered
106 importance_matrix <- importance_matrix[order(-abs(Importance))]
107
108 if (!is.null(top_n)) {
109 top_n <- min(top_n, nrow(importance_matrix))
110 importance_matrix <- head(importance_matrix, top_n)
111 }
112 if (rel_to_first) {
113 importance_matrix[, Importance := Importance / max(abs(Importance))]
114 }
115 if (is.null(cex)) {
116 cex <- 2.5 / log2(1 + nrow(importance_matrix))
117 }
118
119 if (plot) {
120 original_mar <- par()$mar
121
122 # reset margins so this function doesn't have side effects
123 on.exit({
124 par(mar = original_mar)
125 })
126
127 mar <- original_mar
128 if (!is.null(left_margin))
129 mar[2] <- left_margin
130 par(mar = mar)
131
132 # reverse the order of rows to have the highest ranked at the top
133 importance_matrix[rev(seq_len(nrow(importance_matrix))),
134 barplot(Importance, horiz = TRUE, border = NA, cex.names = cex,
135 names.arg = Feature, las = 1, ...)]
136 }
137
138 invisible(importance_matrix)
139 }
140
141 # Avoid error messages during CRAN check.
142 # The reason is that these variables are never declared
143 # They are mainly column names inferred by Data.table...
144 globalVariables(c("Feature", "Importance"))