lgb.plot.interpretation.R 4.64 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
#' \donttest{
19
20
21
#' Logit <- function(x) {
#'   log(x / (1.0 - x))
#' }
22
#' data(agaricus.train, package = "lightgbm")
23
24
25
26
27
#' labels <- agaricus.train$label
#' dtrain <- lgb.Dataset(
#'   agaricus.train$data
#'   , label = labels
#' )
28
29
30
31
32
#' set_field(
#'   dataset = dtrain
#'   , field_name = "init_score"
#'   , data = rep(Logit(mean(labels)), length(labels))
#' )
33
#'
34
#' data(agaricus.test, package = "lightgbm")
35
#'
36
37
#' params <- list(
#'   objective = "binary"
38
#'   , learning_rate = 0.1
39
40
41
#'   , max_depth = -1L
#'   , min_data_in_leaf = 1L
#'   , min_sum_hessian_in_leaf = 1.0
42
#' )
43
44
45
46
47
#' model <- lgb.train(
#'   params = params
#'   , data = dtrain
#'   , nrounds = 5L
#' )
48
#'
49
50
51
52
53
54
55
#' tree_interpretation <- lgb.interprete(
#'   model = model
#'   , data = agaricus.test$data
#'   , idxset = 1L:5L
#' )
#' lgb.plot.interpretation(
#'   tree_interpretation_dt = tree_interpretation[[1L]]
56
#'   , top_n = 3L
57
58
#' )
#' }
59
#' @importFrom data.table setnames
James Lamb's avatar
James Lamb committed
60
#' @importFrom graphics barplot par
61
#' @export
62
lgb.plot.interpretation <- function(tree_interpretation_dt,
63
64
65
                                    top_n = 10L,
                                    cols = 1L,
                                    left_margin = 10L,
66
                                    cex = NULL) {
67

68
  num_class <- ncol(tree_interpretation_dt) - 1L
69

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

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

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

88
  if (num_class == 1L) {
89

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

98
  } else {
99

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

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

110
    # Loop throughout all classes
111
    for (i in seq_len(num_class)) {
112

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

127
128
    }
  }
129
  return(invisible(NULL))
130
131
}

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

138
  # Parse tree
139
  tree_interpretation <- tree_interpretation[order(abs(Contribution), decreasing = TRUE), ][seq_len(min(top_n, .N)), ]
140

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

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

161
  return(invisible(NULL))
162

163
}