| 1 |
# ggplot backend for the xgboost plotting facilities |
| 2 |
|
| 3 |
#' @rdname xgb.plot.importance |
| 4 |
#' @export |
| 5 |
xgb.ggplot.importance <- function(importance_matrix = NULL, top_n = NULL, measure = NULL, |
| 6 |
rel_to_first = FALSE, n_clusters = seq_len(10), ...) { |
| 7 |
|
| 8 |
importance_matrix <- xgb.plot.importance(importance_matrix, top_n = top_n, measure = measure, |
| 9 |
rel_to_first = rel_to_first, plot = FALSE, ...) |
| 10 |
if (!requireNamespace("ggplot2", quietly = TRUE)) { |
| 11 |
stop("ggplot2 package is required", call. = FALSE) |
| 12 |
} |
| 13 |
if (!requireNamespace("Ckmeans.1d.dp", quietly = TRUE)) { |
| 14 |
stop("Ckmeans.1d.dp package is required", call. = FALSE) |
| 15 |
} |
| 16 |
|
| 17 |
clusters <- suppressWarnings( |
| 18 |
Ckmeans.1d.dp::Ckmeans.1d.dp(importance_matrix$Importance, n_clusters) |
| 19 |
) |
| 20 |
importance_matrix[, Cluster := as.character(clusters$cluster)] |
| 21 |
|
| 22 |
plot <- |
| 23 |
ggplot2::ggplot(importance_matrix, |
| 24 |
ggplot2::aes(x = factor(Feature, levels = rev(Feature)), y = Importance, width = 0.5), |
| 25 |
environment = environment()) + |
| 26 |
ggplot2::geom_bar(ggplot2::aes(fill = Cluster), stat = "identity", position = "identity") + |
| 27 |
ggplot2::coord_flip() + |
| 28 |
ggplot2::xlab("Features") + |
| 29 |
ggplot2::ggtitle("Feature importance") + |
| 30 |
ggplot2::theme(plot.title = ggplot2::element_text(lineheight = .9, face = "bold"), |
| 31 |
panel.grid.major.y = ggplot2::element_blank()) |
| 32 |
return(plot) |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
#' @rdname xgb.plot.deepness |
| 37 |
#' @export |
| 38 |
xgb.ggplot.deepness <- function(model = NULL, which = c("2x1", "max.depth", "med.depth", "med.weight")) { |
| 39 |
|
| 40 |
if (!requireNamespace("ggplot2", quietly = TRUE)) |
| 41 |
stop("ggplot2 package is required for plotting the graph deepness.", call. = FALSE) |
| 42 |
|
| 43 |
which <- match.arg(which) |
| 44 |
|
| 45 |
dt_depths <- xgb.plot.deepness(model = model, plot = FALSE) |
| 46 |
dt_summaries <- dt_depths[, .(.N, Cover = mean(Cover)), Depth] |
| 47 |
setkey(dt_summaries, 'Depth') |
| 48 |
|
| 49 |
if (which == "2x1") { |
| 50 |
p1 <- |
| 51 |
ggplot2::ggplot(dt_summaries) + |
| 52 |
ggplot2::geom_bar(ggplot2::aes(x = Depth, y = N), stat = "Identity") + |
| 53 |
ggplot2::xlab("") + |
| 54 |
ggplot2::ylab("Number of leafs") + |
| 55 |
ggplot2::ggtitle("Model complexity") + |
| 56 |
ggplot2::theme( |
| 57 |
plot.title = ggplot2::element_text(lineheight = 0.9, face = "bold"), |
| 58 |
panel.grid.major.y = ggplot2::element_blank(), |
| 59 |
axis.ticks = ggplot2::element_blank(), |
| 60 |
axis.text.x = ggplot2::element_blank() |
| 61 |
) |
| 62 |
|
| 63 |
p2 <- |
| 64 |
ggplot2::ggplot(dt_summaries) + |
| 65 |
ggplot2::geom_bar(ggplot2::aes(x = Depth, y = Cover), stat = "Identity") + |
| 66 |
ggplot2::xlab("Leaf depth") + |
| 67 |
ggplot2::ylab("Weighted cover") |
| 68 |
|
| 69 |
multiplot(p1, p2, cols = 1) |
| 70 |
return(invisible(list(p1, p2))) |
| 71 |
|
| 72 |
} else if (which == "max.depth") { |
| 73 |
p <- |
| 74 |
ggplot2::ggplot(dt_depths[, max(Depth), Tree]) + |
| 75 |
ggplot2::geom_jitter(ggplot2::aes(x = Tree, y = V1), |
| 76 |
height = 0.15, alpha = 0.4, size = 3, stroke = 0) + |
| 77 |
ggplot2::xlab("tree #") + |
| 78 |
ggplot2::ylab("Max tree leaf depth") |
| 79 |
return(p) |
| 80 |
|
| 81 |
} else if (which == "med.depth") { |
| 82 |
p <- |
| 83 |
ggplot2::ggplot(dt_depths[, median(as.numeric(Depth)), Tree]) + |
| 84 |
ggplot2::geom_jitter(ggplot2::aes(x = Tree, y = V1), |
| 85 |
height = 0.15, alpha = 0.4, size = 3, stroke = 0) + |
| 86 |
ggplot2::xlab("tree #") + |
| 87 |
ggplot2::ylab("Median tree leaf depth") |
| 88 |
return(p) |
| 89 |
|
| 90 |
} else if (which == "med.weight") { |
| 91 |
p <- |
| 92 |
ggplot2::ggplot(dt_depths[, median(abs(Weight)), Tree]) + |
| 93 |
ggplot2::geom_point(ggplot2::aes(x = Tree, y = V1), |
| 94 |
alpha = 0.4, size = 3, stroke = 0) + |
| 95 |
ggplot2::xlab("tree #") + |
| 96 |
ggplot2::ylab("Median absolute leaf weight") |
| 97 |
return(p) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
#' @rdname xgb.plot.shap.summary |
| 102 |
#' @export |
| 103 |
xgb.ggplot.shap.summary <- function(data, shap_contrib = NULL, features = NULL, top_n = 10, model = NULL, |
| 104 |
trees = NULL, target_class = NULL, approxcontrib = FALSE, subsample = NULL) { |
| 105 |
if (inherits(data, "xgb.DMatrix")) { |
| 106 |
stop( |
| 107 |
"'xgb.ggplot.shap.summary' is not compatible with 'xgb.DMatrix' objects. Try passing a matrix or data.frame." |
| 108 |
) |
| 109 |
} |
| 110 |
cols_categ <- NULL |
| 111 |
if (!is.null(model)) { |
| 112 |
ftypes <- getinfo(model, "feature_type") |
| 113 |
if (NROW(ftypes)) { |
| 114 |
if (length(ftypes) != ncol(data)) { |
| 115 |
stop(sprintf("'data' has incorrect number of columns (expected: %d, got: %d).", length(ftypes), ncol(data))) |
| 116 |
} |
| 117 |
cols_categ <- colnames(data)[ftypes == "c"] |
| 118 |
} |
| 119 |
} else if (inherits(data, "data.frame")) { |
| 120 |
cols_categ <- names(data)[sapply(data, function(x) is.factor(x) || is.character(x))] |
| 121 |
} |
| 122 |
if (NROW(cols_categ)) { |
| 123 |
warning("Categorical features are ignored in 'xgb.ggplot.shap.summary'.") |
| 124 |
} |
| 125 |
|
| 126 |
data_list <- xgb.shap.data( |
| 127 |
data = data, |
| 128 |
shap_contrib = shap_contrib, |
| 129 |
features = features, |
| 130 |
top_n = top_n, |
| 131 |
model = model, |
| 132 |
trees = trees, |
| 133 |
target_class = target_class, |
| 134 |
approxcontrib = approxcontrib, |
| 135 |
subsample = subsample, |
| 136 |
max_observations = 10000 # 10,000 samples per feature. |
| 137 |
) |
| 138 |
if (NROW(cols_categ)) { |
| 139 |
data_list <- lapply(data_list, function(x) x[, !(colnames(x) %in% cols_categ), drop = FALSE]) |
| 140 |
} |
| 141 |
|
| 142 |
p_data <- prepare.ggplot.shap.data(data_list, normalize = TRUE) |
| 143 |
# Reverse factor levels so that the first level is at the top of the plot |
| 144 |
p_data[, "feature" := factor(feature, rev(levels(feature)))] |
| 145 |
p <- ggplot2::ggplot(p_data, ggplot2::aes(x = feature, y = p_data$shap_value, colour = p_data$feature_value)) + |
| 146 |
ggplot2::geom_jitter(alpha = 0.5, width = 0.1) + |
| 147 |
ggplot2::scale_colour_viridis_c(limits = c(-3, 3), option = "plasma", direction = -1) + |
| 148 |
ggplot2::geom_abline(slope = 0, intercept = 0, colour = "darkgrey") + |
| 149 |
ggplot2::coord_flip() |
| 150 |
|
| 151 |
p |
| 152 |
} |
| 153 |
|
| 154 |
#' Combine feature values and SHAP values |
| 155 |
#' |
| 156 |
#' Internal function used to combine and melt feature values and SHAP contributions |
| 157 |
#' as required for ggplot functions related to SHAP. |
| 158 |
#' |
| 159 |
#' @param data_list The result of `xgb.shap.data()`. |
| 160 |
#' @param normalize Whether to standardize feature values to mean 0 and |
| 161 |
#' standard deviation 1. This is useful for comparing multiple features on the same |
| 162 |
#' plot. Default is `FALSE`. Note that it cannot be used when the data contains |
| 163 |
#' categorical features. |
| 164 |
#' @return A `data.table` containing the observation ID, the feature name, the |
| 165 |
#' feature value (normalized if specified), and the SHAP contribution value. |
| 166 |
#' @noRd |
| 167 |
#' @keywords internal |
| 168 |
prepare.ggplot.shap.data <- function(data_list, normalize = FALSE) { |
| 169 |
data <- data_list[["data"]] |
| 170 |
shap_contrib <- data_list[["shap_contrib"]] |
| 171 |
|
| 172 |
data <- data.table::as.data.table(as.matrix(data)) |
| 173 |
if (normalize) { |
| 174 |
data[, (names(data)) := lapply(.SD, normalize)] |
| 175 |
} |
| 176 |
data[, "id" := seq_len(nrow(data))] |
| 177 |
data_m <- data.table::melt.data.table(data, id.vars = "id", variable.name = "feature", value.name = "feature_value") |
| 178 |
|
| 179 |
shap_contrib <- data.table::as.data.table(as.matrix(shap_contrib)) |
| 180 |
shap_contrib[, "id" := seq_len(nrow(shap_contrib))] |
| 181 |
shap_contrib_m <- data.table::melt.data.table(shap_contrib, id.vars = "id", variable.name = "feature", value.name = "shap_value") |
| 182 |
|
| 183 |
p_data <- data.table::merge.data.table(data_m, shap_contrib_m, by = c("id", "feature")) |
| 184 |
|
| 185 |
p_data |
| 186 |
} |
| 187 |
|
| 188 |
#' Scale feature values |
| 189 |
#' |
| 190 |
#' Internal function that scales feature values to mean 0 and standard deviation 1. |
| 191 |
#' Useful to compare multiple features on the same plot. |
| 192 |
#' |
| 193 |
#' @param x Numeric vector. |
| 194 |
#' @return Numeric vector with mean 0 and standard deviation 1. |
| 195 |
#' @noRd |
| 196 |
#' @keywords internal |
| 197 |
normalize <- function(x) { |
| 198 |
loc <- mean(x, na.rm = TRUE) |
| 199 |
scale <- stats::sd(x, na.rm = TRUE) |
| 200 |
|
| 201 |
(x - loc) / scale |
| 202 |
} |
| 203 |
|
| 204 |
# Plot multiple ggplot graph aligned by rows and columns. |
| 205 |
# ... the plots |
| 206 |
# cols number of columns |
| 207 |
# internal utility function |
| 208 |
multiplot <- function(..., cols) { |
| 209 |
plots <- list(...) |
| 210 |
num_plots <- length(plots) |
| 211 |
|
| 212 |
layout <- matrix(seq(1, cols * ceiling(num_plots / cols)), |
| 213 |
ncol = cols, nrow = ceiling(num_plots / cols)) |
| 214 |
|
| 215 |
if (num_plots == 1) { |
| 216 |
print(plots[[1]]) |
| 217 |
} else { |
| 218 |
grid::grid.newpage() |
| 219 |
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout)))) |
| 220 |
for (i in 1:num_plots) { |
| 221 |
# Get the i,j matrix positions of the regions that contain this subplot |
| 222 |
matchidx <- as.data.table(which(layout == i, arr.ind = TRUE)) |
| 223 |
|
| 224 |
print( |
| 225 |
plots[[i]], vp = grid::viewport( |
| 226 |
layout.pos.row = matchidx$row, |
| 227 |
layout.pos.col = matchidx$col |
| 228 |
) |
| 229 |
) |
| 230 |
} |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
globalVariables(c( |
| 235 |
"Cluster", "ggplot", "aes", "geom_bar", "coord_flip", "xlab", "ylab", "ggtitle", "theme", |
| 236 |
"element_blank", "element_text", "V1", "Weight", "feature" |
| 237 |
)) |