lgb.importance.R 2.1 KB
Newer Older
1
2
3
#' @name lgb.importance
#' @title Compute feature importance in a model
#' @description Creates a \code{data.table} of feature importances in a model.
4
5
#' @param model object of class \code{lgb.Booster}.
#' @param percentage whether to show importance in relative percentage.
6
#'
7
#' @return For a tree model, a \code{data.table} with the following columns:
8
#' \itemize{
9
10
11
12
#'   \item{\code{Feature}: Feature names in the model.}
#'   \item{\code{Gain}: The total gain of this feature's splits.}
#'   \item{\code{Cover}: The number of observation related to this feature.}
#'   \item{\code{Frequency}: The number of times a feature splited in trees.}
13
#' }
14
#'
15
#' @examples
16
17
#' library(lightgbm)
#' data(agaricus.train, package = "lightgbm")
18
19
20
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#'
21
22
23
#' params <- list(
#'   objective = "binary"
#'   , learning_rate = 0.01
24
25
26
27
#'   , num_leaves = 63L
#'   , max_depth = -1L
#'   , min_data_in_leaf = 1L
#'   , min_sum_hessian_in_leaf = 1.0
28
#' )
29
#' model <- lgb.train(params, dtrain, 10L)
30
31
32
#'
#' tree_imp1 <- lgb.importance(model, percentage = TRUE)
#' tree_imp2 <- lgb.importance(model, percentage = FALSE)
33
#'
34
#' @importFrom data.table := setnames setorderv
35
36
#' @export
lgb.importance <- function(model, percentage = TRUE) {
37

38
  # Check if model is a lightgbm model
39
  if (!inherits(model, "lgb.Booster")) {
40
41
    stop("'model' has to be an object of class lgb.Booster")
  }
42

43
  # Setup importance
44
  tree_dt <- lgb.model.dt.tree(model)
45

46
  # Extract elements
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  tree_imp_dt <- tree_dt[
    !is.na(split_index)
    , .(Gain = sum(split_gain), Cover = sum(internal_count), Frequency = .N)
    , by = "split_feature"
  ]

  data.table::setnames(
    tree_imp_dt
    , old = "split_feature"
    , new = "Feature"
  )

  # Sort features by Gain
  data.table::setorderv(
    x = tree_imp_dt
62
63
    , cols = "Gain"
    , order = -1L
64
  )
65

66
  # Check if relative values are requested
67
  if (percentage) {
68
69
70
71
72
    tree_imp_dt[, `:=`(
      Gain = Gain / sum(Gain)
      , Cover = Cover / sum(Cover)
      , Frequency = Frequency / sum(Frequency)
    )]
73
  }
74

75
  # Return importance table
76
  return(tree_imp_dt)
77

78
}