tree.h 8.35 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
#ifndef LIGHTGBM_TREE_H_
#define LIGHTGBM_TREE_H_

#include <LightGBM/meta.h>
#include <LightGBM/dataset.h>

#include <string>
#include <vector>
Guolin Ke's avatar
Guolin Ke committed
9
#include <memory>
Guolin Ke's avatar
Guolin Ke committed
10
11
12

namespace LightGBM {

13
#define kMaxTreeOutput (100)
Guolin Ke's avatar
Guolin Ke committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

/*!
* \brief Tree model
*/
class Tree {
public:
  /*!
  * \brief Constructor
  * \param max_leaves The number of max leaves
  */
  explicit Tree(int max_leaves);

  /*!
  * \brief Construtor, from a string
  * \param str Model string
  */
  explicit Tree(const std::string& str);

  ~Tree();

  /*!
Qiwei Ye's avatar
Qiwei Ye committed
35
36
37
  * \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
38
  * \param bin_type type of this feature, numerical or categorical
Guolin Ke's avatar
Guolin Ke committed
39
40
  * \param threshold Threshold(bin) of split
  * \param real_feature Index of feature, the original index on data
41
  * \param threshold_double Threshold on feature value
Guolin Ke's avatar
Guolin Ke committed
42
43
  * \param left_value Model Left child output
  * \param right_value Model Right child output
Guolin Ke's avatar
Guolin Ke committed
44
45
  * \param left_cnt Count of left child
  * \param right_cnt Count of right child
Guolin Ke's avatar
Guolin Ke committed
46
  * \param gain Split gain
Guolin Ke's avatar
Guolin Ke committed
47
48
49
  * \param zero_bin bin value for value==0 (missing value)
  * \param default_bin default conversion for the missing value, in bin
  * \param default_value default conversion for the missing value, in float value
Guolin Ke's avatar
Guolin Ke committed
50
51
  * \return The index of new leaf.
  */
Guolin Ke's avatar
Guolin Ke committed
52
53
54
55
  int Split(int leaf, int feature, BinType bin_type, uint32_t threshold, int real_feature, 
            double threshold_double, double left_value, double right_value, 
            data_size_t left_cnt, data_size_t right_cnt, double gain,
            uint32_t zero_bin, uint32_t default_bin_for_zero, double default_value);
Guolin Ke's avatar
Guolin Ke committed
56

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

Guolin Ke's avatar
Guolin Ke committed
60
61
62
63
64
  /*! \brief Set the output of one leaf */
  inline void SetLeafOutput(int leaf, double output) {
    leaf_value_[leaf] = output;
  }

Guolin Ke's avatar
Guolin Ke committed
65
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
66
  * \brief Adding prediction value of this tree model to scores
Guolin Ke's avatar
Guolin Ke committed
67
68
69
70
  * \param data The dataset
  * \param num_data Number of total data
  * \param score Will add prediction to score
  */
71
72
73
  void AddPredictionToScore(const Dataset* data,
                            data_size_t num_data,
                            double* score) const;
Guolin Ke's avatar
Guolin Ke committed
74
75

  /*!
Qiwei Ye's avatar
Qiwei Ye committed
76
  * \brief Adding prediction value of this tree model to scorese
Guolin Ke's avatar
Guolin Ke committed
77
78
79
80
81
82
  * \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
83
                            const data_size_t* used_data_indices,
84
                            data_size_t num_data, double* score) const;
Guolin Ke's avatar
Guolin Ke committed
85
86

  /*!
87
  * \brief Prediction on one record
Guolin Ke's avatar
Guolin Ke committed
88
89
90
  * \param feature_values Feature value of this record
  * \return Prediction result
  */
91
92
  inline double Predict(const double* feature_values) const;
  inline int PredictLeafIndex(const double* feature_values) const;
Guolin Ke's avatar
Guolin Ke committed
93
94
95
96

  /*! \brief Get Number of leaves*/
  inline int num_leaves() const { return num_leaves_; }

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

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

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

Guolin Ke's avatar
Guolin Ke committed
105
106
  /*!
  * \brief Shrinkage for the tree's output
Qiwei Ye's avatar
Qiwei Ye committed
107
  *        shrinkage rate (a.k.a learning rate) is used to tune the traning process
Guolin Ke's avatar
Guolin Ke committed
108
109
  * \param rate The factor of shrinkage
  */
110
  inline void Shrinkage(double rate) {
Guolin Ke's avatar
Guolin Ke committed
111
    #pragma omp parallel for schedule(static, 512) if (num_leaves_ >= 1024)
Guolin Ke's avatar
Guolin Ke committed
112
    for (int i = 0; i < num_leaves_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
113
      leaf_value_[i] *= rate;
114
115
      if (leaf_value_[i] > kMaxTreeOutput) { leaf_value_[i] = kMaxTreeOutput; } 
      else if (leaf_value_[i] < -kMaxTreeOutput) { leaf_value_[i] = -kMaxTreeOutput; }
Guolin Ke's avatar
Guolin Ke committed
116
    }
Guolin Ke's avatar
Guolin Ke committed
117
    shrinkage_ *= rate;
Guolin Ke's avatar
Guolin Ke committed
118
119
  }

wxchan's avatar
wxchan committed
120
  /*! \brief Serialize this object to string*/
Guolin Ke's avatar
Guolin Ke committed
121
122
  std::string ToString();

wxchan's avatar
wxchan committed
123
124
125
  /*! \brief Serialize this object to json*/
  std::string ToJSON();

126
127
128
  /*! \brief Serialize this object to if-else statement*/
  std::string ToIfElse(int index, bool is_predict_leaf_index);

129
130
131
132
133
134
135
136
137
  template<typename T>
  static bool CategoricalDecision(T fval, T threshold) {
    if (static_cast<int>(fval) == static_cast<int>(threshold)) {
      return true;
    } else {
      return false;
    }
  }

Guolin Ke's avatar
Guolin Ke committed
138
139
140
141
142
143
144
145
146
  template<typename T>
  static bool NumericalDecision(T fval, T threshold) {
    if (fval <= threshold) {
      return true;
    } else {
      return false;
    }
  }

Guolin Ke's avatar
Guolin Ke committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
  static double DefaultValueForZero(double fval, double zero, double out) {
    if (fval > -zero && fval <= zero) {
      return out;
    } else {
      return fval;
    }
  }

  static uint32_t DefaultValueForZero(uint32_t fval, uint32_t zero, uint32_t out) {
    if (fval == zero) {
      return out;
    } else {
      return fval;
    }
  }


164
165
166
167
168
169
170
  static const char* GetDecisionTypeName(int8_t type) {
    if (type == 0) {
      return "no_greater";
    } else {
      return "is";
    }
  }
Guolin Ke's avatar
Guolin Ke committed
171

172
173
  static std::vector<bool(*)(uint32_t, uint32_t)> inner_decision_funs;
  static std::vector<bool(*)(double, double)> decision_funs;
Guolin Ke's avatar
Guolin Ke committed
174

175
private:
Guolin Ke's avatar
Guolin Ke committed
176
177

  /*!
Qiwei Ye's avatar
Qiwei Ye committed
178
  * \brief Find leaf index of which record belongs by features
Guolin Ke's avatar
Guolin Ke committed
179
180
181
  * \param feature_values Feature value of this record
  * \return Leaf index
  */
182
  inline int GetLeaf(const double* feature_values) const;
Guolin Ke's avatar
Guolin Ke committed
183

wxchan's avatar
wxchan committed
184
185
186
  /*! \brief Serialize one node to json*/
  inline std::string NodeToJSON(int index);

187
188
189
  /*! \brief Serialize one node to if-else statement*/
  inline std::string NodeToIfElse(int index, bool is_predict_leaf_index);

Guolin Ke's avatar
Guolin Ke committed
190
191
192
193
194
195
  /*! \brief Number of max leaves*/
  int max_leaves_;
  /*! \brief Number of current levas*/
  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
196
  std::vector<int> left_child_;
Guolin Ke's avatar
Guolin Ke committed
197
  /*! \brief A non-leaf node's right child */
Guolin Ke's avatar
Guolin Ke committed
198
  std::vector<int> right_child_;
Guolin Ke's avatar
Guolin Ke committed
199
  /*! \brief A non-leaf node's split feature */
Guolin Ke's avatar
Guolin Ke committed
200
  std::vector<int> split_feature_inner_;
Guolin Ke's avatar
Guolin Ke committed
201
  /*! \brief A non-leaf node's split feature, the original index */
Guolin Ke's avatar
Guolin Ke committed
202
  std::vector<int> split_feature_;
Guolin Ke's avatar
Guolin Ke committed
203
  /*! \brief A non-leaf node's split threshold in bin */
Guolin Ke's avatar
Guolin Ke committed
204
  std::vector<uint32_t> threshold_in_bin_;
Guolin Ke's avatar
Guolin Ke committed
205
  /*! \brief A non-leaf node's split threshold in feature value */
Guolin Ke's avatar
Guolin Ke committed
206
  std::vector<double> threshold_;
207
208
  /*! \brief Decision type, 0 for '<='(numerical feature), 1 for 'is'(categorical feature) */
  std::vector<int8_t> decision_type_;
Guolin Ke's avatar
Guolin Ke committed
209
210
211
212
  /*! \brief Default values for the na/0 feature values */
  std::vector<double> default_value_;
  std::vector<uint32_t> zero_bin_;
  std::vector<uint32_t> default_bin_for_zero_;
Guolin Ke's avatar
Guolin Ke committed
213
  /*! \brief A non-leaf node's split gain */
Guolin Ke's avatar
Guolin Ke committed
214
  std::vector<double> split_gain_;
Guolin Ke's avatar
Guolin Ke committed
215
216
  // used for leaf node
  /*! \brief The parent of leaf */
Guolin Ke's avatar
Guolin Ke committed
217
  std::vector<int> leaf_parent_;
Guolin Ke's avatar
Guolin Ke committed
218
  /*! \brief Output of leaves */
Guolin Ke's avatar
Guolin Ke committed
219
  std::vector<double> leaf_value_;
Guolin Ke's avatar
Guolin Ke committed
220
221
222
223
224
225
  /*! \brief DataCount of leaves */
  std::vector<data_size_t> leaf_count_;
  /*! \brief Output of non-leaf nodes */
  std::vector<double> internal_value_;
  /*! \brief DataCount of non-leaf nodes */
  std::vector<data_size_t> internal_count_;
Guolin Ke's avatar
Guolin Ke committed
226
  /*! \brief Depth for leaves */
Guolin Ke's avatar
Guolin Ke committed
227
  std::vector<int> leaf_depth_;
Guolin Ke's avatar
Guolin Ke committed
228
  double shrinkage_;
229
  bool has_categorical_;
Guolin Ke's avatar
Guolin Ke committed
230
231
};

232
inline double Tree::Predict(const double* feature_values) const {
Guolin Ke's avatar
Guolin Ke committed
233
234
235
236
237
238
  if (num_leaves_ > 1) {
    int leaf = GetLeaf(feature_values);
    return LeafOutput(leaf);
  } else {
    return 0.0f;
  }
Guolin Ke's avatar
Guolin Ke committed
239
240
}

241
inline int Tree::PredictLeafIndex(const double* feature_values) const {
Guolin Ke's avatar
Guolin Ke committed
242
243
244
245
246
247
  if (num_leaves_ > 1) {
    int leaf = GetLeaf(feature_values);
    return leaf;
  } else {
    return 0;
  }
wxchan's avatar
wxchan committed
248
249
}

250
inline int Tree::GetLeaf(const double* feature_values) const {
Guolin Ke's avatar
Guolin Ke committed
251
  int node = 0;
Guolin Ke's avatar
Guolin Ke committed
252
253
  if (has_categorical_) {
    while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
254
      double fval = DefaultValueForZero(feature_values[split_feature_[node]], kMissingValueRange, default_value_[node]);
Guolin Ke's avatar
Guolin Ke committed
255
      if (decision_funs[decision_type_[node]](
Guolin Ke's avatar
Guolin Ke committed
256
        fval,
Guolin Ke's avatar
Guolin Ke committed
257
258
259
260
261
262
263
264
        threshold_[node])) {
        node = left_child_[node];
      } else {
        node = right_child_[node];
      }
    }
  } else {
    while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
265
      double fval = DefaultValueForZero(feature_values[split_feature_[node]], kMissingValueRange, default_value_[node]);
Guolin Ke's avatar
Guolin Ke committed
266
      if (NumericalDecision<double>(
Guolin Ke's avatar
Guolin Ke committed
267
        fval,
Guolin Ke's avatar
Guolin Ke committed
268
269
270
271
272
        threshold_[node])) {
        node = left_child_[node];
      } else {
        node = right_child_[node];
      }
Guolin Ke's avatar
Guolin Ke committed
273
274
275
276
277
278
279
    }
  }
  return ~node;
}

}  // namespace LightGBM

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