dart.hpp 6.95 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
16
17
18
19
20
21
#ifndef LIGHTGBM_BOOSTING_DART_H_
#define LIGHTGBM_BOOSTING_DART_H_

#include <LightGBM/boosting.h>
#include "score_updater.hpp"
#include "gbdt.h"

#include <cstdio>
#include <vector>
#include <string>
#include <fstream>

namespace LightGBM {
/*!
* \brief DART algorithm implementation. including Training, prediction, bagging.
*/
class DART: public GBDT {
public:
  /*!
  * \brief Constructor
  */
22
  DART() : GBDT() { }
Guolin Ke's avatar
Guolin Ke committed
23
24
25
26
27
28
29
30
  /*!
  * \brief Destructor
  */
  ~DART() { }
  /*!
  * \brief Initialization logic
  * \param config Config for boosting
  * \param train_data Training data
31
  * \param objective_function Training objective function
Guolin Ke's avatar
Guolin Ke committed
32
33
34
  * \param training_metrics Training metrics
  * \param output_model_filename Filename of output model
  */
Guolin Ke's avatar
Guolin Ke committed
35
  void Init(const Config* config, const Dataset* train_data,
36
            const ObjectiveFunction* objective_function,
37
38
            const std::vector<const Metric*>& training_metrics) override {
    GBDT::Init(config, train_data, objective_function, training_metrics);
Guolin Ke's avatar
Guolin Ke committed
39
    random_for_drop_ = Random(config_->drop_seed);
40
    sum_weight_ = 0.0f;
Guolin Ke's avatar
Guolin Ke committed
41
  }
Guolin Ke's avatar
Guolin Ke committed
42

Guolin Ke's avatar
Guolin Ke committed
43
  void ResetConfig(const Config* config) override {
Guolin Ke's avatar
Guolin Ke committed
44
    GBDT::ResetConfig(config);
Guolin Ke's avatar
Guolin Ke committed
45
    random_for_drop_ = Random(config_->drop_seed);
Guolin Ke's avatar
Guolin Ke committed
46
47
48
    sum_weight_ = 0.0f;
  }

Guolin Ke's avatar
Guolin Ke committed
49
50
51
  /*!
  * \brief one training iteration
  */
Guolin Ke's avatar
Guolin Ke committed
52
  bool TrainOneIter(const score_t* gradient, const score_t* hessian) override {
Guolin Ke's avatar
Guolin Ke committed
53
    is_update_score_cur_iter_ = false;
Guolin Ke's avatar
Guolin Ke committed
54
55
56
57
    bool ret = GBDT::TrainOneIter(gradient, hessian);
    if (ret) {
      return ret;
    }
Guolin Ke's avatar
Guolin Ke committed
58
59
    // normalize
    Normalize();
Guolin Ke's avatar
Guolin Ke committed
60
    if (!config_->uniform_drop) {
61
62
63
      tree_weight_.push_back(shrinkage_rate_);
      sum_weight_ += shrinkage_rate_;
    }
Guolin Ke's avatar
Guolin Ke committed
64
    return false;
Guolin Ke's avatar
Guolin Ke committed
65
  }
Guolin Ke's avatar
Guolin Ke committed
66

Guolin Ke's avatar
Guolin Ke committed
67
68
69
70
71
  /*!
  * \brief Get current training score
  * \param out_len length of returned score
  * \return training score
  */
72
  const double* GetTrainingScore(int64_t* out_len) override {
Guolin Ke's avatar
Guolin Ke committed
73
74
75
76
77
    if (!is_update_score_cur_iter_) {
      // only drop one time in one iteration
      DroppingTrees();
      is_update_score_cur_iter_ = true;
    }
78
    *out_len = static_cast<int64_t>(train_score_updater_->num_data()) * num_class_;
Guolin Ke's avatar
Guolin Ke committed
79
80
    return train_score_updater_->score();
  }
81
82
83
84
85
  
  bool EvalAndCheckEarlyStopping() override {
    GBDT::OutputMetric(iter_);
    return false;
  }
Guolin Ke's avatar
Guolin Ke committed
86

Guolin Ke's avatar
Guolin Ke committed
87
88
89
90
91
92
private:
  /*!
  * \brief drop trees based on drop_rate
  */
  void DroppingTrees() {
    drop_index_.clear();
Guolin Ke's avatar
Guolin Ke committed
93
    bool is_skip = random_for_drop_.NextFloat() < config_->skip_drop;
zhangyafeikimi's avatar
zhangyafeikimi committed
94
    // select dropping tree indices based on drop_rate and tree weights
95
    if (!is_skip) {
Guolin Ke's avatar
Guolin Ke committed
96
97
      double drop_rate = config_->drop_rate;
      if (!config_->uniform_drop) {
98
        double inv_average_weight = static_cast<double>(tree_weight_.size()) / sum_weight_;
Guolin Ke's avatar
Guolin Ke committed
99
100
        if (config_->max_drop > 0) {
          drop_rate = std::min(drop_rate, config_->max_drop * inv_average_weight / sum_weight_);
101
102
        }
        for (int i = 0; i < iter_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
103
          if (random_for_drop_.NextFloat() < drop_rate * tree_weight_[i] * inv_average_weight) {
Guolin Ke's avatar
Guolin Ke committed
104
            drop_index_.push_back(num_init_iteration_ + i);
Guolin Ke's avatar
Guolin Ke committed
105
            if (drop_index_.size() >= static_cast<size_t>(config_->max_drop)) {
106
107
              break;
            }
108
109
110
          }
        }
      } else {
Guolin Ke's avatar
Guolin Ke committed
111
112
        if (config_->max_drop > 0) {
          drop_rate = std::min(drop_rate, config_->max_drop / static_cast<double>(iter_));
113
114
        }
        for (int i = 0; i < iter_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
115
          if (random_for_drop_.NextFloat() < drop_rate) {
Guolin Ke's avatar
Guolin Ke committed
116
            drop_index_.push_back(num_init_iteration_ + i);
Guolin Ke's avatar
Guolin Ke committed
117
            if (drop_index_.size() >= static_cast<size_t>(config_->max_drop)) {
118
119
              break;
            }
120
          }
Guolin Ke's avatar
Guolin Ke committed
121
122
123
124
125
        }
      }
    }
    // drop trees
    for (auto i : drop_index_) {
126
127
      for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
        auto curr_tree = i * num_tree_per_iteration_ + cur_tree_id;
Guolin Ke's avatar
Guolin Ke committed
128
        models_[curr_tree]->Shrinkage(-1.0);
129
        train_score_updater_->AddScore(models_[curr_tree].get(), cur_tree_id);
Guolin Ke's avatar
Guolin Ke committed
130
131
      }
    }
Guolin Ke's avatar
Guolin Ke committed
132
133
    if (!config_->xgboost_dart_mode) {
      shrinkage_rate_ = config_->learning_rate / (1.0f + static_cast<double>(drop_index_.size()));
134
135
    } else {
      if (drop_index_.empty()) {
Guolin Ke's avatar
Guolin Ke committed
136
        shrinkage_rate_ = config_->learning_rate;
137
      } else {
Guolin Ke's avatar
Guolin Ke committed
138
        shrinkage_rate_ = config_->learning_rate / (config_->learning_rate + static_cast<double>(drop_index_.size()));
139
140
      }
    }
Guolin Ke's avatar
Guolin Ke committed
141
142
143
  }
  /*!
  * \brief normalize dropped trees
144
  * NOTE: num_drop_tree(k), learning_rate(lr), shrinkage_rate_ = lr / (k + 1)
wxchan's avatar
wxchan committed
145
  *       step 1: shrink tree to -1 -> drop tree
146
  *       step 2: shrink tree to k / (k + 1) - 1 from -1, by 1/(k+1)
wxchan's avatar
wxchan committed
147
  *               -> normalize for valid data
148
  *       step 3: shrink tree to k / (k + 1) from k / (k + 1) - 1, by -k
wxchan's avatar
wxchan committed
149
  *               -> normalize for train data
150
  *       end with tree weight = (k / (k + 1)) * old_weight
Guolin Ke's avatar
Guolin Ke committed
151
152
153
  */
  void Normalize() {
    double k = static_cast<double>(drop_index_.size());
Guolin Ke's avatar
Guolin Ke committed
154
    if (!config_->xgboost_dart_mode) {
155
      for (auto i : drop_index_) {
156
157
        for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
          auto curr_tree = i * num_tree_per_iteration_ + cur_tree_id;
158
159
160
          // update validation score
          models_[curr_tree]->Shrinkage(1.0f / (k + 1.0f));
          for (auto& score_updater : valid_score_updater_) {
161
            score_updater->AddScore(models_[curr_tree].get(), cur_tree_id);
162
163
164
          }
          // update training score
          models_[curr_tree]->Shrinkage(-k);
165
          train_score_updater_->AddScore(models_[curr_tree].get(), cur_tree_id);
166
        }
Guolin Ke's avatar
Guolin Ke committed
167
        if (!config_->uniform_drop) {
168
169
170
171
172
173
          sum_weight_ -= tree_weight_[i] * (1.0f / (k + 1.0f));
          tree_weight_[i] *= (k / (k + 1.0f));
        }
      }
    } else {
      for (auto i : drop_index_) {
174
175
        for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
          auto curr_tree = i * num_tree_per_iteration_ + cur_tree_id;
176
177
178
          // update validation score
          models_[curr_tree]->Shrinkage(shrinkage_rate_);
          for (auto& score_updater : valid_score_updater_) {
179
            score_updater->AddScore(models_[curr_tree].get(), cur_tree_id);
180
181
          }
          // update training score
Guolin Ke's avatar
Guolin Ke committed
182
          models_[curr_tree]->Shrinkage(-k / config_->learning_rate);
183
          train_score_updater_->AddScore(models_[curr_tree].get(), cur_tree_id);
184
        }
Guolin Ke's avatar
Guolin Ke committed
185
186
187
        if (!config_->uniform_drop) {
          sum_weight_ -= tree_weight_[i] * (1.0f / (k + config_->learning_rate));;
          tree_weight_[i] *= (k / (k + config_->learning_rate));
Guolin Ke's avatar
Guolin Ke committed
188
189
190
191
        }
      }
    }
  }
192
193
194
195
  /*! \brief The weights of all trees, used to choose drop trees */
  std::vector<double> tree_weight_;
  /*! \brief sum weights of all trees */
  double sum_weight_;
zhangyafeikimi's avatar
zhangyafeikimi committed
196
  /*! \brief The indices of dropping trees */
197
  std::vector<int> drop_index_;
Guolin Ke's avatar
Guolin Ke committed
198
199
  /*! \brief Random generator, used to select dropping trees */
  Random random_for_drop_;
Guolin Ke's avatar
Guolin Ke committed
200
201
  /*! \brief Flag that the score is update on current iter or not*/
  bool is_update_score_cur_iter_;
Guolin Ke's avatar
Guolin Ke committed
202
203
204
205
};

}  // namespace LightGBM
#endif   // LightGBM_BOOSTING_DART_H_