Debian Codegraph @

R/xgb.plot.shap.R

raw
1 #' SHAP dependence plots
2 #'
3 #' Visualizes SHAP values against feature values to gain an impression of feature effects.
4 #'
5 #' @param data The data to explain as a `matrix`, `dgCMatrix`, or `data.frame`.
6 #' @param shap_contrib Matrix of SHAP contributions of `data`.
7 #' The default (`NULL`) computes it from `model` and `data`.
8 #' @param features Vector of column indices or feature names to plot. When `NULL`
9 #' (default), the `top_n` most important features are selected by [xgb.importance()].
10 #' @param top_n How many of the most important features (<= 100) should be selected?
11 #' By default 1 for SHAP dependence and 10 for SHAP summary.
12 #' Only used when `features = NULL`.
13 #' @param model An `xgb.Booster` model. Only required when `shap_contrib = NULL` or
14 #' `features = NULL`.
15 #' @param trees Passed to [xgb.importance()] when `features = NULL`.
16 #' @param target_class Only relevant for multiclass models. The default (`NULL`)
17 #' averages the SHAP values over all classes. Pass a (0-based) class index
18 #' to show only SHAP values of that class.
19 #' @param approxcontrib Passed to [predict.xgb.Booster()] when `shap_contrib = NULL`.
20 #' @param subsample Fraction of data points randomly picked for plotting.
21 #' The default (`NULL`) will use up to 100k data points.
22 #' @param n_col Number of columns in a grid of plots.
23 #' @param col Color of the scatterplot markers.
24 #' @param pch Scatterplot marker.
25 #' @param discrete_n_uniq Maximal number of unique feature values to consider the
26 #' feature as discrete.
27 #' @param discrete_jitter Jitter amount added to the values of discrete features.
28 #' @param ylab The y-axis label in 1D plots.
29 #' @param plot_NA Should contributions of cases with missing values be plotted?
30 #' Default is `TRUE`.
31 #' @param col_NA Color of marker for missing value contributions.
32 #' @param pch_NA Marker type for `NA` values.
33 #' @param pos_NA Relative position of the x-location where `NA` values are shown:
34 #' `min(x) + (max(x) - min(x)) * pos_NA`.
35 #' @param plot_loess Should loess-smoothed curves be plotted? (Default is `TRUE`).
36 #' The smoothing is only done for features with more than 5 distinct values.
37 #' @param col_loess Color of loess curves.
38 #' @param span_loess The `span` parameter of [stats::loess()].
39 #' @param which Whether to do univariate or bivariate plotting. Currently, only "1d" is implemented.
40 #' @param plot Should the plot be drawn? (Default is `TRUE`).
41 #' If `FALSE`, only a list of matrices is returned.
42 #' @param ... Other parameters passed to [graphics::plot()].
43 #'
44 #' @details
45 #'
46 #' These scatterplots represent how SHAP feature contributions depend of feature values.
47 #' The similarity to partial dependence plots is that they also give an idea for how feature values
48 #' affect predictions. However, in partial dependence plots, we see marginal dependencies
49 #' of model prediction on feature value, while SHAP dependence plots display the estimated
50 #' contributions of a feature to the prediction for each individual case.
51 #'
52 #' When `plot_loess = TRUE`, feature values are rounded to three significant digits and
53 #' weighted LOESS is computed and plotted, where the weights are the numbers of data points
54 #' at each rounded value.
55 #'
56 #' Note: SHAP contributions are on the scale of the model margin.
57 #' E.g., for a logistic binomial objective, the margin is on log-odds scale.
58 #' Also, since SHAP stands for "SHapley Additive exPlanation" (model prediction = sum of SHAP
59 #' contributions for all features + bias), depending on the objective used, transforming SHAP
60 #' contributions for a feature from the marginal to the prediction space is not necessarily
61 #' a meaningful thing to do.
62 #'
63 #' @return
64 #' In addition to producing plots (when `plot = TRUE`), it silently returns a list of two matrices:
65 #' - `data`: Feature value matrix.
66 #' - `shap_contrib`: Corresponding SHAP value matrix.
67 #'
68 #' @references
69 #' 1. Scott M. Lundberg, Su-In Lee, "A Unified Approach to Interpreting Model Predictions",
70 #' NIPS Proceedings 2017, <https://arxiv.org/abs/1705.07874>
71 #' 2. Scott M. Lundberg, Su-In Lee, "Consistent feature attribution for tree ensembles",
72 #' <https://arxiv.org/abs/1706.06060>
73 #'
74 #' @examples
75 #'
76 #' data(agaricus.train, package = "xgboost")
77 #' data(agaricus.test, package = "xgboost")
78 #'
79 #' ## Keep the number of threads to 1 for examples
80 #' nthread <- 1
81 #' data.table::setDTthreads(nthread)
82 #' nrounds <- 20
83 #'
84 #' model_binary <- xgboost(
85 #' agaricus.train$data, factor(agaricus.train$label),
86 #' nrounds = nrounds,
87 #' verbosity = 0L,
88 #' learning_rate = 0.1,
89 #' max_depth = 3L,
90 #' subsample = 0.5,
91 #' nthreads = nthread
92 #' )
93 #'
94 #' xgb.plot.shap(agaricus.test$data, model = model_binary, features = "odor=none")
95 #'
96 #' contr <- predict(model_binary, agaricus.test$data, type = "contrib")
97 #' xgb.plot.shap(agaricus.test$data, contr, model = model_binary, top_n = 12, n_col = 3)
98 #'
99 #' # Summary plot
100 #' xgb.ggplot.shap.summary(agaricus.test$data, contr, model = model_binary, top_n = 12)
101 #'
102 #' # Multiclass example - plots for each class separately:
103 #' x <- as.matrix(iris[, -5])
104 #' set.seed(123)
105 #' is.na(x[sample(nrow(x) * 4, 30)]) <- TRUE # introduce some missing values
106 #'
107 #' model_multiclass <- xgboost(
108 #' x, iris$Species,
109 #' nrounds = nrounds,
110 #' verbosity = 0,
111 #' max_depth = 2,
112 #' subsample = 0.5,
113 #' nthreads = nthread
114 #' )
115 #' nclass <- 3
116 #' trees0 <- seq(from = 1, by = nclass, length.out = nrounds)
117 #' col <- rgb(0, 0, 1, 0.5)
118 #'
119 #' xgb.plot.shap(
120 #' x,
121 #' model = model_multiclass,
122 #' trees = trees0,
123 #' target_class = 0,
124 #' top_n = 4,
125 #' n_col = 2,
126 #' col = col,
127 #' pch = 16,
128 #' pch_NA = 17
129 #' )
130 #'
131 #' xgb.plot.shap(
132 #' x,
133 #' model = model_multiclass,
134 #' trees = trees0 + 1,
135 #' target_class = 1,
136 #' top_n = 4,
137 #' n_col = 2,
138 #' col = col,
139 #' pch = 16,
140 #' pch_NA = 17
141 #' )
142 #'
143 #' xgb.plot.shap(
144 #' x,
145 #' model = model_multiclass,
146 #' trees = trees0 + 2,
147 #' target_class = 2,
148 #' top_n = 4,
149 #' n_col = 2,
150 #' col = col,
151 #' pch = 16,
152 #' pch_NA = 17
153 #' )
154 #'
155 #' # Summary plot
156 #' xgb.ggplot.shap.summary(x, model = model_multiclass, target_class = 0, top_n = 4)
157 #'
158 #' @rdname xgb.plot.shap
159 #' @export
160 xgb.plot.shap <- function(data, shap_contrib = NULL, features = NULL, top_n = 1, model = NULL,
161 trees = NULL, target_class = NULL, approxcontrib = FALSE,
162 subsample = NULL, n_col = 1, col = rgb(0, 0, 1, 0.2), pch = '.',
163 discrete_n_uniq = 5, discrete_jitter = 0.01, ylab = "SHAP",
164 plot_NA = TRUE, col_NA = rgb(0.7, 0, 1, 0.6), pch_NA = '.', pos_NA = 1.07,
165 plot_loess = TRUE, col_loess = 2, span_loess = 0.5,
166 which = c("1d", "2d"), plot = TRUE, ...) {
167 data_list <- xgb.shap.data(
168 data = data,
169 shap_contrib = shap_contrib,
170 features = features,
171 top_n = top_n,
172 model = model,
173 trees = trees,
174 target_class = target_class,
175 approxcontrib = approxcontrib,
176 subsample = subsample,
177 max_observations = 100000
178 )
179 data <- data_list[["data"]]
180 shap_contrib <- data_list[["shap_contrib"]]
181 features <- colnames(data)
182
183 which <- match.arg(which)
184 if (which == "2d")
185 stop("2D plots are not implemented yet")
186
187 if (n_col > length(features)) n_col <- length(features)
188 if (plot && which == "1d") {
189 op <- par(mfrow = c(ceiling(length(features) / n_col), n_col),
190 oma = c(0, 0, 0, 0) + 0.2,
191 mar = c(3.5, 3.5, 0, 0) + 0.1,
192 mgp = c(1.7, 0.6, 0))
193 for (f in features) {
194 ord <- order(data[, f])
195 x <- data[, f][ord]
196 y <- shap_contrib[, f][ord]
197 x_lim <- range(x, na.rm = TRUE)
198 y_lim <- range(y, na.rm = TRUE)
199 do_na <- plot_NA && anyNA(x)
200 if (do_na) {
201 x_range <- diff(x_lim)
202 loc_na <- min(x, na.rm = TRUE) + x_range * pos_NA
203 x_lim <- range(c(x_lim, loc_na))
204 }
205 x_uniq <- unique(x)
206 x2plot <- x
207 # add small jitter for discrete features with <= 5 distinct values
208 if (length(x_uniq) <= discrete_n_uniq)
209 x2plot <- jitter(x, amount = discrete_jitter * min(diff(x_uniq), na.rm = TRUE))
210 plot(x2plot, y, pch = pch, xlab = f, col = col, xlim = x_lim, ylim = y_lim, ylab = ylab, ...)
211 grid()
212 if (plot_loess) {
213 # compress x to 3 digits, and mean-aggregate y
214 zz <- data.table(x = signif(x, 3), y)[, .(.N, y = mean(y)), x]
215 if (nrow(zz) <= 5) {
216 lines(zz$x, zz$y, col = col_loess)
217 } else {
218 lo <- stats::loess(y ~ x, data = zz, weights = zz$N, span = span_loess)
219 zz$y_lo <- predict(lo, zz, type = "link")
220 lines(zz$x, zz$y_lo, col = col_loess)
221 }
222 }
223 if (do_na) {
224 i_na <- which(is.na(x))
225 x_na <- rep(loc_na, length(i_na))
226 x_na <- jitter(x_na, amount = x_range * 0.01)
227 points(x_na, y[i_na], pch = pch_NA, col = col_NA)
228 }
229 }
230 par(op)
231 }
232 if (plot && which == "2d") {
233 # TODO
234 warning("Bivariate plotting is currently not available.")
235 }
236 invisible(list(data = data, shap_contrib = shap_contrib))
237 }
238
239 #' SHAP summary plot
240 #'
241 #' Visualizes SHAP contributions of different features.
242 #'
243 #' A point plot (each point representing one observation from `data`) is
244 #' produced for each feature, with the points plotted on the SHAP value axis.
245 #' Each point (observation) is coloured based on its feature value.
246 #'
247 #' The plot allows to see which features have a negative / positive contribution
248 #' on the model prediction, and whether the contribution is different for larger
249 #' or smaller values of the feature. Inspired by the summary plot of
250 #' <https://github.com/shap/shap>.
251 #'
252 #' @inheritParams xgb.plot.shap
253 #'
254 #' @return A `ggplot2` object.
255 #' @export
256 #'
257 #' @examples
258 #' # See examples in xgb.plot.shap()
259 #'
260 #' @seealso [xgb.plot.shap()], [xgb.ggplot.shap.summary()],
261 #' and the Python library <https://github.com/shap/shap>.
262 xgb.plot.shap.summary <- function(data, shap_contrib = NULL, features = NULL, top_n = 10, model = NULL,
263 trees = NULL, target_class = NULL, approxcontrib = FALSE, subsample = NULL) {
264 # Only ggplot implementation is available.
265 xgb.ggplot.shap.summary(data, shap_contrib, features, top_n, model, trees, target_class, approxcontrib, subsample)
266 }
267
268 #' Prepare data for SHAP plots
269 #'
270 #' Internal function used in [xgb.plot.shap()], [xgb.plot.shap.summary()], etc.
271 #'
272 #' @inheritParams xgb.plot.shap
273 #' @param max_observations Maximum number of observations to consider.
274 #' @keywords internal
275 #' @noRd
276 #'
277 #' @return
278 #' A list containing:
279 #' - `data`: The matrix of feature values.
280 #' - `shap_contrib`: The matrix with corresponding SHAP values.
281 xgb.shap.data <- function(data, shap_contrib = NULL, features = NULL, top_n = 1, model = NULL,
282 trees = NULL, target_class = NULL, approxcontrib = FALSE,
283 subsample = NULL, max_observations = 100000) {
284 if (!inherits(data, c("matrix", "dsparseMatrix", "data.frame")))
285 stop("data: must be matrix, sparse matrix, or data.frame.")
286 if (inherits(data, "data.frame") && length(class(data)) > 1L) {
287 data <- as.data.frame(data)
288 }
289
290 if (is.null(shap_contrib) && (is.null(model) || !inherits(model, "xgb.Booster")))
291 stop("when shap_contrib is not provided, one must provide an xgb.Booster model")
292
293 if (is.null(features) && (is.null(model) || !inherits(model, "xgb.Booster")))
294 stop("when features are not provided, one must provide an xgb.Booster model to rank the features")
295
296 last_dim <- function(v) dim(v)[length(dim(v))]
297
298 if (!is.null(shap_contrib) &&
299 (!is.array(shap_contrib) || nrow(shap_contrib) != nrow(data) || last_dim(shap_contrib) != ncol(data) + 1))
300 stop("shap_contrib is not compatible with the provided data")
301
302 if (is.character(features) && is.null(colnames(data)))
303 stop("either provide `data` with column names or provide `features` as column indices")
304
305 model_feature_names <- NULL
306 if (is.null(features) && !is.null(model)) {
307 model_feature_names <- xgb.feature_names(model)
308 }
309 if (is.null(model_feature_names) && xgb.num_feature(model) != ncol(data))
310 stop("if model has no feature_names, columns in `data` must match features in model")
311
312 if (!is.null(subsample)) {
313 if (subsample <= 0 || subsample >= 1) {
314 stop("'subsample' must be a number between zero and one (non-inclusive).")
315 }
316 sample_size <- as.integer(subsample * nrow(data))
317 if (sample_size < 2) {
318 stop("Sampling fraction involves less than 2 rows.")
319 }
320 idx <- sample(x = seq_len(nrow(data)), size = sample_size, replace = FALSE)
321 } else {
322 idx <- seq_len(min(nrow(data), max_observations))
323 }
324 data <- data[idx, ]
325 if (is.null(colnames(data))) {
326 colnames(data) <- paste0("X", seq_len(ncol(data)))
327 }
328
329 reshape_3d_shap_contrib <- function(shap_contrib, target_class) {
330 # multiclass: either choose a class or merge
331 if (is.list(shap_contrib)) {
332 if (!is.null(target_class)) {
333 shap_contrib <- shap_contrib[[target_class + 1]]
334 } else {
335 shap_contrib <- Reduce("+", lapply(shap_contrib, abs))
336 }
337 } else if (length(dim(shap_contrib)) > 2) {
338 if (!is.null(target_class)) {
339 orig_shape <- dim(shap_contrib)
340 shap_contrib <- shap_contrib[, target_class + 1, , drop = TRUE]
341 if (!is.matrix(shap_contrib)) {
342 shap_contrib <- matrix(shap_contrib, orig_shape[c(1L, 3L)])
343 }
344 } else {
345 shap_contrib <- apply(abs(shap_contrib), c(1L, 3L), sum)
346 }
347 }
348 return(shap_contrib)
349 }
350
351 if (is.null(shap_contrib)) {
352 shap_contrib <- predict.xgb.Booster(
353 model,
354 newdata = data,
355 predcontrib = TRUE,
356 approxcontrib = approxcontrib
357 )
358 }
359 shap_contrib <- reshape_3d_shap_contrib(shap_contrib, target_class)
360 if (is.null(colnames(shap_contrib))) {
361 colnames(shap_contrib) <- paste0("X", seq_len(ncol(data)))
362 }
363
364 if (is.null(features)) {
365 if (!is.null(model_feature_names)) {
366 imp <- xgb.importance(model = model, trees = trees)
367 } else {
368 imp <- xgb.importance(model = model, trees = trees, feature_names = colnames(data))
369 }
370 top_n <- top_n[1]
371 if (top_n < 1 || top_n > 100) stop("top_n: must be an integer within [1, 100]")
372 features <- imp$Feature[seq_len(min(top_n, NROW(imp)))]
373 }
374 if (is.character(features)) {
375 features <- match(features, colnames(data))
376 }
377
378 shap_contrib <- shap_contrib[, features, drop = FALSE]
379 data <- data[, features, drop = FALSE]
380
381 list(
382 data = data,
383 shap_contrib = shap_contrib
384 )
385 }