Debian Codegraph @

R/xgb.importance.R

raw
1 #' Feature importance
2 #'
3 #' Creates a `data.table` of feature importances.
4 #'
5 #' @details
6 #' This function works for both linear and tree models.
7 #'
8 #' For linear models, the importance is the absolute magnitude of linear coefficients.
9 #' To obtain a meaningful ranking by importance for linear models, the features need to
10 #' be on the same scale (which is also recommended when using L1 or L2 regularization).
11 #'
12 #' @param feature_names Character vector used to overwrite the feature names
13 #' of the model. The default is `NULL` (use original feature names).
14 #' @param model Object of class `xgb.Booster`.
15 #' @param trees An integer vector of (base-1) tree indices that should be included
16 #' into the importance calculation (only for the "gbtree" booster).
17 #' The default (`NULL`) parses all trees.
18 #' It could be useful, e.g., in multiclass classification to get feature importances
19 #' for each class separately.
20 #' @return A `data.table` with the following columns:
21 #'
22 #' For a tree model:
23 #' - `Features`: Names of the features used in the model.
24 #' - `Gain`: Fractional contribution of each feature to the model based on
25 #' the total gain of this feature's splits. Higher percentage means higher importance.
26 #' - `Cover`: Metric of the number of observation related to this feature.
27 #' - `Frequency`: Percentage of times a feature has been used in trees.
28 #'
29 #' For a linear model:
30 #' - `Features`: Names of the features used in the model.
31 #' - `Weight`: Linear coefficient of this feature.
32 #' - `Class`: Class label (only for multiclass models). For objects of class `xgboost` (as
33 #' produced by [xgboost()]), it will be a `factor`, while for objects of class `xgb.Booster`
34 #' (as produced by [xgb.train()]), it will be a zero-based integer vector.
35 #'
36 #' If `feature_names` is not provided and `model` doesn't have `feature_names`,
37 #' the index of the features will be used instead. Because the index is extracted from the model dump
38 #' (based on C++ code), it starts at 0 (as in C/C++ or Python) instead of 1 (usual in R).
39 #'
40 #' @examples
41 #' # binary classification using "gbtree":
42 #' data("ToothGrowth")
43 #' x <- ToothGrowth[, c("len", "dose")]
44 #' y <- ToothGrowth$supp
45 #' model_tree_binary <- xgboost(
46 #' x, y,
47 #' nrounds = 5L,
48 #' nthreads = 1L,
49 #' booster = "gbtree",
50 #' max_depth = 2L
51 #' )
52 #' xgb.importance(model_tree_binary)
53 #'
54 #' # binary classification using "gblinear":
55 #' model_tree_linear <- xgboost(
56 #' x, y,
57 #' nrounds = 5L,
58 #' nthreads = 1L,
59 #' booster = "gblinear",
60 #' learning_rate = 0.3
61 #' )
62 #' xgb.importance(model_tree_linear)
63 #'
64 #' # multi-class classification using "gbtree":
65 #' data("iris")
66 #' x <- iris[, c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")]
67 #' y <- iris$Species
68 #' model_tree_multi <- xgboost(
69 #' x, y,
70 #' nrounds = 5L,
71 #' nthreads = 1L,
72 #' booster = "gbtree",
73 #' max_depth = 3
74 #' )
75 #' # all classes clumped together:
76 #' xgb.importance(model_tree_multi)
77 #' # inspect importances separately for each class:
78 #' num_classes <- 3L
79 #' nrounds <- 5L
80 #' xgb.importance(
81 #' model_tree_multi, trees = seq(from = 1, by = num_classes, length.out = nrounds)
82 #' )
83 #' xgb.importance(
84 #' model_tree_multi, trees = seq(from = 2, by = num_classes, length.out = nrounds)
85 #' )
86 #' xgb.importance(
87 #' model_tree_multi, trees = seq(from = 3, by = num_classes, length.out = nrounds)
88 #' )
89 #'
90 #' # multi-class classification using "gblinear":
91 #' model_linear_multi <- xgboost(
92 #' x, y,
93 #' nrounds = 5L,
94 #' nthreads = 1L,
95 #' booster = "gblinear",
96 #' learning_rate = 0.2
97 #' )
98 #' xgb.importance(model_linear_multi)
99 #' @export
100 xgb.importance <- function(model = NULL, feature_names = getinfo(model, "feature_name"), trees = NULL) {
101
102 if (!(is.null(feature_names) || is.character(feature_names)))
103 stop("feature_names: Has to be a character vector")
104
105 if (!is.null(trees)) {
106 if (!is.vector(trees)) {
107 stop("'trees' must be a vector of tree indices.")
108 }
109 trees <- trees - 1L
110 if (anyNA(trees)) {
111 stop("Passed invalid tree indices.")
112 }
113 }
114
115 handle <- xgb.get.handle(model)
116 if (xgb.booster_type(model) == "gblinear") {
117 args <- list(importance_type = "weight", feature_names = feature_names)
118 results <- .Call(
119 XGBoosterFeatureScore_R, handle, jsonlite::toJSON(args, auto_unbox = TRUE, null = "null")
120 )
121 names(results) <- c("features", "shape", "weight")
122 if (length(results$shape) == 2) {
123 n_classes <- results$shape[2]
124 } else {
125 n_classes <- 0
126 }
127 importance <- if (n_classes == 0) {
128 return(data.table(Feature = results$features, Weight = results$weight)[order(-abs(Weight))])
129 } else {
130 out <- data.table(
131 Feature = rep(results$features, each = n_classes), Weight = results$weight, Class = seq_len(n_classes) - 1
132 )[order(Class, -abs(Weight))]
133 if (inherits(model, "xgboost") && NROW(attributes(model)$metadata$y_levels)) {
134 class_vec <- out$Class
135 class_vec <- as.integer(class_vec) + 1L
136 attributes(class_vec)$levels <- attributes(model)$metadata$y_levels
137 attributes(class_vec)$class <- "factor"
138 out[, Class := class_vec]
139 }
140 return(out[])
141 }
142 } else {
143 concatenated <- list()
144 output_names <- vector()
145 for (importance_type in c("weight", "total_gain", "total_cover")) {
146 args <- list(importance_type = importance_type, feature_names = feature_names, tree_idx = trees)
147 results <- .Call(
148 XGBoosterFeatureScore_R, handle, jsonlite::toJSON(args, auto_unbox = TRUE, null = "null")
149 )
150 names(results) <- c("features", "shape", importance_type)
151 concatenated[
152 switch(importance_type, "weight" = "Frequency", "total_gain" = "Gain", "total_cover" = "Cover")
153 ] <- results[importance_type]
154 output_names <- results$features
155 }
156 importance <- data.table(
157 Feature = output_names,
158 Gain = concatenated$Gain / sum(concatenated$Gain),
159 Cover = concatenated$Cover / sum(concatenated$Cover),
160 Frequency = concatenated$Frequency / sum(concatenated$Frequency)
161 )[order(Gain, decreasing = TRUE)]
162 }
163 importance
164 }
165
166 # Avoid error messages during CRAN check.
167 # The reason is that these variables are never declared
168 # They are mainly column names inferred by Data.table...
169 globalVariables(c(".", ".N", "Gain", "Cover", "Frequency", "Feature", "Class"))