lgb.plot.interpretation.R 4.4 KB
Newer Older
1
#' Plot feature contribution as a bar graph
2
#'
3
#' Plot previously calculated feature contribution as a bar graph.
4
#'
5
6
7
8
9
#' @param tree_interpretation_dt a \code{data.table} returned by \code{\link{lgb.interprete}}.
#' @param top_n maximal number of top features to include into the plot.
#' @param cols the column numbers of layout, will be used only for multiclass classification feature contribution.
#' @param left_margin (base R barplot) allows to adjust the left margin size to fit feature names.
#' @param cex (base R barplot) passed as \code{cex.names} parameter to \code{barplot}.
10
#'
11
12
13
#' @details
#' The graph represents each feature as a horizontal bar of length proportional to the defined contribution of a feature.
#' Features are shown ranked in a decreasing contribution order.
14
#'
15
#' @return
16
#' The \code{lgb.plot.interpretation} function creates a \code{barplot}.
17
#'
18
#' @examples
19
20
21
22
#' library(lightgbm)
#' Sigmoid <- function(x) {1 / (1 + exp(-x))}
#' Logit <- function(x) {log(x / (1 - x))}
#' data(agaricus.train, package = "lightgbm")
23
24
25
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#' setinfo(dtrain, "init_score", rep(Logit(mean(train$label)), length(train$label)))
26
#' data(agaricus.test, package = "lightgbm")
27
#' test <- agaricus.test
28
#'
29
#' params <- list(objective = "binary",
30
31
32
#'                learning_rate = 0.01, num_leaves = 63, max_depth = -1,
#'                min_data_in_leaf = 1, min_sum_hessian_in_leaf = 1)
#' model <- lgb.train(params, dtrain, 10)
33
#'
34
35
#' tree_interpretation <- lgb.interprete(model, test$data, 1:5)
#' lgb.plot.interpretation(tree_interpretation[[1]], top_n = 10)
36
#' @importFrom data.table setnames
James Lamb's avatar
James Lamb committed
37
#' @importFrom graphics barplot par
38
#' @export
39
40
41
42
43
lgb.plot.interpretation <- function(tree_interpretation_dt,
                                    top_n = 10,
                                    cols = 1,
                                    left_margin = 10,
                                    cex = NULL) {
44

45
  # Get number of columns
46
  num_class <- ncol(tree_interpretation_dt) - 1
47

48
  # Refresh plot
James Lamb's avatar
James Lamb committed
49
50
  op <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(op))
51

52
  # Do some magic plotting
53
54
55
56
57
58
59
60
61
62
63
64
  bottom_margin <- 3.0
  top_margin <- 2.0
  right_margin <- op$mar[4]

  graphics::par(
    mar = c(
      bottom_margin
      , left_margin
      , top_margin
      , right_margin
    )
  )
65

66
  # Check for number of classes
67
  if (num_class == 1) {
68

69
70
71
72
73
    # Only one class, plot straight away
    multiple.tree.plot.interpretation(tree_interpretation_dt,
                                      top_n = top_n,
                                      title = NULL,
                                      cex = cex)
74

75
  } else {
76

77
    # More than one class, shape data first
78
    layout_mat <- matrix(seq.int(to = cols * ceiling(num_class / cols)),
79
                         ncol = cols, nrow = ceiling(num_class / cols))
80

81
    # Shape output
James Lamb's avatar
James Lamb committed
82
    graphics::par(mfcol = c(nrow(layout_mat), ncol(layout_mat)))
83

84
    # Loop throughout all classes
85
    for (i in seq_len(num_class)) {
86

87
      # Prepare interpretation, perform T, get the names, and plot straight away
88
89
90
91
92
93
94
95
96
97
98
99
      plot_dt <- tree_interpretation_dt[, c(1, i + 1), with = FALSE]
      data.table::setnames(
        plot_dt
        , old = names(plot_dt)
        , new = c("Feature", "Contribution")
      )
      multiple.tree.plot.interpretation(
        plot_dt
        , top_n = top_n
        , title = paste("Class", i - 1)
        , cex = cex
      )
100

101
102
103
104
    }
  }
}

105
#' @importFrom graphics barplot
106
107
108
109
multiple.tree.plot.interpretation <- function(tree_interpretation,
                                              top_n,
                                              title,
                                              cex) {
110

111
  # Parse tree
112
  tree_interpretation <- tree_interpretation[order(abs(Contribution), decreasing = TRUE),][seq_len(min(top_n, .N)),]
113

114
  # Attempt to setup a correct cex
115
116
117
  if (is.null(cex)) {
    cex <- 2.5 / log2(1 + top_n)
  }
118

119
  # Do plot
120
  tree_interpretation[.N:1,
James Lamb's avatar
James Lamb committed
121
122
123
124
125
126
127
128
129
130
                      graphics::barplot(
                          height = Contribution,
                          names.arg = Feature,
                          horiz = TRUE,
                          col = ifelse(Contribution > 0, "firebrick", "steelblue"),
                          border = NA,
                          main = title,
                          cex.names = cex,
                          las = 1
                      )]
131

132
  # Return invisibly
133
  return(invisible(NULL))
134

135
}