lgb.model.dt.tree.R 7.01 KB
Newer Older
1
2
3
#' @name lgb.model.dt.tree
#' @title Parse a LightGBM model json dump
#' @description Parse a LightGBM model json dump into a \code{data.table} structure.
4
#' @param model object of class \code{lgb.Booster}
James Lamb's avatar
James Lamb committed
5
#' @param num_iteration number of iterations you want to predict with. NULL or
James Lamb's avatar
James Lamb committed
6
#'                      <= 0 means use best iteration
7
8
#' @return
#' A \code{data.table} with detailed information about model trees' nodes and leafs.
James Lamb's avatar
James Lamb committed
9
#'
10
#' The columns of the \code{data.table} are:
James Lamb's avatar
James Lamb committed
11
#'
12
#' \itemize{
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#'  \item{\code{tree_index}: ID of a tree in a model (integer)}
#'  \item{\code{split_index}: ID of a node in a tree (integer)}
#'  \item{\code{split_feature}: for a node, it's a feature name (character);
#'                              for a leaf, it simply labels it as \code{"NA"}}
#'  \item{\code{node_parent}: ID of the parent node for current node (integer)}
#'  \item{\code{leaf_index}: ID of a leaf in a tree (integer)}
#'  \item{\code{leaf_parent}: ID of the parent node for current leaf (integer)}
#'  \item{\code{split_gain}: Split gain of a node}
#'  \item{\code{threshold}: Splitting threshold value of a node}
#'  \item{\code{decision_type}: Decision type of a node}
#'  \item{\code{default_left}: Determine how to handle NA value, TRUE -> Left, FALSE -> Right}
#'  \item{\code{internal_value}: Node value}
#'  \item{\code{internal_count}: The number of observation collected by a node}
#'  \item{\code{leaf_value}: Leaf value}
#'  \item{\code{leaf_count}: The number of observation collected by a leaf}
28
#' }
James Lamb's avatar
James Lamb committed
29
#'
30
#' @examples
31
#' \donttest{
32
33
#' \dontshow{setLGBMthreads(2L)}
#' \dontshow{data.table::setDTthreads(1L)}
34
#' data(agaricus.train, package = "lightgbm")
35
36
37
#' train <- agaricus.train
#' dtrain <- lgb.Dataset(train$data, label = train$label)
#'
38
39
40
#' params <- list(
#'   objective = "binary"
#'   , learning_rate = 0.01
41
42
43
44
#'   , num_leaves = 63L
#'   , max_depth = -1L
#'   , min_data_in_leaf = 1L
#'   , min_sum_hessian_in_leaf = 1.0
45
#'   , num_threads = 2L
46
#' )
47
#' model <- lgb.train(params, dtrain, 10L)
48
49
#'
#' tree_dt <- lgb.model.dt.tree(model)
50
#' }
51
#' @importFrom data.table := rbindlist
James Lamb's avatar
James Lamb committed
52
#' @importFrom jsonlite fromJSON
53
54
#' @export
lgb.model.dt.tree <- function(model, num_iteration = NULL) {
James Lamb's avatar
James Lamb committed
55

56
  json_model <- lgb.dump(booster = model, num_iteration = num_iteration)
James Lamb's avatar
James Lamb committed
57

58
  parsed_json_model <- jsonlite::fromJSON(
59
    txt = json_model
60
61
62
63
64
    , simplifyVector = TRUE
    , simplifyDataFrame = FALSE
    , simplifyMatrix = FALSE
    , flatten = FALSE
  )
James Lamb's avatar
James Lamb committed
65

66
  # Parse tree model
67
68
69
70
  tree_list <- lapply(
    X = parsed_json_model$tree_info
    , FUN = .single_tree_parse
  )
James Lamb's avatar
James Lamb committed
71

72
  # Combine into single data.table
73
  tree_dt <- data.table::rbindlist(l = tree_list, use.names = TRUE)
James Lamb's avatar
James Lamb committed
74

75
76
77
78
  # Substitute feature index with the actual feature name

  # Since the index comes from C++ (which is 0-indexed), be sure
  # to add 1 (e.g. index 28 means the 29th feature in feature_names)
79
  split_feature_indx <- tree_dt[, split_feature] + 1L
80
81
82
83
84

  # Get corresponding feature names. Positions in split_feature_indx
  # which are NA will result in an NA feature name
  feature_names <- parsed_json_model$feature_names[split_feature_indx]
  tree_dt[, split_feature := feature_names]
James Lamb's avatar
James Lamb committed
85

86
  return(tree_dt)
James Lamb's avatar
James Lamb committed
87

88
89
}

James Lamb's avatar
James Lamb committed
90

91
#' @importFrom data.table := data.table rbindlist
92
.single_tree_parse <- function(lgb_tree) {
James Lamb's avatar
James Lamb committed
93

94
  # Traverse tree function
Yachen Yan's avatar
Yachen Yan committed
95
  pre_order_traversal <- function(env = NULL, tree_node_leaf, current_depth = 0L, parent_index = NA_integer_) {
James Lamb's avatar
James Lamb committed
96

Yachen Yan's avatar
Yachen Yan committed
97
98
99
    if (is.null(env)) {
      # Setup initial default data.table with default types
      env <- new.env(parent = emptyenv())
100
      env$single_tree_dt <- data.table::data.table(
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
        tree_index = integer(0L)
        , depth = integer(0L)
        , split_index = integer(0L)
        , split_feature = integer(0L)
        , node_parent = integer(0L)
        , leaf_index = integer(0L)
        , leaf_parent = integer(0L)
        , split_gain = numeric(0L)
        , threshold = numeric(0L)
        , decision_type = character(0L)
        , default_left = character(0L)
        , internal_value = integer(0L)
        , internal_count = integer(0L)
        , leaf_value = integer(0L)
        , leaf_count = integer(0L)
116
      )
Yachen Yan's avatar
Yachen Yan committed
117
      # start tree traversal
118
119
120
121
122
123
      pre_order_traversal(
        env = env
        , tree_node_leaf = tree_node_leaf
        , current_depth = current_depth
        , parent_index = parent_index
      )
Yachen Yan's avatar
Yachen Yan committed
124
    } else {
James Lamb's avatar
James Lamb committed
125

Yachen Yan's avatar
Yachen Yan committed
126
127
      # Check if split index is not null in leaf
      if (!is.null(tree_node_leaf$split_index)) {
James Lamb's avatar
James Lamb committed
128

Yachen Yan's avatar
Yachen Yan committed
129
130
131
132
133
134
135
        # update data.table
        env$single_tree_dt <- data.table::rbindlist(l = list(env$single_tree_dt,
                                                             c(tree_node_leaf[c("split_index",
                                                                                "split_feature",
                                                                                "split_gain",
                                                                                "threshold",
                                                                                "decision_type",
136
                                                                                "default_left",
Yachen Yan's avatar
Yachen Yan committed
137
138
139
140
141
142
                                                                                "internal_value",
                                                                                "internal_count")],
                                                               "depth" = current_depth,
                                                               "node_parent" = parent_index)),
                                                    use.names = TRUE,
                                                    fill = TRUE)
James Lamb's avatar
James Lamb committed
143

Yachen Yan's avatar
Yachen Yan committed
144
        # Traverse tree again both left and right
145
        pre_order_traversal(
146
147
          env = env
          , tree_node_leaf = tree_node_leaf$left_child
148
149
150
151
          , current_depth = current_depth + 1L
          , parent_index = tree_node_leaf$split_index
        )
        pre_order_traversal(
152
153
          env = env
          , tree_node_leaf = tree_node_leaf$right_child
154
155
156
          , current_depth = current_depth + 1L
          , parent_index = tree_node_leaf$split_index
        )
James Lamb's avatar
James Lamb committed
157

Yachen Yan's avatar
Yachen Yan committed
158
      } else if (!is.null(tree_node_leaf$leaf_index)) {
James Lamb's avatar
James Lamb committed
159

Yachen Yan's avatar
Yachen Yan committed
160
161
162
163
164
165
166
167
168
        # update data.table
        env$single_tree_dt <- data.table::rbindlist(l = list(env$single_tree_dt,
                                                             c(tree_node_leaf[c("leaf_index",
                                                                                "leaf_value",
                                                                                "leaf_count")],
                                                               "depth" = current_depth,
                                                               "leaf_parent" = parent_index)),
                                                    use.names = TRUE,
                                                    fill = TRUE)
James Lamb's avatar
James Lamb committed
169

Yachen Yan's avatar
Yachen Yan committed
170
      }
James Lamb's avatar
James Lamb committed
171

172
    }
Yachen Yan's avatar
Yachen Yan committed
173
    return(env$single_tree_dt)
174
  }
James Lamb's avatar
James Lamb committed
175

176
  # Traverse structure
Yachen Yan's avatar
Yachen Yan committed
177
  single_tree_dt <- pre_order_traversal(tree_node_leaf = lgb_tree$tree_structure)
James Lamb's avatar
James Lamb committed
178

179
  # Store index
180
  single_tree_dt[, tree_index := lgb_tree$tree_index]
James Lamb's avatar
James Lamb committed
181

182
  return(single_tree_dt)
James Lamb's avatar
James Lamb committed
183

184
}