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

71
  num_class <- ncol(tree_interpretation_dt) - 1L
72

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

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

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

91
  if (num_class == 1L) {
92

93
    # Only one class, plot straight away
94
    .multiple_tree_plot_interpretation(
95
      tree_interpretation = tree_interpretation_dt
96
97
98
99
      , top_n = top_n
      , title = NULL
      , cex = cex
    )
100

101
  } else {
102

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

110
    # Shape output
James Lamb's avatar
James Lamb committed
111
    graphics::par(mfcol = c(nrow(layout_mat), ncol(layout_mat)))
112

113
    # Loop throughout all classes
114
    for (i in seq_len(num_class)) {
115

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

130
131
    }
  }
132
  return(invisible(NULL))
133
134
}

135
#' @importFrom graphics barplot
136
.multiple_tree_plot_interpretation <- function(tree_interpretation,
137
138
139
                                              top_n,
                                              title,
                                              cex) {
140

141
  # Parse tree
142
  tree_interpretation <- tree_interpretation[order(abs(Contribution), decreasing = TRUE), ][seq_len(min(top_n, .N)), ]
143

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

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

164
  return(invisible(NULL))
165

166
}