lgb.plot.interpretation.R 4.58 KB
Newer Older
1
2
3
#' @name lgb.plot.interpretation
#' @title Plot feature contribution as a bar graph
#' @description Plot previously calculated feature contribution as a bar graph.
4
5
6
7
8
#' @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}.
9
#'
10
#' @details
11
12
#' 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.
13
#'
14
#' @return
15
#' The \code{lgb.plot.interpretation} function creates a \code{barplot}.
16
#'
17
#' @examples
18
19
20
21
#' \donttest{
#' Logit <- function(x) {
#'   log(x / (1.0 - x))
#' }
22
#' data(agaricus.train, package = "lightgbm")
23
24
25
26
27
28
29
#' labels <- agaricus.train$label
#' dtrain <- lgb.Dataset(
#'   agaricus.train$data
#'   , label = labels
#' )
#' setinfo(dtrain, "init_score", rep(Logit(mean(labels)), length(labels)))
#'
30
#' data(agaricus.test, package = "lightgbm")
31
#'
32
33
#' params <- list(
#'   objective = "binary"
34
#'   , learning_rate = 0.1
35
36
37
#'   , max_depth = -1L
#'   , min_data_in_leaf = 1L
#'   , min_sum_hessian_in_leaf = 1.0
38
#' )
39
40
41
42
43
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
#'   , nrounds = 5L
#' )
44
#'
45
46
47
48
49
50
51
#' tree_interpretation <- lgb.interprete(
#'   model = model
#'   , data = agaricus.test$data
#'   , idxset = 1L:5L
#' )
#' lgb.plot.interpretation(
#'   tree_interpretation_dt = tree_interpretation[[1L]]
52
#'   , top_n = 3L
53
54
#' )
#' }
55
#' @importFrom data.table setnames
James Lamb's avatar
James Lamb committed
56
#' @importFrom graphics barplot par
57
#' @export
58
lgb.plot.interpretation <- function(tree_interpretation_dt,
59
60
61
                                    top_n = 10L,
                                    cols = 1L,
                                    left_margin = 10L,
62
                                    cex = NULL) {
63

64
  # Get number of columns
65
  num_class <- ncol(tree_interpretation_dt) - 1L
66

67
  # Refresh plot
James Lamb's avatar
James Lamb committed
68
69
  op <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(op))
70

71
  # Do some magic plotting
72
73
  bottom_margin <- 3.0
  top_margin <- 2.0
74
  right_margin <- op$mar[4L]
75
76
77
78
79
80
81
82
83

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

85
  # Check for number of classes
86
  if (num_class == 1L) {
87

88
    # Only one class, plot straight away
89
90
91
92
93
94
    multiple.tree.plot.interpretation(
      tree_interpretation_dt
      , top_n = top_n
      , title = NULL
      , cex = cex
    )
95

96
  } else {
97

98
    # More than one class, shape data first
99
100
101
102
103
    layout_mat <- matrix(
      seq.int(to = cols * ceiling(num_class / cols))
      , ncol = cols
      , nrow = ceiling(num_class / cols)
    )
104

105
    # Shape output
James Lamb's avatar
James Lamb committed
106
    graphics::par(mfcol = c(nrow(layout_mat), ncol(layout_mat)))
107

108
    # Loop throughout all classes
109
    for (i in seq_len(num_class)) {
110

111
      # Prepare interpretation, perform T, get the names, and plot straight away
112
      plot_dt <- tree_interpretation_dt[, c(1L, i + 1L), with = FALSE]
113
114
115
116
117
118
119
120
      data.table::setnames(
        plot_dt
        , old = names(plot_dt)
        , new = c("Feature", "Contribution")
      )
      multiple.tree.plot.interpretation(
        plot_dt
        , top_n = top_n
121
        , title = paste("Class", i - 1L)
122
123
        , cex = cex
      )
124

125
126
127
128
    }
  }
}

129
#' @importFrom graphics barplot
130
131
132
133
multiple.tree.plot.interpretation <- function(tree_interpretation,
                                              top_n,
                                              title,
                                              cex) {
134

135
  # Parse tree
136
  tree_interpretation <- tree_interpretation[order(abs(Contribution), decreasing = TRUE), ][seq_len(min(top_n, .N)), ]
137

138
  # Attempt to setup a correct cex
139
  if (is.null(cex)) {
140
    cex <- 2.5 / log2(1.0 + top_n)
141
  }
142

143
  # create plot
144
  tree_interpretation[abs(Contribution) > 0.0, bar_color := "firebrick"]
145
  tree_interpretation[Contribution == 0.0, bar_color := "steelblue"]
146
  tree_interpretation[.N:1L,
James Lamb's avatar
James Lamb committed
147
                      graphics::barplot(
148
149
150
                          height = Contribution
                          , names.arg = Feature
                          , horiz = TRUE
151
                          , col = bar_color
152
153
154
                          , border = NA
                          , main = title
                          , cex.names = cex
155
                          , las = 1L
James Lamb's avatar
James Lamb committed
156
                      )]
157

158
  # Return invisibly
159
  return(invisible(NULL))
160

161
}