feature_histogram.hpp 12.6 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef LIGHTGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_
#define LIGHTGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_

#include "split_info.hpp"
#include <LightGBM/feature.h>

#include <cstring>

namespace LightGBM {

/*!
* \brief FeatureHistogram is used to construct and store a histogram for a feature.
*/
class FeatureHistogram {
public:
Guolin Ke's avatar
Guolin Ke committed
16
  FeatureHistogram() {
Guolin Ke's avatar
Guolin Ke committed
17
18
19
20
  }
  ~FeatureHistogram() {
  }

Guolin Ke's avatar
Guolin Ke committed
21
22
23
24
25
  /*! \brief Disable copy */
  FeatureHistogram& operator=(const FeatureHistogram&) = delete;
  /*! \brief Disable copy */
  FeatureHistogram(const FeatureHistogram&) = delete;

Guolin Ke's avatar
Guolin Ke committed
26
27
28
29
30
31
  /*!
  * \brief Init the feature histogram
  * \param feature the feature data for this histogram
  * \param min_num_data_one_leaf minimal number of data in one leaf
  */
  void Init(const Feature* feature, int feature_idx, data_size_t min_num_data_one_leaf,
32
    double min_sum_hessian_one_leaf, double lambda_l1, double lambda_l2, double min_gain_to_split) {
Guolin Ke's avatar
Guolin Ke committed
33
34
35
    feature_idx_ = feature_idx;
    min_num_data_one_leaf_ = min_num_data_one_leaf;
    min_sum_hessian_one_leaf_ = min_sum_hessian_one_leaf;
36
37
38
    lambda_l1_ = lambda_l1;
    lambda_l2_ = lambda_l2;
    min_gain_to_split_ = min_gain_to_split;
Guolin Ke's avatar
Guolin Ke committed
39
40
    bin_data_ = feature->bin_data();
    num_bins_ = feature->num_bin();
Guolin Ke's avatar
Guolin Ke committed
41
    data_.resize(num_bins_);
Guolin Ke's avatar
Guolin Ke committed
42
43
44
45
46
47
48
  }


  /*!
  * \brief Construct a histogram
  * \param num_data number of data in current leaf
  * \param sum_gradients sum of gradients of current leaf
Hui Xue's avatar
Hui Xue committed
49
  * \param sum_hessians sum of hessians of current leaf
Guolin Ke's avatar
Guolin Ke committed
50
51
52
53
  * \param ordered_gradients Orederd gradients
  * \param ordered_hessians  Ordered hessians
  * \param data_indices data indices of current leaf
  */
Guolin Ke's avatar
Guolin Ke committed
54
  void Construct(const data_size_t* data_indices, data_size_t num_data, double sum_gradients,
Guolin Ke's avatar
Guolin Ke committed
55
    double sum_hessians, const score_t* ordered_gradients, const score_t* ordered_hessians) {
Guolin Ke's avatar
Guolin Ke committed
56
    std::memset(data_.data(), 0, sizeof(HistogramBinEntry)* num_bins_);
Guolin Ke's avatar
Guolin Ke committed
57
58
59
    num_data_ = num_data;
    sum_gradients_ = sum_gradients;
    sum_hessians_ = sum_hessians + 2 * kEpsilon;
Guolin Ke's avatar
Guolin Ke committed
60
    bin_data_->ConstructHistogram(data_indices, num_data, ordered_gradients, ordered_hessians, data_.data());
Guolin Ke's avatar
Guolin Ke committed
61
62
63
64
65
66
67
  }

  /*!
  * \brief Construct a histogram by ordered bin
  * \param leaf current leaf
  * \param num_data number of data in current leaf
  * \param sum_gradients sum of gradients of current leaf
Hui Xue's avatar
Hui Xue committed
68
  * \param sum_hessians sum of hessians of current leaf
Guolin Ke's avatar
Guolin Ke committed
69
70
71
  * \param gradients
  * \param hessian
  */
Guolin Ke's avatar
Guolin Ke committed
72
73
  void Construct(const OrderedBin* ordered_bin, int leaf, data_size_t num_data, double sum_gradients,
    double sum_hessians, const score_t* gradients, const score_t* hessians) {
Guolin Ke's avatar
Guolin Ke committed
74
    std::memset(data_.data(), 0, sizeof(HistogramBinEntry)* num_bins_);
Guolin Ke's avatar
Guolin Ke committed
75
76
77
    num_data_ = num_data;
    sum_gradients_ = sum_gradients;
    sum_hessians_ = sum_hessians + 2 * kEpsilon;
Guolin Ke's avatar
Guolin Ke committed
78
    ordered_bin->ConstructHistogram(leaf, gradients, hessians, data_.data());
Guolin Ke's avatar
Guolin Ke committed
79
80
81
82
83
84
  }

  /*!
  * \brief Set sumup information for current histogram
  * \param num_data number of data in current leaf
  * \param sum_gradients sum of gradients of current leaf
Hui Xue's avatar
Hui Xue committed
85
  * \param sum_hessians sum of hessians of current leaf
Guolin Ke's avatar
Guolin Ke committed
86
  */
Guolin Ke's avatar
Guolin Ke committed
87
  void SetSumup(data_size_t num_data, double sum_gradients, double sum_hessians) {
Guolin Ke's avatar
Guolin Ke committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    num_data_ = num_data;
    sum_gradients_ = sum_gradients;
    sum_hessians_ = sum_hessians + 2 * kEpsilon;
  }

  /*!
  * \brief Subtract current histograms with other
  * \param other The histogram that want to subtract
  */
  void Subtract(const FeatureHistogram& other) {
    num_data_ -= other.num_data_;
    sum_gradients_ -= other.sum_gradients_;
    sum_hessians_ -= other.sum_hessians_;
    for (unsigned int i = 0; i < num_bins_; ++i) {
      data_[i].cnt -= other.data_[i].cnt;
      data_[i].sum_gradients -= other.data_[i].sum_gradients;
      data_[i].sum_hessians -= other.data_[i].sum_hessians;
    }
  }

  /*!
  * \brief Find best threshold for this histogram
  * \param output The best split result
  */
  void FindBestThreshold(SplitInfo* output) {
Guolin Ke's avatar
Guolin Ke committed
113
114
115
    double best_sum_left_gradient = NAN;
    double best_sum_left_hessian = NAN;
    double best_gain = kMinScore;
Guolin Ke's avatar
Guolin Ke committed
116
117
    data_size_t best_left_count = 0;
    unsigned int best_threshold = static_cast<unsigned int>(num_bins_);
Guolin Ke's avatar
Guolin Ke committed
118
119
    double sum_right_gradient = 0.0f;
    double sum_right_hessian = kEpsilon;
Guolin Ke's avatar
Guolin Ke committed
120
    data_size_t right_count = 0;
Guolin Ke's avatar
Guolin Ke committed
121
    double gain_shift = GetLeafSplitGain(sum_gradients_, sum_hessians_);
122
    double min_gain_shift = gain_shift + min_gain_to_split_;
Guolin Ke's avatar
Guolin Ke committed
123
124
125
126
127
128
129
130
131
132
133
134
    is_splittable_ = false;
    // from right to left, and we don't need data in bin0
    for (unsigned int t = num_bins_ - 1; t > 0; --t) {
      sum_right_gradient += data_[t].sum_gradients;
      sum_right_hessian += data_[t].sum_hessians;
      right_count += data_[t].cnt;
      // if data not enough, or sum hessian too small
      if (right_count < min_num_data_one_leaf_ || sum_right_hessian < min_sum_hessian_one_leaf_) continue;
      data_size_t left_count = num_data_ - right_count;
      // if data not enough
      if (left_count < min_num_data_one_leaf_) break;

Guolin Ke's avatar
Guolin Ke committed
135
      double sum_left_hessian = sum_hessians_ - sum_right_hessian;
Guolin Ke's avatar
Guolin Ke committed
136
      // if sum hessian too small
137
138
      if (sum_left_hessian < min_sum_hessian_one_leaf_) break;

Guolin Ke's avatar
Guolin Ke committed
139
      double sum_left_gradient = sum_gradients_ - sum_right_gradient;
Guolin Ke's avatar
Guolin Ke committed
140
      // current split gain
Guolin Ke's avatar
Guolin Ke committed
141
      double current_gain = GetLeafSplitGain(sum_left_gradient, sum_left_hessian) + GetLeafSplitGain(sum_right_gradient, sum_right_hessian);
142
143
144
      // gain with split is worse than without split
      if (current_gain < min_gain_shift) continue;

Guolin Ke's avatar
Guolin Ke committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
      // mark to is splittable
      is_splittable_ = true;
      // better split point
      if (current_gain > best_gain) {
        best_left_count = left_count;
        best_sum_left_gradient = sum_left_gradient;
        best_sum_left_hessian = sum_left_hessian;
        // left is <= threshold, right is > threshold.  so this is t-1
        best_threshold = t - 1;
        best_gain = current_gain;
      }
    }
    // update split information
    output->feature = feature_idx_;
    output->threshold = best_threshold;
    output->left_output = CalculateSplittedLeafOutput(best_sum_left_gradient, best_sum_left_hessian);
    output->left_count = best_left_count;
    output->left_sum_gradient = best_sum_left_gradient;
    output->left_sum_hessian = best_sum_left_hessian;
    output->right_output = CalculateSplittedLeafOutput(sum_gradients_ - best_sum_left_gradient,
      sum_hessians_ - best_sum_left_hessian);
    output->right_count = num_data_ - best_left_count;
    output->right_sum_gradient = sum_gradients_ - best_sum_left_gradient;
    output->right_sum_hessian = sum_hessians_ - best_sum_left_hessian;
    output->gain = best_gain - gain_shift;
  }

  /*!
  * \brief Binary size of this histogram
  */
  int SizeOfHistgram() const {
    return num_bins_ * sizeof(HistogramBinEntry);
  }

  /*!
  * \brief Memory pointer to histogram data
  */
  const HistogramBinEntry* HistogramData() const {
Guolin Ke's avatar
Guolin Ke committed
183
    return data_.data();
Guolin Ke's avatar
Guolin Ke committed
184
185
186
187
188
189
  }

  /*!
  * \brief Restore histogram from memory
  */
  void FromMemory(char* memory_data)  {
Guolin Ke's avatar
Guolin Ke committed
190
    std::memcpy(data_.data(), memory_data, num_bins_ * sizeof(HistogramBinEntry));
Guolin Ke's avatar
Guolin Ke committed
191
192
193
194
195
196
197
198
199
200
201
202
  }

  /*!
  * \brief Set min number data in one leaf
  */
  void SetMinNumDataOneLeaf(data_size_t new_val) {
    min_num_data_one_leaf_ = new_val;
  }

  /*!
  * \brief Set min sum hessian in one leaf
  */
Guolin Ke's avatar
Guolin Ke committed
203
  void SetMinSumHessianOneLeaf(double new_val) {
Guolin Ke's avatar
Guolin Ke committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    min_sum_hessian_one_leaf_ = new_val;
  }

  /*!
  * \brief True if this histogram can be splitted
  */
  bool is_splittable() { return is_splittable_; }

  /*!
  * \brief Set splittable to this histogram
  */
  void set_is_splittable(bool val) { is_splittable_ = val; }

private:
  /*!
219
  * \brief Calculate the split gain based on regularized sum_gradients and sum_hessians
Guolin Ke's avatar
Guolin Ke committed
220
221
222
223
  * \param sum_gradients
  * \param sum_hessians
  * \return split gain
  */
Guolin Ke's avatar
Guolin Ke committed
224
  double GetLeafSplitGain(double sum_gradients, double sum_hessians) const {
225
226
227
228
229
230
    double abs_sum_gradients = std::fabs(sum_gradients);
    if (abs_sum_gradients > lambda_l1_) {
      double reg_abs_sum_gradients = abs_sum_gradients - lambda_l1_;
      return (reg_abs_sum_gradients * reg_abs_sum_gradients) / (sum_hessians + lambda_l2_);
    }
    return 0.0f;
Guolin Ke's avatar
Guolin Ke committed
231
232
233
  }

  /*!
234
  * \brief Calculate the output of a leaf based on regularized sum_gradients and sum_hessians
Guolin Ke's avatar
Guolin Ke committed
235
236
237
238
  * \param sum_gradients
  * \param sum_hessians
  * \return leaf output
  */
Guolin Ke's avatar
Guolin Ke committed
239
  double CalculateSplittedLeafOutput(double sum_gradients, double sum_hessians) const {
240
241
242
243
244
    double abs_sum_gradients = std::fabs(sum_gradients);
    if (abs_sum_gradients > lambda_l1_) {
      return -std::copysign(abs_sum_gradients - lambda_l1_, sum_gradients) / (sum_hessians + lambda_l2_);
    }
    return 0.0f;
Guolin Ke's avatar
Guolin Ke committed
245
246
247
248
249
250
  }

  int feature_idx_;
  /*! \brief minimal number of data in one leaf */
  data_size_t min_num_data_one_leaf_;
  /*! \brief minimal sum hessian of data in one leaf */
Guolin Ke's avatar
Guolin Ke committed
251
  double min_sum_hessian_one_leaf_;
252
253
254
255
256
257
  /*! \brief lambda of the L1 weights regularization */
  double lambda_l1_;
  /*! \brief lambda of the L2 weights regularization */
  double lambda_l2_;
  /*! \brief minimal gain (loss reduction) to split */
  double min_gain_to_split_;
Guolin Ke's avatar
Guolin Ke committed
258
259
260
261
262
  /*! \brief the bin data of current feature */
  const Bin* bin_data_;
  /*! \brief number of bin of histogram */
  unsigned int num_bins_;
  /*! \brief sum of gradient of each bin */
Guolin Ke's avatar
Guolin Ke committed
263
  std::vector<HistogramBinEntry> data_;
Guolin Ke's avatar
Guolin Ke committed
264
265
266
  /*! \brief number of all data */
  data_size_t num_data_;
  /*! \brief sum of gradient of current leaf */
Guolin Ke's avatar
Guolin Ke committed
267
  double sum_gradients_;
Guolin Ke's avatar
Guolin Ke committed
268
  /*! \brief sum of hessians of current leaf */
Guolin Ke's avatar
Guolin Ke committed
269
  double sum_hessians_;
Guolin Ke's avatar
Guolin Ke committed
270
271
272
273
  /*! \brief False if this histogram cannot split */
  bool is_splittable_ = true;
};

Guolin Ke's avatar
Guolin Ke committed
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401

class HistogramPool {
public:
  /*!
  * \brief Constructor
  */
  HistogramPool() {
  }

  /*!
  * \brief Destructor
  */
  ~HistogramPool() {
  }
  /*!
  * \brief Reset pool size
  * \param cache_size Max cache size
  * \param total_size Total size will be used
  */
  void ResetSize(int cache_size, int total_size) {
    cache_size_ = cache_size;
    // at least need 2 bucket to store smaller leaf and larger leaf
    CHECK(cache_size_ >= 2);
    total_size_ = total_size;
    if (cache_size_ > total_size_) {
      cache_size_ = total_size_;
    }
    is_enough_ = (cache_size_ == total_size_);
    if (!is_enough_) {
      mapper_ = std::vector<int>(total_size_);
      inverse_mapper_ = std::vector<int>(cache_size_);
      last_used_time_ = std::vector<int>(cache_size_);
      ResetMap();
    }
  }

  /*!
  * \brief Reset mapper
  */
  void ResetMap() {
    if (!is_enough_) {
      cur_time_ = 0;
      std::fill(mapper_.begin(), mapper_.end(), -1);
      std::fill(inverse_mapper_.begin(), inverse_mapper_.end(), -1);
      std::fill(last_used_time_.begin(), last_used_time_.end(), 0);
    }
  }

  /*!
  * \brief Fill the pool
  * \param obj_create_fun that used to generate object
  */
  void Fill(std::function<FeatureHistogram*()> obj_create_fun) {
    pool_.clear();
    pool_.resize(cache_size_);
    for (int i = 0; i < cache_size_; ++i) {
      pool_[i].reset(obj_create_fun());
    }
  }

  /*!
  * \brief Get data for the specific index
  * \param idx which index want to get
  * \param out output data will store into this
  * \return True if this index is in the pool, False if this index is not in the pool
  */
  bool Get(int idx, FeatureHistogram** out) {
    if (is_enough_) {
      *out = pool_[idx].get();
      return true;
    } else if (mapper_[idx] >= 0) {
      int slot = mapper_[idx];
      *out = pool_[slot].get();
      last_used_time_[slot] = ++cur_time_;
      return true;
    } else {
      // choose the least used slot 
      int slot = static_cast<int>(ArrayArgs<int>::ArgMin(last_used_time_));
      *out = pool_[slot].get();
      last_used_time_[slot] = ++cur_time_;

      // reset previous mapper
      if (inverse_mapper_[slot] >= 0) mapper_[inverse_mapper_[slot]] = -1;

      // update current mapper
      mapper_[idx] = slot;
      inverse_mapper_[slot] = idx;
      return false;
    }
  }

  /*!
  * \brief Move data from one index to another index
  * \param src_idx
  * \param dst_idx
  */
  void Move(int src_idx, int dst_idx) {
    if (is_enough_) {
      std::swap(pool_[src_idx], pool_[dst_idx]);
      return;
    }
    if (mapper_[src_idx] < 0) {
      return;
    }
    // get slot of src idx
    int slot = mapper_[src_idx];
    // reset src_idx
    mapper_[src_idx] = -1;

    // move to dst idx
    mapper_[dst_idx] = slot;
    last_used_time_[slot] = ++cur_time_;
    inverse_mapper_[slot] = dst_idx;
  }
private:

  std::vector<std::unique_ptr<FeatureHistogram[]>> pool_;
  int cache_size_;
  int total_size_;
  bool is_enough_ = false;
  std::vector<int> mapper_;
  std::vector<int> inverse_mapper_;
  std::vector<int> last_used_time_;
  int cur_time_ = 0;
};



Guolin Ke's avatar
Guolin Ke committed
402
}  // namespace LightGBM
Guolin Ke's avatar
Guolin Ke committed
403
#endif   // LightGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_