lgb.plot.interpretation.R 4.36 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
#' @details
12
13
#' 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
#' library(lightgbm)
20
21
#' Sigmoid <- function(x) {1.0 / (1.0 + exp(-x))}
#' Logit <- function(x) {log(x / (1.0 - x))}
22
#' 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
30
31
#' params <- list(
#'   objective = "binary"
#'   , learning_rate = 0.01
32
33
34
35
#'   , num_leaves = 63L
#'   , max_depth = -1L
#'   , min_data_in_leaf = 1L
#'   , min_sum_hessian_in_leaf = 1.0
36
#' )
37
#' model <- lgb.train(params, dtrain, 10L)
38
#'
39
40
#' tree_interpretation <- lgb.interprete(model, test$data, 1L:5L)
#' lgb.plot.interpretation(tree_interpretation[[1L]], top_n = 10L)
41
#' @importFrom data.table setnames
James Lamb's avatar
James Lamb committed
42
#' @importFrom graphics barplot par
43
#' @export
44
lgb.plot.interpretation <- function(tree_interpretation_dt,
45
46
47
                                    top_n = 10L,
                                    cols = 1L,
                                    left_margin = 10L,
48
                                    cex = NULL) {
49

50
  # Get number of columns
51
  num_class <- ncol(tree_interpretation_dt) - 1L
52

53
  # Refresh plot
James Lamb's avatar
James Lamb committed
54
55
  op <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(op))
56

57
  # Do some magic plotting
58
59
  bottom_margin <- 3.0
  top_margin <- 2.0
60
  right_margin <- op$mar[4L]
61
62
63
64
65
66
67
68
69

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

71
  # Check for number of classes
72
  if (num_class == 1L) {
73

74
    # Only one class, plot straight away
75
76
77
78
79
80
    multiple.tree.plot.interpretation(
      tree_interpretation_dt
      , top_n = top_n
      , title = NULL
      , cex = cex
    )
81

82
  } else {
83

84
    # More than one class, shape data first
85
86
87
88
89
    layout_mat <- matrix(
      seq.int(to = cols * ceiling(num_class / cols))
      , ncol = cols
      , nrow = ceiling(num_class / cols)
    )
90

91
    # Shape output
James Lamb's avatar
James Lamb committed
92
    graphics::par(mfcol = c(nrow(layout_mat), ncol(layout_mat)))
93

94
    # Loop throughout all classes
95
    for (i in seq_len(num_class)) {
96

97
      # Prepare interpretation, perform T, get the names, and plot straight away
98
      plot_dt <- tree_interpretation_dt[, c(1L, i + 1L), with = FALSE]
99
100
101
102
103
104
105
106
      data.table::setnames(
        plot_dt
        , old = names(plot_dt)
        , new = c("Feature", "Contribution")
      )
      multiple.tree.plot.interpretation(
        plot_dt
        , top_n = top_n
107
        , title = paste("Class", i - 1L)
108
109
        , cex = cex
      )
110

111
112
113
114
    }
  }
}

115
#' @importFrom graphics barplot
116
117
118
119
multiple.tree.plot.interpretation <- function(tree_interpretation,
                                              top_n,
                                              title,
                                              cex) {
120

121
  # Parse tree
122
  tree_interpretation <- tree_interpretation[order(abs(Contribution), decreasing = TRUE), ][seq_len(min(top_n, .N)), ]
123

124
  # Attempt to setup a correct cex
125
  if (is.null(cex)) {
126
    cex <- 2.5 / log2(1.0 + top_n)
127
  }
128

129
  # Do plot
130
  tree_interpretation[.N:1L,
James Lamb's avatar
James Lamb committed
131
                      graphics::barplot(
132
133
134
                          height = Contribution
                          , names.arg = Feature
                          , horiz = TRUE
135
                          , col = ifelse(Contribution > 0L, "firebrick", "steelblue")
136
137
138
                          , border = NA
                          , main = title
                          , cex.names = cex
139
                          , las = 1L
James Lamb's avatar
James Lamb committed
140
                      )]
141

142
  # Return invisibly
143
  return(invisible(NULL))
144

145
}