gbdt.h 12.1 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
#ifndef LIGHTGBM_BOOSTING_GBDT_H_
#define LIGHTGBM_BOOSTING_GBDT_H_

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

#include <cstdio>
#include <vector>
#include <string>
10
#include <fstream>
Guolin Ke's avatar
Guolin Ke committed
11
#include <memory>
Guolin Ke's avatar
Guolin Ke committed
12
13
14
15
16
17
18
19
20
21

namespace LightGBM {
/*!
* \brief GBDT algorithm implementation. including Training, prediction, bagging.
*/
class GBDT: public Boosting {
public:
  /*!
  * \brief Constructor
  */
22
  GBDT();
Guolin Ke's avatar
Guolin Ke committed
23
24
25
26
27
  /*!
  * \brief Destructor
  */
  ~GBDT();
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
28
  * \brief Initialization logic
zhangyafeikimi's avatar
zhangyafeikimi committed
29
  * \param gbdt_config Config for boosting
Guolin Ke's avatar
Guolin Ke committed
30
31
32
33
  * \param train_data Training data
  * \param object_function Training objective function
  * \param training_metrics Training metrics
  */
34
35
  void Init(const BoostingConfig* gbdt_config, const Dataset* train_data, const ObjectiveFunction* object_function,
                             const std::vector<const Metric*>& training_metrics)
Guolin Ke's avatar
Guolin Ke committed
36
                                                                       override;
wxchan's avatar
wxchan committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

  /*!
  * \brief Merge model from other boosting object
           Will insert to the front of current boosting object
  * \param other
  */
  void MergeFrom(const Boosting* other) override {
    auto other_gbdt = reinterpret_cast<const GBDT*>(other);
    // tmp move to other vector
    auto original_models = std::move(models_);
    models_ = std::vector<std::unique_ptr<Tree>>();
    // push model from other first
    for (const auto& tree : other_gbdt->models_) {
      auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
      models_.push_back(std::move(new_tree));
    }
    num_init_iteration_ = static_cast<int>(models_.size()) / num_class_;
    // push model in current object
    for (const auto& tree : original_models) {
      auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
      models_.push_back(std::move(new_tree));
    }
    num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_class_;
  }

  /*!
  * \brief Reset training data for current boosting
  * \param train_data Training data
  * \param object_function Training objective function
  * \param training_metrics Training metric
  */
  void ResetTrainingData(const BoostingConfig* config, const Dataset* train_data, const ObjectiveFunction* object_function, const std::vector<const Metric*>& training_metrics) override;

Guolin Ke's avatar
Guolin Ke committed
70
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
71
72
73
  * \brief Adding a validation dataset
  * \param valid_data Validation dataset
  * \param valid_metrics Metrics for validation dataset
Guolin Ke's avatar
Guolin Ke committed
74
  */
wxchan's avatar
wxchan committed
75
  void AddValidDataset(const Dataset* valid_data,
Guolin Ke's avatar
Guolin Ke committed
76
77
       const std::vector<const Metric*>& valid_metrics) override;
  /*!
Guolin Ke's avatar
Guolin Ke committed
78
79
80
  * \brief Training logic
  * \param gradient nullptr for using default objective, otherwise use self-defined boosting
  * \param hessian nullptr for using default objective, otherwise use self-defined boosting
Guolin Ke's avatar
Guolin Ke committed
81
  * \param is_eval true if need evaluation or early stop
Guolin Ke's avatar
Guolin Ke committed
82
  * \return True if meet early stopping or cannot boosting
Guolin Ke's avatar
Guolin Ke committed
83
  */
84
  virtual bool TrainOneIter(const score_t* gradient, const score_t* hessian, bool is_eval) override;
85

wxchan's avatar
wxchan committed
86
87
88
89
90
  /*!
  * \brief Rollback one iteration
  */
  void RollbackOneIter() override;

Guolin Ke's avatar
Guolin Ke committed
91
  int GetCurrentIteration() const override { return static_cast<int>(models_.size()) / num_class_; }
wxchan's avatar
wxchan committed
92

Guolin Ke's avatar
Guolin Ke committed
93
94
  bool EvalAndCheckEarlyStopping() override;

Guolin Ke's avatar
Guolin Ke committed
95
96
97
98
99
  /*!
  * \brief Get evaluation result at data_idx data
  * \param data_idx 0: training data, 1: 1st validation data
  * \return evaluation result
  */
100
  std::vector<double> GetEvalAt(int data_idx) const override;
101

Guolin Ke's avatar
Guolin Ke committed
102
103
  /*!
  * \brief Get current training score
Guolin Ke's avatar
Guolin Ke committed
104
  * \param out_len length of returned score
Guolin Ke's avatar
Guolin Ke committed
105
106
  * \return training score
  */
107
  virtual const double* GetTrainingScore(int64_t* out_len) override;
108

Guolin Ke's avatar
Guolin Ke committed
109
110
111
112
113
114
115
116
  virtual int64_t GetNumPredictAt(int data_idx) const override {
    CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size()));
    data_size_t num_data = train_data_->num_data();
    if (data_idx > 0) {
      num_data = valid_score_updater_[data_idx - 1]->num_data();
    }
    return num_data * num_class_;
  }
Guolin Ke's avatar
Guolin Ke committed
117
118
119
120
  /*!
  * \brief Get prediction result at data_idx data
  * \param data_idx 0: training data, 1: 1st validation data
  * \param result used to store prediction result, should allocate memory before call this function
121
  * \param out_len length of returned score
Guolin Ke's avatar
Guolin Ke committed
122
  */
Guolin Ke's avatar
Guolin Ke committed
123
  void GetPredictAt(int data_idx, double* out_result, int64_t* out_len) override;
Guolin Ke's avatar
Guolin Ke committed
124

Guolin Ke's avatar
Guolin Ke committed
125
  /*!
wxchan's avatar
wxchan committed
126
  * \brief Prediction for one record without sigmoid transformation
Guolin Ke's avatar
Guolin Ke committed
127
128
129
  * \param feature_values Feature value on this record
  * \return Prediction result for this record
  */
130
  std::vector<double> PredictRaw(const double* feature_values) const override;
Guolin Ke's avatar
Guolin Ke committed
131
132

  /*!
wxchan's avatar
wxchan committed
133
  * \brief Prediction for one record with sigmoid transformation if enabled
Guolin Ke's avatar
Guolin Ke committed
134
135
136
  * \param feature_values Feature value on this record
  * \return Prediction result for this record
  */
137
  std::vector<double> Predict(const double* feature_values) const override;
wxchan's avatar
wxchan committed
138

wxchan's avatar
wxchan committed
139
  /*!
wxchan's avatar
wxchan committed
140
  * \brief Prediction for one record with leaf index
wxchan's avatar
wxchan committed
141
142
143
  * \param feature_values Feature value on this record
  * \return Predicted leaf index for this record
  */
144
  std::vector<int> PredictLeafIndex(const double* value) const override;
wxchan's avatar
wxchan committed
145

Guolin Ke's avatar
Guolin Ke committed
146
  /*!
wxchan's avatar
wxchan committed
147
148
  * \brief Dump model to json format string
  * \return Json format string of model
Guolin Ke's avatar
Guolin Ke committed
149
  */
150
  std::string DumpModel(int num_iteration) const override;
wxchan's avatar
wxchan committed
151
152
153
154
155
156
157

  /*!
  * \brief Save model to file
  * \param num_used_model Number of model that want to save, -1 means save all
  * \param is_finish Is training finished or not
  * \param filename Filename that want to save to
  */
158
  virtual bool SaveModelToFile(int num_iterations, const char* filename) const override ;
wxchan's avatar
wxchan committed
159

160
161
162
163
164
165
166
  /*!
  * \brief Save model to string
  * \param num_used_model Number of model that want to save, -1 means save all
  * \return Non-empty string if succeeded
  */
  virtual std::string SaveModelToString(int num_iterations) const override ;

Guolin Ke's avatar
Guolin Ke committed
167
168
169
  /*!
  * \brief Restore from a serialized string
  */
170
  bool LoadModelFromString(const std::string& model_str) override;
wxchan's avatar
wxchan committed
171

Guolin Ke's avatar
Guolin Ke committed
172
173
174
175
176
  /*!
  * \brief Get max feature index of this model
  * \return Max feature index of this model
  */
  inline int MaxFeatureIdx() const override { return max_feature_idx_; }
Guolin Ke's avatar
Guolin Ke committed
177

wxchan's avatar
wxchan committed
178
179
180
181
182
183
  /*!
  * \brief Get feature names of this model
  * \return Feature names of this model
  */
  inline std::vector<std::string> FeatureNames() const override { return feature_names_; }

Guolin Ke's avatar
Guolin Ke committed
184
185
186
187
188
189
  /*!
  * \brief Get index of label column
  * \return index of label column
  */
  inline int LabelIdx() const override { return label_idx_; }

Guolin Ke's avatar
Guolin Ke committed
190
191
192
193
  /*!
  * \brief Get number of weak sub-models
  * \return Number of weak sub-models
  */
wxchan's avatar
wxchan committed
194
  inline int NumberOfTotalModel() const override { return static_cast<int>(models_.size()); }
Guolin Ke's avatar
Guolin Ke committed
195

196
197
198
199
  /*!
  * \brief Get number of classes
  * \return Number of classes
  */
Guolin Ke's avatar
Guolin Ke committed
200
  inline int NumberOfClasses() const override { return num_class_; }
201
202

  /*!
wxchan's avatar
wxchan committed
203
  * \brief Set number of iterations for prediction
204
  */
wxchan's avatar
wxchan committed
205
  inline void SetNumIterationForPred(int num_iteration) override {
206
    num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_class_;
wxchan's avatar
wxchan committed
207
    if (num_iteration > 0) {
208
      num_iteration_for_pred_ = std::min(num_iteration + (boost_from_average_ ? 1 : 0), num_iteration_for_pred_);
209
210
    }
  }
wxchan's avatar
wxchan committed
211

Guolin Ke's avatar
Guolin Ke committed
212
213
214
215
216
217
218
219
220
221
222
223
  inline double GetLeafValue(int tree_idx, int leaf_idx) const {
    CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
    CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
    return models_[tree_idx]->LeafOutput(leaf_idx);
  }

  inline void SetLeafValue(int tree_idx, int leaf_idx, double val) {
    CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
    CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
    models_[tree_idx]->SetLeafOutput(leaf_idx, val);
  }

224
225
226
  /*!
  * \brief Get Type name of this boosting object
  */
Guolin Ke's avatar
Guolin Ke committed
227
  virtual const char* SubModelName() const override { return "tree"; }
228

229
protected:
Guolin Ke's avatar
Guolin Ke committed
230
231
232
233
  /*!
  * \brief Implement bagging logic
  * \param iter Current interation
  */
234
235
236
237
238
239
240
241
242
  virtual void Bagging(int iter);

  /*!
  * \brief Helper function for bagging, used for multi-threading optimization
  * \param start start indice of bagging
  * \param cnt count
  * \param buffer output buffer
  * \return count of left size
  */
Guolin Ke's avatar
Guolin Ke committed
243
  data_size_t BaggingHelper(Random& cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer);
Guolin Ke's avatar
Guolin Ke committed
244
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
245
246
  * \brief updating score for out-of-bag data.
  *        Data should be update since we may re-bagging data on training
Guolin Ke's avatar
Guolin Ke committed
247
  * \param tree Trained tree of this iteration
248
  * \param curr_class Current class for multiclass training
Guolin Ke's avatar
Guolin Ke committed
249
  */
250
  void UpdateScoreOutOfBag(const Tree* tree, const int curr_class);
Guolin Ke's avatar
Guolin Ke committed
251
252
253
254
255
  /*!
  * \brief calculate the object function
  */
  void Boosting();
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
256
  * \brief updating score after tree was trained
Guolin Ke's avatar
Guolin Ke committed
257
  * \param tree Trained tree of this iteration
258
  * \param curr_class Current class for multiclass training
Guolin Ke's avatar
Guolin Ke committed
259
  */
260
  virtual void UpdateScore(const Tree* tree, const int curr_class);
Guolin Ke's avatar
Guolin Ke committed
261
  /*!
Hui Xue's avatar
Hui Xue committed
262
  * \brief Print metric result of current iteration
Guolin Ke's avatar
Guolin Ke committed
263
  * \param iter Current interation
Guolin Ke's avatar
Guolin Ke committed
264
  * \return best_msg if met early_stopping
Guolin Ke's avatar
Guolin Ke committed
265
  */
Guolin Ke's avatar
Guolin Ke committed
266
  std::string OutputMetric(int iter);
wxchan's avatar
wxchan committed
267
268
269
  /*!
  * \brief Calculate feature importances
  */
wxchan's avatar
wxchan committed
270
  std::vector<std::pair<size_t, std::string>> FeatureImportance() const;
271
272
  /*! \brief current iteration */
  int iter_;
Guolin Ke's avatar
Guolin Ke committed
273
274
275
  /*! \brief Pointer to training data */
  const Dataset* train_data_;
  /*! \brief Config of gbdt */
Guolin Ke's avatar
Guolin Ke committed
276
  std::unique_ptr<BoostingConfig> gbdt_config_;
Hui Xue's avatar
Hui Xue committed
277
  /*! \brief Tree learner, will use this class to learn trees */
278
  std::unique_ptr<TreeLearner> tree_learner_;
Guolin Ke's avatar
Guolin Ke committed
279
280
  /*! \brief Objective function */
  const ObjectiveFunction* object_function_;
Hui Xue's avatar
Hui Xue committed
281
  /*! \brief Store and update training data's score */
Guolin Ke's avatar
Guolin Ke committed
282
  std::unique_ptr<ScoreUpdater> train_score_updater_;
Guolin Ke's avatar
Guolin Ke committed
283
284
285
  /*! \brief Metrics for training data */
  std::vector<const Metric*> training_metrics_;
  /*! \brief Store and update validation data's scores */
Guolin Ke's avatar
Guolin Ke committed
286
  std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_;
Guolin Ke's avatar
Guolin Ke committed
287
288
  /*! \brief Metric for validation data */
  std::vector<std::vector<const Metric*>> valid_metrics_;
wxchan's avatar
wxchan committed
289
290
  /*! \brief Number of rounds for early stopping */
  int early_stopping_round_;
Guolin Ke's avatar
Guolin Ke committed
291
  /*! \brief Best iteration(s) for early stopping */
wxchan's avatar
wxchan committed
292
  std::vector<std::vector<int>> best_iter_;
Guolin Ke's avatar
Guolin Ke committed
293
  /*! \brief Best score(s) for early stopping */
294
  std::vector<std::vector<double>> best_score_;
Guolin Ke's avatar
Guolin Ke committed
295
296
  /*! \brief output message of best iteration */
  std::vector<std::vector<std::string>> best_msg_;
Guolin Ke's avatar
Guolin Ke committed
297
  /*! \brief Trained models(trees) */
Guolin Ke's avatar
Guolin Ke committed
298
  std::vector<std::unique_ptr<Tree>> models_;
Guolin Ke's avatar
Guolin Ke committed
299
300
301
  /*! \brief Max feature index of training data*/
  int max_feature_idx_;
  /*! \brief First order derivative of training data */
Guolin Ke's avatar
Guolin Ke committed
302
  std::vector<score_t> gradients_;
Guolin Ke's avatar
Guolin Ke committed
303
  /*! \brief Secend order derivative of training data */
Guolin Ke's avatar
Guolin Ke committed
304
  std::vector<score_t> hessians_;
Guolin Ke's avatar
Guolin Ke committed
305
  /*! \brief Store the indices of in-bag data */
Guolin Ke's avatar
Guolin Ke committed
306
  std::vector<data_size_t> bag_data_indices_;
Guolin Ke's avatar
Guolin Ke committed
307
308
  /*! \brief Number of in-bag data */
  data_size_t bag_data_cnt_;
309
310
  /*! \brief Store the indices of in-bag data */
  std::vector<data_size_t> tmp_indices_;
wxchan's avatar
wxchan committed
311
  /*! \brief Number of training data */
Guolin Ke's avatar
Guolin Ke committed
312
  data_size_t num_data_;
313
314
  /*! \brief Number of classes */
  int num_class_;
Guolin Ke's avatar
Guolin Ke committed
315
316
  /*!
  *   \brief Sigmoid parameter, used for prediction.
wxchan's avatar
wxchan committed
317
  *          if > 0 means output score will transform by sigmoid function
Guolin Ke's avatar
Guolin Ke committed
318
  */
319
  double sigmoid_;
Guolin Ke's avatar
Guolin Ke committed
320
321
  /*! \brief Index of label column */
  data_size_t label_idx_;
322
  /*! \brief number of used model */
wxchan's avatar
wxchan committed
323
  int num_iteration_for_pred_;
Guolin Ke's avatar
Guolin Ke committed
324
325
  /*! \brief Shrinkage rate for one iteration */
  double shrinkage_rate_;
wxchan's avatar
wxchan committed
326
327
  /*! \brief Number of loaded initial models */
  int num_init_iteration_;
Guolin Ke's avatar
Guolin Ke committed
328
329
  /*! \brief Feature names */
  std::vector<std::string> feature_names_;
Guolin Ke's avatar
Guolin Ke committed
330
  std::vector<std::string> feature_infos_;
331
332
333
334
335
336
337
338
339
340
341
342
  /*! \brief number of threads */
  int num_threads_;
  /*! \brief Buffer for multi-threading bagging */
  std::vector<data_size_t> offsets_buf_;
  /*! \brief Buffer for multi-threading bagging */
  std::vector<data_size_t> left_cnts_buf_;
  /*! \brief Buffer for multi-threading bagging */
  std::vector<data_size_t> right_cnts_buf_;
  /*! \brief Buffer for multi-threading bagging */
  std::vector<data_size_t> left_write_pos_buf_;
  /*! \brief Buffer for multi-threading bagging */
  std::vector<data_size_t> right_write_pos_buf_;
Guolin Ke's avatar
Guolin Ke committed
343
344
  std::unique_ptr<Dataset> tmp_subset_;
  bool is_use_subset_;
345
  bool boost_from_average_;
346
347
  std::vector<bool> class_need_train_;
  std::vector<double> class_default_output_;
Guolin Ke's avatar
Guolin Ke committed
348
349
350
};

}  // namespace LightGBM
Guolin Ke's avatar
Guolin Ke committed
351
#endif   // LightGBM_BOOSTING_GBDT_H_