tree.h 18.7 KB
Newer Older
1
2
3
4
/*!
 * Copyright (c) 2016 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
Guolin Ke's avatar
Guolin Ke committed
5
6
7
8
#ifndef LIGHTGBM_TREE_H_
#define LIGHTGBM_TREE_H_

#include <LightGBM/dataset.h>
9
#include <LightGBM/meta.h>
Guolin Ke's avatar
Guolin Ke committed
10
11

#include <string>
12
#include <map>
13
14
15
#include <memory>
#include <unordered_map>
#include <vector>
Guolin Ke's avatar
Guolin Ke committed
16
17
18

namespace LightGBM {

Guolin Ke's avatar
Guolin Ke committed
19
20
#define kCategoricalMask (1)
#define kDefaultLeftMask (2)
Guolin Ke's avatar
Guolin Ke committed
21
22
23
24
25

/*!
* \brief Tree model
*/
class Tree {
Nikita Titov's avatar
Nikita Titov committed
26
 public:
Guolin Ke's avatar
Guolin Ke committed
27
28
29
30
31
32
33
  /*!
  * \brief Constructor
  * \param max_leaves The number of max leaves
  */
  explicit Tree(int max_leaves);

  /*!
34
  * \brief Constructor, from a string
Guolin Ke's avatar
Guolin Ke committed
35
  * \param str Model string
36
  * \param used_len used count of str
Guolin Ke's avatar
Guolin Ke committed
37
  */
38
  Tree(const char* str, size_t* used_len);
Guolin Ke's avatar
Guolin Ke committed
39
40
41
42

  ~Tree();

  /*!
Qiwei Ye's avatar
Qiwei Ye committed
43
44
45
  * \brief Performing a split on tree leaves.
  * \param leaf Index of leaf to be split
  * \param feature Index of feature; the converted index after removing useless features
Guolin Ke's avatar
Guolin Ke committed
46
  * \param real_feature Index of feature, the original index on data
47
  * \param threshold_bin Threshold(bin) of split
48
  * \param threshold_double Threshold on feature value
Guolin Ke's avatar
Guolin Ke committed
49
50
  * \param left_value Model Left child output
  * \param right_value Model Right child output
Guolin Ke's avatar
Guolin Ke committed
51
52
  * \param left_cnt Count of left child
  * \param right_cnt Count of right child
53
54
  * \param left_weight Weight of left child
  * \param right_weight Weight of right child
Guolin Ke's avatar
Guolin Ke committed
55
  * \param gain Split gain
Guolin Ke's avatar
Guolin Ke committed
56
57
  * \param missing_type missing type
  * \param default_left default direction for missing value
Guolin Ke's avatar
Guolin Ke committed
58
59
  * \return The index of new leaf.
  */
60
61
  int Split(int leaf, int feature, int real_feature, uint32_t threshold_bin,
            double threshold_double, double left_value, double right_value,
62
63
            int left_cnt, int right_cnt, double left_weight, double right_weight,
            float gain, MissingType missing_type, bool default_left);
Guolin Ke's avatar
Guolin Ke committed
64

65
66
67
68
69
70
71
  /*!
  * \brief Performing a split on tree leaves, with categorical feature
  * \param leaf Index of leaf to be split
  * \param feature Index of feature; the converted index after removing useless features
  * \param real_feature Index of feature, the original index on data
  * \param threshold_bin Threshold(bin) of split, use bitset to represent
  * \param num_threshold_bin size of threshold_bin
72
73
  * \param threshold Thresholds of real feature value, use bitset to represent
  * \param num_threshold size of threshold
74
75
76
77
  * \param left_value Model Left child output
  * \param right_value Model Right child output
  * \param left_cnt Count of left child
  * \param right_cnt Count of right child
78
79
  * \param left_weight Weight of left child
  * \param right_weight Weight of right child
80
81
82
  * \param gain Split gain
  * \return The index of new leaf.
  */
83
84
  int SplitCategorical(int leaf, int feature, int real_feature, const uint32_t* threshold_bin, int num_threshold_bin,
                       const uint32_t* threshold, int num_threshold, double left_value, double right_value,
85
                       int left_cnt, int right_cnt, double left_weight, double right_weight, float gain, MissingType missing_type);
86

Guolin Ke's avatar
Guolin Ke committed
87
  /*! \brief Get the output of one leaf */
88
  inline double LeafOutput(int leaf) const { return leaf_value_[leaf]; }
Guolin Ke's avatar
Guolin Ke committed
89

Guolin Ke's avatar
Guolin Ke committed
90
91
  /*! \brief Set the output of one leaf */
  inline void SetLeafOutput(int leaf, double output) {
92
93
94
95
96
97
    // Prevent denormal values because they can cause std::out_of_range exception when converting strings to doubles 
    if (IsZero(output)) {
      leaf_value_[leaf] = 0;
    } else {
      leaf_value_[leaf] = output;
    }
Guolin Ke's avatar
Guolin Ke committed
98
99
  }

Guolin Ke's avatar
Guolin Ke committed
100
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
101
  * \brief Adding prediction value of this tree model to scores
Guolin Ke's avatar
Guolin Ke committed
102
103
104
105
  * \param data The dataset
  * \param num_data Number of total data
  * \param score Will add prediction to score
  */
106
107
108
  void AddPredictionToScore(const Dataset* data,
                            data_size_t num_data,
                            double* score) const;
Guolin Ke's avatar
Guolin Ke committed
109
110

  /*!
111
  * \brief Adding prediction value of this tree model to scores
Guolin Ke's avatar
Guolin Ke committed
112
113
114
115
116
117
  * \param data The dataset
  * \param used_data_indices Indices of used data
  * \param num_data Number of total data
  * \param score Will add prediction to score
  */
  void AddPredictionToScore(const Dataset* data,
Qiwei Ye's avatar
Qiwei Ye committed
118
                            const data_size_t* used_data_indices,
119
                            data_size_t num_data, double* score) const;
Guolin Ke's avatar
Guolin Ke committed
120
121

  /*!
122
  * \brief Prediction on one record
Guolin Ke's avatar
Guolin Ke committed
123
124
125
  * \param feature_values Feature value of this record
  * \return Prediction result
  */
126
  inline double Predict(const double* feature_values) const;
127
  inline double PredictByMap(const std::unordered_map<int, double>& feature_values) const;
128

129
  inline int PredictLeafIndex(const double* feature_values) const;
130
131
  inline int PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const;

Guolin Ke's avatar
Guolin Ke committed
132

133
  inline void PredictContrib(const double* feature_values, int num_features, double* output);
134

Guolin Ke's avatar
Guolin Ke committed
135
136
137
  /*! \brief Get Number of leaves*/
  inline int num_leaves() const { return num_leaves_; }

Guolin Ke's avatar
Guolin Ke committed
138
139
140
  /*! \brief Get depth of specific leaf*/
  inline int leaf_depth(int leaf_idx) const { return leaf_depth_[leaf_idx]; }

wxchan's avatar
wxchan committed
141
  /*! \brief Get feature of specific split*/
Guolin Ke's avatar
Guolin Ke committed
142
  inline int split_feature(int split_idx) const { return split_feature_[split_idx]; }
wxchan's avatar
wxchan committed
143

Guolin Ke's avatar
Guolin Ke committed
144
145
  inline double split_gain(int split_idx) const { return split_gain_[split_idx]; }

146
  /*! \brief Get the number of data points that fall at or below this node*/
Guolin Ke's avatar
Guolin Ke committed
147
  inline int data_count(int node) const { return node >= 0 ? internal_count_[node] : leaf_count_[~node]; }
148

Guolin Ke's avatar
Guolin Ke committed
149
150
  /*!
  * \brief Shrinkage for the tree's output
151
  *        shrinkage rate (a.k.a learning rate) is used to tune the training process
Guolin Ke's avatar
Guolin Ke committed
152
153
  * \param rate The factor of shrinkage
  */
154
  inline void Shrinkage(double rate) {
155
    #pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
Guolin Ke's avatar
Guolin Ke committed
156
    for (int i = 0; i < num_leaves_; ++i) {
157
158
159
160
161
162
163
      double new_leaf_value = leaf_value_[i] * rate;
      // Prevent denormal values because they can cause std::out_of_range exception when converting strings to doubles 
      if (IsZero(new_leaf_value)) {
        leaf_value_[i] = 0;
      } else {
        leaf_value_[i] = new_leaf_value;
      }
Guolin Ke's avatar
Guolin Ke committed
164
    }
Guolin Ke's avatar
Guolin Ke committed
165
    shrinkage_ *= rate;
Guolin Ke's avatar
Guolin Ke committed
166
167
  }

168
169
170
171
  inline double shrinkage() const {
    return shrinkage_;
  }

Guolin Ke's avatar
Guolin Ke committed
172
173
174
  inline void AddBias(double val) {
    #pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
    for (int i = 0; i < num_leaves_; ++i) {
175
176
177
178
179
180
181
      double new_leaf_value = val + leaf_value_[i];
      // Prevent denormal values because they can cause std::out_of_range exception when converting strings to doubles 
      if (IsZero(new_leaf_value)) {
        leaf_value_[i] = 0;
      } else {
        leaf_value_[i] = new_leaf_value;
      }
Guolin Ke's avatar
Guolin Ke committed
182
183
184
185
186
    }
    // force to 1.0
    shrinkage_ = 1.0f;
  }

187
188
189
190
191
192
  inline void AsConstantTree(double val) {
    num_leaves_ = 1;
    shrinkage_ = 1.0f;
    leaf_value_[0] = val;
  }

wxchan's avatar
wxchan committed
193
  /*! \brief Serialize this object to string*/
Guolin Ke's avatar
Guolin Ke committed
194
  std::string ToString() const;
Guolin Ke's avatar
Guolin Ke committed
195

wxchan's avatar
wxchan committed
196
  /*! \brief Serialize this object to json*/
Guolin Ke's avatar
Guolin Ke committed
197
  std::string ToJSON() const;
wxchan's avatar
wxchan committed
198

199
  /*! \brief Serialize this object to if-else statement*/
Guolin Ke's avatar
Guolin Ke committed
200
  std::string ToIfElse(int index, bool predict_leaf_index) const;
201

Guolin Ke's avatar
Guolin Ke committed
202
  inline static bool IsZero(double fval) {
Guolin Ke's avatar
Guolin Ke committed
203
    if (fval > -kZeroThreshold && fval <= kZeroThreshold) {
Guolin Ke's avatar
Guolin Ke committed
204
      return true;
Guolin Ke's avatar
Guolin Ke committed
205
    } else {
Guolin Ke's avatar
Guolin Ke committed
206
      return false;
Guolin Ke's avatar
Guolin Ke committed
207
208
209
    }
  }

Guolin Ke's avatar
Guolin Ke committed
210
211
212
213
214
215
216
  inline static bool GetDecisionType(int8_t decision_type, int8_t mask) {
    return (decision_type & mask) > 0;
  }

  inline static void SetDecisionType(int8_t* decision_type, bool input, int8_t mask) {
    if (input) {
      (*decision_type) |= mask;
Guolin Ke's avatar
Guolin Ke committed
217
    } else {
Guolin Ke's avatar
Guolin Ke committed
218
      (*decision_type) &= (127 - mask);
Guolin Ke's avatar
Guolin Ke committed
219
220
221
    }
  }

Guolin Ke's avatar
Guolin Ke committed
222
223
224
225
226
227
228
229
230
  inline static int8_t GetMissingType(int8_t decision_type) {
    return (decision_type >> 2) & 3;
  }

  inline static void SetMissingType(int8_t* decision_type, int8_t input) {
    (*decision_type) &= 3;
    (*decision_type) |= (input << 2);
  }

231
232
  void RecomputeMaxDepth();

233
  int NextLeafId() const { return num_leaves_; }
Nikita Titov's avatar
Nikita Titov committed
234
 private:
Guolin Ke's avatar
Guolin Ke committed
235
  std::string NumericalDecisionIfElse(int node) const;
Guolin Ke's avatar
Guolin Ke committed
236

Guolin Ke's avatar
Guolin Ke committed
237
  std::string CategoricalDecisionIfElse(int node) const;
238
239
240

  inline int NumericalDecision(double fval, int node) const {
    uint8_t missing_type = GetMissingType(decision_type_[node]);
Guolin Ke's avatar
Guolin Ke committed
241
242
243
244
245
246
247
    if (std::isnan(fval)) {
      if (missing_type != 2) {
        fval = 0.0f;
      }
    }
    if ((missing_type == 1 && IsZero(fval))
        || (missing_type == 2 && std::isnan(fval))) {
248
249
      if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
        return left_child_[node];
Guolin Ke's avatar
Guolin Ke committed
250
      } else {
251
        return right_child_[node];
Guolin Ke's avatar
Guolin Ke committed
252
253
      }
    }
254
255
256
257
258
    if (fval <= threshold_[node]) {
      return left_child_[node];
    } else {
      return right_child_[node];
    }
Guolin Ke's avatar
Guolin Ke committed
259
  }
Guolin Ke's avatar
Guolin Ke committed
260

261
262
263
264
265
266
267
268
269
270
271
272
  inline int NumericalDecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
    uint8_t missing_type = GetMissingType(decision_type_[node]);
    if ((missing_type == 1 && fval == default_bin)
        || (missing_type == 2 && fval == max_bin)) {
      if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
        return left_child_[node];
      } else {
        return right_child_[node];
      }
    }
    if (fval <= threshold_in_bin_[node]) {
      return left_child_[node];
273
    } else {
274
      return right_child_[node];
275
276
    }
  }
Guolin Ke's avatar
Guolin Ke committed
277

278
279
280
281
282
283
284
285
286
287
288
289
  inline int CategoricalDecision(double fval, int node) const {
    uint8_t missing_type = GetMissingType(decision_type_[node]);
    int int_fval = static_cast<int>(fval);
    if (int_fval < 0) {
      return right_child_[node];;
    } else if (std::isnan(fval)) {
      // NaN is always in the right
      if (missing_type == 2) {
        return right_child_[node];
      }
      int_fval = 0;
    }
290
    int cat_idx = static_cast<int>(threshold_[node]);
291
292
    if (Common::FindInBitset(cat_threshold_.data() + cat_boundaries_[cat_idx],
                             cat_boundaries_[cat_idx + 1] - cat_boundaries_[cat_idx], int_fval)) {
293
294
295
296
      return left_child_[node];
    }
    return right_child_[node];
  }
Guolin Ke's avatar
Guolin Ke committed
297

298
  inline int CategoricalDecisionInner(uint32_t fval, int node) const {
299
    int cat_idx = static_cast<int>(threshold_in_bin_[node]);
300
301
    if (Common::FindInBitset(cat_threshold_inner_.data() + cat_boundaries_inner_[cat_idx],
                             cat_boundaries_inner_[cat_idx + 1] - cat_boundaries_inner_[cat_idx], fval)) {
302
303
304
305
      return left_child_[node];
    }
    return right_child_[node];
  }
Guolin Ke's avatar
Guolin Ke committed
306

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
  inline int Decision(double fval, int node) const {
    if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
      return CategoricalDecision(fval, node);
    } else {
      return NumericalDecision(fval, node);
    }
  }

  inline int DecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
    if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
      return CategoricalDecisionInner(fval, node);
    } else {
      return NumericalDecisionInner(fval, node, default_bin, max_bin);
    }
  }

323
324
  inline void Split(int leaf, int feature, int real_feature, double left_value, double right_value, int left_cnt, int right_cnt,
                    double left_weight, double right_weight, float gain);
Guolin Ke's avatar
Guolin Ke committed
325
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
326
  * \brief Find leaf index of which record belongs by features
Guolin Ke's avatar
Guolin Ke committed
327
328
329
  * \param feature_values Feature value of this record
  * \return Leaf index
  */
330
  inline int GetLeaf(const double* feature_values) const;
331
  inline int GetLeafByMap(const std::unordered_map<int, double>& feature_values) const;
Guolin Ke's avatar
Guolin Ke committed
332

wxchan's avatar
wxchan committed
333
  /*! \brief Serialize one node to json*/
Guolin Ke's avatar
Guolin Ke committed
334
  std::string NodeToJSON(int index) const;
wxchan's avatar
wxchan committed
335

336
  /*! \brief Serialize one node to if-else statement*/
Guolin Ke's avatar
Guolin Ke committed
337
  std::string NodeToIfElse(int index, bool predict_leaf_index) const;
Guolin Ke's avatar
Guolin Ke committed
338

Guolin Ke's avatar
Guolin Ke committed
339
  std::string NodeToIfElseByMap(int index, bool predict_leaf_index) const;
340

341
  double ExpectedValue() const;
Guolin Ke's avatar
Guolin Ke committed
342

343
344
  /*! \brief This is used fill in leaf_depth_ after reloading a model*/
  inline void RecomputeLeafDepths(int node = 0, int depth = 0);
Guolin Ke's avatar
Guolin Ke committed
345
346
347
348
349
350
351
352
353
354

  /*!
  * \brief Used by TreeSHAP for data we keep about our decision path
  */
  struct PathElement {
    int feature_index;
    double zero_fraction;
    double one_fraction;

    // note that pweight is included for convenience and is not tied with the other attributes,
355
    // the pweight of the i'th path element is the permutation weight of paths with i-1 ones in them
Guolin Ke's avatar
Guolin Ke committed
356
357
358
359
360
361
    double pweight;

    PathElement() {}
    PathElement(int i, double z, double o, double w) : feature_index(i), zero_fraction(z), one_fraction(o), pweight(w) {}
  };

362
  /*! \brief Polynomial time algorithm for SHAP values (arXiv:1706.06060)*/
Guolin Ke's avatar
Guolin Ke committed
363
364
365
366
  void TreeSHAP(const double *feature_values, double *phi,
                int node, int unique_depth,
                PathElement *parent_unique_path, double parent_zero_fraction,
                double parent_one_fraction, int parent_feature_index) const;
367

368
  /*! \brief Extend our decision path with a fraction of one and zero extensions for TreeSHAP*/
Guolin Ke's avatar
Guolin Ke committed
369
370
  static void ExtendPath(PathElement *unique_path, int unique_depth,
                         double zero_fraction, double one_fraction, int feature_index);
371
372

  /*! \brief Undo a previous extension of the decision path for TreeSHAP*/
Guolin Ke's avatar
Guolin Ke committed
373
  static void UnwindPath(PathElement *unique_path, int unique_depth, int path_index);
374

375
  /*! determine what the total permutation weight would be if we unwound a previous extension in the decision path*/
Guolin Ke's avatar
Guolin Ke committed
376
  static double UnwoundPathSum(const PathElement *unique_path, int unique_depth, int path_index);
377

Guolin Ke's avatar
Guolin Ke committed
378
379
  /*! \brief Number of max leaves*/
  int max_leaves_;
380
  /*! \brief Number of current leaves*/
Guolin Ke's avatar
Guolin Ke committed
381
382
383
  int num_leaves_;
  // following values used for non-leaf node
  /*! \brief A non-leaf node's left child */
Guolin Ke's avatar
Guolin Ke committed
384
  std::vector<int> left_child_;
Guolin Ke's avatar
Guolin Ke committed
385
  /*! \brief A non-leaf node's right child */
Guolin Ke's avatar
Guolin Ke committed
386
  std::vector<int> right_child_;
Guolin Ke's avatar
Guolin Ke committed
387
  /*! \brief A non-leaf node's split feature */
Guolin Ke's avatar
Guolin Ke committed
388
  std::vector<int> split_feature_inner_;
Guolin Ke's avatar
Guolin Ke committed
389
  /*! \brief A non-leaf node's split feature, the original index */
Guolin Ke's avatar
Guolin Ke committed
390
  std::vector<int> split_feature_;
Guolin Ke's avatar
Guolin Ke committed
391
  /*! \brief A non-leaf node's split threshold in bin */
Guolin Ke's avatar
Guolin Ke committed
392
  std::vector<uint32_t> threshold_in_bin_;
Guolin Ke's avatar
Guolin Ke committed
393
  /*! \brief A non-leaf node's split threshold in feature value */
Guolin Ke's avatar
Guolin Ke committed
394
  std::vector<double> threshold_;
395
  int num_cat_;
396
397
398
399
  std::vector<int> cat_boundaries_inner_;
  std::vector<uint32_t> cat_threshold_inner_;
  std::vector<int> cat_boundaries_;
  std::vector<uint32_t> cat_threshold_;
400
  /*! \brief Store the information for categorical feature handle and missing value handle. */
401
  std::vector<int8_t> decision_type_;
Guolin Ke's avatar
Guolin Ke committed
402
  /*! \brief A non-leaf node's split gain */
403
  std::vector<float> split_gain_;
Guolin Ke's avatar
Guolin Ke committed
404
405
  // used for leaf node
  /*! \brief The parent of leaf */
Guolin Ke's avatar
Guolin Ke committed
406
  std::vector<int> leaf_parent_;
Guolin Ke's avatar
Guolin Ke committed
407
  /*! \brief Output of leaves */
Guolin Ke's avatar
Guolin Ke committed
408
  std::vector<double> leaf_value_;
409
410
  /*! \brief weight of leaves */
  std::vector<double> leaf_weight_;
Guolin Ke's avatar
Guolin Ke committed
411
  /*! \brief DataCount of leaves */
412
  std::vector<int> leaf_count_;
Guolin Ke's avatar
Guolin Ke committed
413
414
  /*! \brief Output of non-leaf nodes */
  std::vector<double> internal_value_;
415
416
  /*! \brief weight of non-leaf nodes */
  std::vector<double> internal_weight_;
Guolin Ke's avatar
Guolin Ke committed
417
  /*! \brief DataCount of non-leaf nodes */
418
  std::vector<int> internal_count_;
Guolin Ke's avatar
Guolin Ke committed
419
  /*! \brief Depth for leaves */
Guolin Ke's avatar
Guolin Ke committed
420
  std::vector<int> leaf_depth_;
Guolin Ke's avatar
Guolin Ke committed
421
  double shrinkage_;
422
  int max_depth_;
Guolin Ke's avatar
Guolin Ke committed
423
424
};

425
inline void Tree::Split(int leaf, int feature, int real_feature,
426
                        double left_value, double right_value, int left_cnt, int right_cnt,
427
                        double left_weight, double right_weight, float gain) {
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
  int new_node_idx = num_leaves_ - 1;
  // update parent info
  int parent = leaf_parent_[leaf];
  if (parent >= 0) {
    // if cur node is left child
    if (left_child_[parent] == ~leaf) {
      left_child_[parent] = new_node_idx;
    } else {
      right_child_[parent] = new_node_idx;
    }
  }
  // add new node
  split_feature_inner_[new_node_idx] = feature;
  split_feature_[new_node_idx] = real_feature;

Guolin Ke's avatar
Guolin Ke committed
443
  split_gain_[new_node_idx] = gain;
444
445
446
447
448
449
450
  // add two new leaves
  left_child_[new_node_idx] = ~leaf;
  right_child_[new_node_idx] = ~num_leaves_;
  // update new leaves
  leaf_parent_[leaf] = new_node_idx;
  leaf_parent_[num_leaves_] = new_node_idx;
  // save current leaf value to internal node before change
451
  internal_weight_[new_node_idx] = leaf_weight_[leaf];
452
453
454
  internal_value_[new_node_idx] = leaf_value_[leaf];
  internal_count_[new_node_idx] = left_cnt + right_cnt;
  leaf_value_[leaf] = std::isnan(left_value) ? 0.0f : left_value;
455
  leaf_weight_[leaf] = left_weight;
456
457
  leaf_count_[leaf] = left_cnt;
  leaf_value_[num_leaves_] = std::isnan(right_value) ? 0.0f : right_value;
458
  leaf_weight_[num_leaves_] = right_weight;
459
460
461
462
463
464
  leaf_count_[num_leaves_] = right_cnt;
  // update leaf depth
  leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1;
  leaf_depth_[leaf]++;
}

465
inline double Tree::Predict(const double* feature_values) const {
Guolin Ke's avatar
Guolin Ke committed
466
467
468
469
  if (num_leaves_ > 1) {
    int leaf = GetLeaf(feature_values);
    return LeafOutput(leaf);
  } else {
470
    return leaf_value_[0];
Guolin Ke's avatar
Guolin Ke committed
471
  }
Guolin Ke's avatar
Guolin Ke committed
472
473
}

474
475
476
477
478
479
480
481
482
inline double Tree::PredictByMap(const std::unordered_map<int, double>& feature_values) const {
  if (num_leaves_ > 1) {
    int leaf = GetLeafByMap(feature_values);
    return LeafOutput(leaf);
  } else {
    return leaf_value_[0];
  }
}

483
inline int Tree::PredictLeafIndex(const double* feature_values) const {
Guolin Ke's avatar
Guolin Ke committed
484
485
486
487
488
489
  if (num_leaves_ > 1) {
    int leaf = GetLeaf(feature_values);
    return leaf;
  } else {
    return 0;
  }
wxchan's avatar
wxchan committed
490
491
}

492
493
494
495
496
497
498
499
500
inline int Tree::PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const {
  if (num_leaves_ > 1) {
    int leaf = GetLeafByMap(feature_values);
    return leaf;
  } else {
    return 0;
  }
}

501
502
inline void Tree::PredictContrib(const double* feature_values, int num_features, double* output) {
  output[num_features] += ExpectedValue();
503
  // Run the recursion with preallocated space for the unique path data
504
  if (num_leaves_ > 1) {
505
506
507
508
    CHECK(max_depth_ >= 0);
    const int max_path_len = max_depth_ + 1;
    std::vector<PathElement> unique_path_data(max_path_len*(max_path_len + 1) / 2);
    TreeSHAP(feature_values, output, 0, 0, unique_path_data.data(), 1, 1, -1);
509
510
511
512
513
514
515
516
  }
}

inline void Tree::RecomputeLeafDepths(int node, int depth) {
  if (node == 0) leaf_depth_.resize(num_leaves());
  if (node < 0) {
    leaf_depth_[~node] = depth;
  } else {
Guolin Ke's avatar
Guolin Ke committed
517
518
    RecomputeLeafDepths(left_child_[node], depth + 1);
    RecomputeLeafDepths(right_child_[node], depth + 1);
519
  }
520
521
}

522
inline int Tree::GetLeaf(const double* feature_values) const {
Guolin Ke's avatar
Guolin Ke committed
523
  int node = 0;
524
  if (num_cat_ > 0) {
Guolin Ke's avatar
Guolin Ke committed
525
    while (node >= 0) {
526
      node = Decision(feature_values[split_feature_[node]], node);
Guolin Ke's avatar
Guolin Ke committed
527
528
529
    }
  } else {
    while (node >= 0) {
530
      node = NumericalDecision(feature_values[split_feature_[node]], node);
Guolin Ke's avatar
Guolin Ke committed
531
532
533
534
535
    }
  }
  return ~node;
}

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
inline int Tree::GetLeafByMap(const std::unordered_map<int, double>& feature_values) const {
  int node = 0;
  if (num_cat_ > 0) {
    while (node >= 0) {
      node = Decision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
    }
  } else {
    while (node >= 0) {
      node = NumericalDecision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
    }
  }
  return ~node;
}


Guolin Ke's avatar
Guolin Ke committed
551
552
}  // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
553
#endif   // LightGBM_TREE_H_