"vscode:/vscode.git/clone" did not exist on "4b1669c495aac7149ab0ec5364a947b231093cdd"
feature_histogram.hpp 15.1 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
  /*!
  * \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
  */
Guolin Ke's avatar
Guolin Ke committed
31
  void Init(const Feature* feature, int feature_idx, const TreeConfig* tree_config) {
Guolin Ke's avatar
Guolin Ke committed
32
    feature_idx_ = feature_idx;
Guolin Ke's avatar
Guolin Ke committed
33
    tree_config_ = tree_config;
Guolin Ke's avatar
Guolin Ke committed
34
35
    feature_ = feature;
    data_.resize(feature_->num_bin());
Guolin Ke's avatar
Guolin Ke committed
36
    if (feature->bin_type() == BinType::NumericalBin) {
Guolin Ke's avatar
Guolin Ke committed
37
38
      find_best_threshold_fun_ = std::bind(&FeatureHistogram::FindBestThresholdForNumerical, this, std::placeholders::_1
        , std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
Guolin Ke's avatar
Guolin Ke committed
39
    } else {
Guolin Ke's avatar
Guolin Ke committed
40
41
      find_best_threshold_fun_ = std::bind(&FeatureHistogram::FindBestThresholdForCategorical, this, std::placeholders::_1
        , std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
Guolin Ke's avatar
Guolin Ke committed
42
    }
Guolin Ke's avatar
Guolin Ke committed
43
44
  }

Guolin Ke's avatar
Guolin Ke committed
45
46
47
  HistogramBinEntry* GetData() {
    std::memset(data_.data(), 0, feature_->num_bin() * sizeof(HistogramBinEntry));
    return data_.data();
Guolin Ke's avatar
Guolin Ke committed
48
49
50
51
52
53
54
  }

  /*!
  * \brief Subtract current histograms with other
  * \param other The histogram that want to subtract
  */
  void Subtract(const FeatureHistogram& other) {
Guolin Ke's avatar
Guolin Ke committed
55
    for (int i = 0; i < feature_->num_bin(); ++i) {
Guolin Ke's avatar
Guolin Ke committed
56
57
58
59
60
      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;
    }
  }
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

  void FixIgnoreBin(double sum_gradient, double sum_hessian, data_size_t num_data) {
    if (feature_->is_sparse()) {
      // not need to Fix if max heavy bin is 0
      if (feature_->bin_type() == BinType::NumericalBin
        && feature_->bin_mapper()->GetDefaultBin() == 0) {
        return;
      }
      int default_bin = static_cast<int>(feature_->bin_mapper()->GetDefaultBin());
      data_[default_bin].sum_gradients = sum_gradient;
      data_[default_bin].sum_hessians = sum_hessian;
      data_[default_bin].cnt = num_data;
      for (int t = feature_->num_bin() - 1; t >= 0; --t) {
        if (t != default_bin) {
          data_[default_bin].sum_gradients -= data_[t].sum_gradients;
          data_[default_bin].sum_hessians -= data_[t].sum_hessians;
          data_[default_bin].cnt -= data_[t].cnt;
        }
      }
    }
  }
Guolin Ke's avatar
Guolin Ke committed
82
83
84
85
  /*!
  * \brief Find best threshold for this histogram
  * \param output The best split result
  */
Guolin Ke's avatar
Guolin Ke committed
86
87
  void FindBestThreshold(double sum_gradient, double sum_hessian, data_size_t num_data,
    SplitInfo* output) {
88
    FixIgnoreBin(sum_gradient, sum_hessian, num_data);
89
    find_best_threshold_fun_(sum_gradient, sum_hessian + 2 * kEpsilon, num_data, output);
Guolin Ke's avatar
Guolin Ke committed
90
91
92
93
94
    if (output->gain > kMinScore) {
      is_splittable_ = true;
    } else {
      is_splittable_ = false;
    }
Guolin Ke's avatar
Guolin Ke committed
95
96
  }

Guolin Ke's avatar
Guolin Ke committed
97
98
  void FindBestThresholdForNumerical(double sum_gradient, double sum_hessian, data_size_t num_data,
    SplitInfo* output) {
Guolin Ke's avatar
Guolin Ke committed
99
100
101
    double best_sum_left_gradient = NAN;
    double best_sum_left_hessian = NAN;
    double best_gain = kMinScore;
Guolin Ke's avatar
Guolin Ke committed
102
    data_size_t best_left_count = 0;
Guolin Ke's avatar
Guolin Ke committed
103
    unsigned int best_threshold = static_cast<unsigned int>(feature_->num_bin());
Guolin Ke's avatar
Guolin Ke committed
104
105
    double sum_right_gradient = 0.0f;
    double sum_right_hessian = kEpsilon;
Guolin Ke's avatar
Guolin Ke committed
106
    data_size_t right_count = 0;
Guolin Ke's avatar
Guolin Ke committed
107
    double gain_shift = GetLeafSplitGain(sum_gradient, sum_hessian);
Guolin Ke's avatar
Guolin Ke committed
108
    double min_gain_shift = gain_shift + tree_config_->min_gain_to_split;
Guolin Ke's avatar
Guolin Ke committed
109
    bool is_splittable = false;
Guolin Ke's avatar
Guolin Ke committed
110
    // from right to left, and we don't need data in bin0
Guolin Ke's avatar
Guolin Ke committed
111
    for (int t = feature_->num_bin() - 1; t > 0; --t) {
Guolin Ke's avatar
Guolin Ke committed
112
113
114
115
      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
Guolin Ke's avatar
Guolin Ke committed
116
117
118
      if (right_count < tree_config_->min_data_in_leaf
        || sum_right_hessian < tree_config_->min_sum_hessian_in_leaf) continue;
      data_size_t left_count = num_data - right_count;
Guolin Ke's avatar
Guolin Ke committed
119
      // if data not enough
Guolin Ke's avatar
Guolin Ke committed
120
      if (left_count < tree_config_->min_data_in_leaf) break;
Guolin Ke's avatar
Guolin Ke committed
121

Guolin Ke's avatar
Guolin Ke committed
122
      double sum_left_hessian = sum_hessian - sum_right_hessian;
Guolin Ke's avatar
Guolin Ke committed
123
      // if sum hessian too small
Guolin Ke's avatar
Guolin Ke committed
124
      if (sum_left_hessian < tree_config_->min_sum_hessian_in_leaf) break;
125

Guolin Ke's avatar
Guolin Ke committed
126
      double sum_left_gradient = sum_gradient - sum_right_gradient;
Guolin Ke's avatar
Guolin Ke committed
127
      // current split gain
Guolin Ke's avatar
Guolin Ke committed
128
129
      double current_gain = GetLeafSplitGain(sum_left_gradient, sum_left_hessian)
        + GetLeafSplitGain(sum_right_gradient, sum_right_hessian);
130
131
132
      // gain with split is worse than without split
      if (current_gain < min_gain_shift) continue;

Guolin Ke's avatar
Guolin Ke committed
133
      // mark to is splittable
Guolin Ke's avatar
Guolin Ke committed
134
      is_splittable = true;
Guolin Ke's avatar
Guolin Ke committed
135
136
137
138
139
140
      // 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
Guolin Ke's avatar
Guolin Ke committed
141
        best_threshold = static_cast<unsigned int>(t - 1);
Guolin Ke's avatar
Guolin Ke committed
142
143
144
        best_gain = current_gain;
      }
    }
Guolin Ke's avatar
Guolin Ke committed
145
    if (is_splittable) {
Guolin Ke's avatar
Guolin Ke committed
146
147
148
149
150
151
152
      // 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;
Guolin Ke's avatar
Guolin Ke committed
153
154
155
156
157
      output->right_output = CalculateSplittedLeafOutput(sum_gradient - best_sum_left_gradient,
        sum_hessian - best_sum_left_hessian);
      output->right_count = num_data - best_left_count;
      output->right_sum_gradient = sum_gradient - best_sum_left_gradient;
      output->right_sum_hessian = sum_hessian - best_sum_left_hessian;
Guolin Ke's avatar
Guolin Ke committed
158
159
160
161
162
163
164
165
166
167
168
      output->gain = best_gain - gain_shift;
    } else {
      output->feature = feature_idx_;
      output->gain = kMinScore;
    }
  }

  /*!
  * \brief Find best threshold for this histogram
  * \param output The best split result
  */
Guolin Ke's avatar
Guolin Ke committed
169
170
  void FindBestThresholdForCategorical(double sum_gradient, double sum_hessian, data_size_t num_data,
    SplitInfo* output) {
Guolin Ke's avatar
Guolin Ke committed
171
    double best_gain = kMinScore;
Guolin Ke's avatar
Guolin Ke committed
172
    unsigned int best_threshold = static_cast<unsigned int>(feature_->num_bin());
Guolin Ke's avatar
Guolin Ke committed
173

Guolin Ke's avatar
Guolin Ke committed
174
    double gain_shift = GetLeafSplitGain(sum_gradient, sum_hessian);
Guolin Ke's avatar
Guolin Ke committed
175
    double min_gain_shift = gain_shift + tree_config_->min_gain_to_split;
Guolin Ke's avatar
Guolin Ke committed
176
177
    bool is_splittable = false;
    for (int t = feature_->num_bin() - 1; t >= 0; --t) {
Guolin Ke's avatar
Guolin Ke committed
178
179
180
181
182
      double sum_current_gradient = data_[t].sum_gradients;
      double sum_current_hessian = data_[t].sum_hessians;
      data_size_t current_count = data_[t].cnt;
      // if data not enough, or sum hessian too small
      if (current_count < tree_config_->min_data_in_leaf
Guolin Ke's avatar
Guolin Ke committed
183
184
        || sum_current_hessian < tree_config_->min_sum_hessian_in_leaf) continue;
      data_size_t other_count = num_data - current_count;
Guolin Ke's avatar
Guolin Ke committed
185
186
187
      // if data not enough
      if (other_count < tree_config_->min_data_in_leaf) continue;

Guolin Ke's avatar
Guolin Ke committed
188
      double sum_other_hessian = sum_hessian - sum_current_hessian;
Guolin Ke's avatar
Guolin Ke committed
189
190
191
      // if sum hessian too small
      if (sum_other_hessian < tree_config_->min_sum_hessian_in_leaf) continue;

Guolin Ke's avatar
Guolin Ke committed
192
      double sum_other_gradient = sum_gradient - sum_current_gradient;
Guolin Ke's avatar
Guolin Ke committed
193
      // current split gain
Guolin Ke's avatar
Guolin Ke committed
194
      double current_gain = GetLeafSplitGain(sum_other_gradient, sum_other_hessian)
Guolin Ke's avatar
Guolin Ke committed
195
196
197
198
199
        + GetLeafSplitGain(sum_current_gradient, sum_current_hessian);
      // gain with split is worse than without split
      if (current_gain < min_gain_shift) continue;

      // mark to is splittable
Guolin Ke's avatar
Guolin Ke committed
200
      is_splittable = true;
Guolin Ke's avatar
Guolin Ke committed
201
202
203
204
205
206
      // better split point
      if (current_gain > best_gain) {
        best_threshold = static_cast<unsigned int>(t);
        best_gain = current_gain;
      }
    }
Guolin Ke's avatar
Guolin Ke committed
207
    // update split information
Guolin Ke's avatar
Guolin Ke committed
208
    if (is_splittable) {
Guolin Ke's avatar
Guolin Ke committed
209
210
211
212
213
214
215
216
      output->feature = feature_idx_;
      output->threshold = best_threshold;
      output->left_output = CalculateSplittedLeafOutput(data_[best_threshold].sum_gradients,
        data_[best_threshold].sum_hessians);
      output->left_count = data_[best_threshold].cnt;
      output->left_sum_gradient = data_[best_threshold].sum_gradients;
      output->left_sum_hessian = data_[best_threshold].sum_hessians;

Guolin Ke's avatar
Guolin Ke committed
217
218
219
220
221
      output->right_output = CalculateSplittedLeafOutput(sum_gradient - data_[best_threshold].sum_gradients,
        sum_hessian - data_[best_threshold].sum_hessians);
      output->right_count = num_data - data_[best_threshold].cnt;
      output->right_sum_gradient = sum_gradient - data_[best_threshold].sum_gradients;
      output->right_sum_hessian = sum_hessian - data_[best_threshold].sum_hessians;
Guolin Ke's avatar
Guolin Ke committed
222
223
224
225
226
227

      output->gain = best_gain - gain_shift;
    } else {
      output->feature = feature_idx_;
      output->gain = kMinScore;
    }
Guolin Ke's avatar
Guolin Ke committed
228
229
230
231
232
  }
  /*!
  * \brief Binary size of this histogram
  */
  int SizeOfHistgram() const {
Guolin Ke's avatar
Guolin Ke committed
233
    return feature_->num_bin() * sizeof(HistogramBinEntry);
Guolin Ke's avatar
Guolin Ke committed
234
235
236
237
238
239
  }

  /*!
  * \brief Memory pointer to histogram data
  */
  const HistogramBinEntry* HistogramData() const {
Guolin Ke's avatar
Guolin Ke committed
240
    return data_.data();
Guolin Ke's avatar
Guolin Ke committed
241
242
243
244
245
246
  }

  /*!
  * \brief Restore histogram from memory
  */
  void FromMemory(char* memory_data)  {
Guolin Ke's avatar
Guolin Ke committed
247
    std::memcpy(data_.data(), memory_data, feature_->num_bin() * sizeof(HistogramBinEntry));
Guolin Ke's avatar
Guolin Ke committed
248
249
250
251
252
253
254
255
256
257
258
259
  }

  /*!
  * \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; }

Guolin Ke's avatar
Guolin Ke committed
260
261
262
263
  void ResetConfig(const TreeConfig* tree_config) {
    tree_config_ = tree_config;
  }

Guolin Ke's avatar
Guolin Ke committed
264
265
private:
  /*!
266
  * \brief Calculate the split gain based on regularized sum_gradients and sum_hessians
Guolin Ke's avatar
Guolin Ke committed
267
268
269
270
  * \param sum_gradients
  * \param sum_hessians
  * \return split gain
  */
Guolin Ke's avatar
Guolin Ke committed
271
  double GetLeafSplitGain(double sum_gradients, double sum_hessians) const {
272
    double abs_sum_gradients = std::fabs(sum_gradients);
Guolin Ke's avatar
Guolin Ke committed
273
274
275
276
    if (abs_sum_gradients > tree_config_->lambda_l1) {
      double reg_abs_sum_gradients = abs_sum_gradients - tree_config_->lambda_l1;
      return (reg_abs_sum_gradients * reg_abs_sum_gradients) 
             / (sum_hessians + tree_config_->lambda_l2);
277
278
    }
    return 0.0f;
Guolin Ke's avatar
Guolin Ke committed
279
280
281
  }

  /*!
282
  * \brief Calculate the output of a leaf based on regularized sum_gradients and sum_hessians
Guolin Ke's avatar
Guolin Ke committed
283
284
285
286
  * \param sum_gradients
  * \param sum_hessians
  * \return leaf output
  */
Guolin Ke's avatar
Guolin Ke committed
287
  double CalculateSplittedLeafOutput(double sum_gradients, double sum_hessians) const {
288
    double abs_sum_gradients = std::fabs(sum_gradients);
Guolin Ke's avatar
Guolin Ke committed
289
290
291
    if (abs_sum_gradients > tree_config_->lambda_l1) {
      return -std::copysign(abs_sum_gradients - tree_config_->lambda_l1, sum_gradients) 
                            / (sum_hessians + tree_config_->lambda_l2);
292
293
    }
    return 0.0f;
Guolin Ke's avatar
Guolin Ke committed
294
295
296
  }

  int feature_idx_;
Guolin Ke's avatar
Guolin Ke committed
297
  const Feature* feature_;
Guolin Ke's avatar
Guolin Ke committed
298
299
  /*! \brief pointer of tree config */
  const TreeConfig* tree_config_;
Guolin Ke's avatar
Guolin Ke committed
300
  /*! \brief sum of gradient of each bin */
Guolin Ke's avatar
Guolin Ke committed
301
  std::vector<HistogramBinEntry> data_;
Guolin Ke's avatar
Guolin Ke committed
302
303
  /*! \brief False if this histogram cannot split */
  bool is_splittable_ = true;
Guolin Ke's avatar
Guolin Ke committed
304
  /*! \brief function that used to find best threshold */
Guolin Ke's avatar
Guolin Ke committed
305
  std::function<void(double, double, data_size_t, SplitInfo*)> find_best_threshold_fun_;
Guolin Ke's avatar
Guolin Ke committed
306
307
};

Guolin Ke's avatar
Guolin Ke committed
308
309
310
311
312
313
314

class HistogramPool {
public:
  /*!
  * \brief Constructor
  */
  HistogramPool() {
Guolin Ke's avatar
Guolin Ke committed
315
316
    cache_size_ = 0;
    total_size_ = 0;
Guolin Ke's avatar
Guolin Ke committed
317
318
319
320
321
322
323
324
325
326
327
328
  }

  /*!
  * \brief Destructor
  */
  ~HistogramPool() {
  }
  /*!
  * \brief Reset pool size
  * \param cache_size Max cache size
  * \param total_size Total size will be used
  */
Guolin Ke's avatar
Guolin Ke committed
329
  void Reset(int cache_size, int total_size) {
Guolin Ke's avatar
Guolin Ke committed
330
331
332
333
334
335
336
337
338
    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_) {
339
340
341
      mapper_.resize(total_size_);
      inverse_mapper_.resize(cache_size_);
      last_used_time_.resize(cache_size_);
Guolin Ke's avatar
Guolin Ke committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
      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) {
Guolin Ke's avatar
Guolin Ke committed
363
    fill_func_ = obj_create_fun;
Guolin Ke's avatar
Guolin Ke committed
364
365
366
367
368
369
370
    pool_.clear();
    pool_.resize(cache_size_);
    for (int i = 0; i < cache_size_; ++i) {
      pool_[i].reset(obj_create_fun());
    }
  }

Guolin Ke's avatar
Guolin Ke committed
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
  void DynamicChangeSize(int cache_size, int total_size) {
    int old_cache_size = cache_size_;
    Reset(cache_size, total_size);
    pool_.resize(cache_size_);
    for (int i = old_cache_size; i < cache_size_; ++i) {
      pool_[i].reset(fill_func_());
    }
  }

  void ResetConfig(const TreeConfig* tree_config, int array_size) {
    for (int i = 0; i < cache_size_; ++i) {
      auto data_ptr = pool_[i].get();
      for (int j = 0; j < array_size; ++j) {
        data_ptr[j].ResetConfig(tree_config);
      }
    }
  }
Guolin Ke's avatar
Guolin Ke committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
  /*!
  * \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_;
Guolin Ke's avatar
Guolin Ke committed
445
  std::function<FeatureHistogram*()> fill_func_;
Guolin Ke's avatar
Guolin Ke committed
446
447
448
449
450
451
452
453
454
455
456
  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
457
}  // namespace LightGBM
Guolin Ke's avatar
Guolin Ke committed
458
#endif   // LightGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_