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

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

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

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

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

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

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

81
  } else {
82

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

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

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

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

110
111
112
113
    }
  }
}

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

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

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

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

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

144
}