gbdt.h 8.17 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
Guolin Ke's avatar
Guolin Ke committed
29
30
31
32
33
34
  * \param config Config for boosting
  * \param train_data Training data
  * \param object_function Training objective function
  * \param training_metrics Training metrics
  * \param output_model_filename Filename of output model
  */
35
36
  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
37
38
                                                                       override;
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
39
40
41
  * \brief Adding a validation dataset
  * \param valid_data Validation dataset
  * \param valid_metrics Metrics for validation dataset
Guolin Ke's avatar
Guolin Ke committed
42
43
44
45
  */
  void AddDataset(const Dataset* valid_data,
       const std::vector<const Metric*>& valid_metrics) override;
  /*!
Guolin Ke's avatar
Guolin Ke committed
46
47
48
  * \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
49
  * \param is_eval true if need evaluation or early stop
Guolin Ke's avatar
Guolin Ke committed
50
  * \return True if meet early stopping or cannot boosting
Guolin Ke's avatar
Guolin Ke committed
51
  */
52
  virtual bool TrainOneIter(const score_t* gradient, const score_t* hessian, bool is_eval) override;
53

Guolin Ke's avatar
Guolin Ke committed
54
55
  bool EvalAndCheckEarlyStopping() override;

Guolin Ke's avatar
Guolin Ke committed
56
57
58
59
60
  /*!
  * \brief Get evaluation result at data_idx data
  * \param data_idx 0: training data, 1: 1st validation data
  * \return evaluation result
  */
61
  std::vector<double> GetEvalAt(int data_idx) const override;
62

Guolin Ke's avatar
Guolin Ke committed
63
64
  /*!
  * \brief Get current training score
Guolin Ke's avatar
Guolin Ke committed
65
  * \param out_len length of returned score
Guolin Ke's avatar
Guolin Ke committed
66
67
  * \return training score
  */
68
  virtual const score_t* GetTrainingScore(data_size_t* out_len) override;
69

Guolin Ke's avatar
Guolin Ke committed
70
71
72
73
74
75
76
  /*!
  * \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
  * \param out_len lenght of returned score
  */
  void GetPredictAt(int data_idx, score_t* out_result, data_size_t* out_len) const override;
Guolin Ke's avatar
Guolin Ke committed
77

Guolin Ke's avatar
Guolin Ke committed
78
  /*!
79
  * \brief Prediction for one record without sigmoid transformation
Guolin Ke's avatar
Guolin Ke committed
80
81
82
  * \param feature_values Feature value on this record
  * \return Prediction result for this record
  */
83
  std::vector<double> PredictRaw(const double* feature_values) const override;
Guolin Ke's avatar
Guolin Ke committed
84
85

  /*!
86
  * \brief Prediction for one record with sigmoid transformation if enabled
Guolin Ke's avatar
Guolin Ke committed
87
88
89
  * \param feature_values Feature value on this record
  * \return Prediction result for this record
  */
90
  std::vector<double> Predict(const double* feature_values) const override;
91

wxchan's avatar
wxchan committed
92
  /*!
93
  * \brief Prediction for one record with leaf index
wxchan's avatar
wxchan committed
94
95
96
  * \param feature_values Feature value on this record
  * \return Predicted leaf index for this record
  */
97
  std::vector<int> PredictLeafIndex(const double* value) const override;
98

Guolin Ke's avatar
Guolin Ke committed
99
  /*!
Guolin Ke's avatar
Guolin Ke committed
100
101
102
103
  * \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
Guolin Ke's avatar
Guolin Ke committed
104
  */
105
  virtual void SaveModelToFile(int num_used_model, bool is_finish, const char* filename) override;
Guolin Ke's avatar
Guolin Ke committed
106
107
108
  /*!
  * \brief Restore from a serialized string
  */
Guolin Ke's avatar
Guolin Ke committed
109
  void LoadModelFromString(const std::string& model_str) override;
Guolin Ke's avatar
Guolin Ke committed
110
111
112
113
114
  /*!
  * \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
115
116
117
118
119
120
121

  /*!
  * \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
122
123
124
125
126
127
  /*!
  * \brief Get number of weak sub-models
  * \return Number of weak sub-models
  */
  inline int NumberOfSubModels() const override { return static_cast<int>(models_.size()); }

128
129
130
131
  /*!
  * \brief Get number of classes
  * \return Number of classes
  */
Guolin Ke's avatar
Guolin Ke committed
132
  inline int NumberOfClasses() const override { return num_class_; }
133
134
135
136
137
138
139

  /*!
  * \brief Set number of used model for prediction
  */
  inline void SetNumUsedModel(int num_used_model) {
    if (num_used_model >= 0) {
      num_used_model_ = static_cast<int>(num_used_model / num_class_);
140
141
    } else {
      num_used_model_ = static_cast<int>(models_.size()) / num_class_;
142
143
    }
  }
144

145
146
147
  /*!
  * \brief Get Type name of this boosting object
  */
148
  virtual const char* Name() const override { return "gbdt"; }
149

150
protected:
Guolin Ke's avatar
Guolin Ke committed
151
152
153
  /*!
  * \brief Implement bagging logic
  * \param iter Current interation
154
  * \param curr_class Current class for multiclass training
Guolin Ke's avatar
Guolin Ke committed
155
  */
156
  void Bagging(int iter, const int curr_class);
Guolin Ke's avatar
Guolin Ke committed
157
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
158
159
  * \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
160
  * \param tree Trained tree of this iteration
161
  * \param curr_class Current class for multiclass training
Guolin Ke's avatar
Guolin Ke committed
162
  */
163
  void UpdateScoreOutOfBag(const Tree* tree, const int curr_class);
Guolin Ke's avatar
Guolin Ke committed
164
165
166
167
168
  /*!
  * \brief calculate the object function
  */
  void Boosting();
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
169
  * \brief updating score after tree was trained
Guolin Ke's avatar
Guolin Ke committed
170
  * \param tree Trained tree of this iteration
171
  * \param curr_class Current class for multiclass training
Guolin Ke's avatar
Guolin Ke committed
172
  */
173
  virtual void UpdateScore(const Tree* tree, const int curr_class);
Guolin Ke's avatar
Guolin Ke committed
174
  /*!
Hui Xue's avatar
Hui Xue committed
175
  * \brief Print metric result of current iteration
Guolin Ke's avatar
Guolin Ke committed
176
177
  * \param iter Current interation
  */
wxchan's avatar
wxchan committed
178
  bool OutputMetric(int iter);
wxchan's avatar
wxchan committed
179
180
181
182
  /*!
  * \brief Calculate feature importances
  * \param last_iter Last tree use to calculate
  */
183
184
185
  std::string FeatureImportance() const;
  /*! \brief current iteration */
  int iter_;
Guolin Ke's avatar
Guolin Ke committed
186
187
188
  /*! \brief Pointer to training data */
  const Dataset* train_data_;
  /*! \brief Config of gbdt */
Guolin Ke's avatar
Guolin Ke committed
189
  const BoostingConfig* gbdt_config_;
Hui Xue's avatar
Hui Xue committed
190
  /*! \brief Tree learner, will use this class to learn trees */
Guolin Ke's avatar
Guolin Ke committed
191
  std::vector<std::unique_ptr<TreeLearner>> tree_learner_;
Guolin Ke's avatar
Guolin Ke committed
192
193
  /*! \brief Objective function */
  const ObjectiveFunction* object_function_;
Hui Xue's avatar
Hui Xue committed
194
  /*! \brief Store and update training data's score */
Guolin Ke's avatar
Guolin Ke committed
195
  std::unique_ptr<ScoreUpdater> train_score_updater_;
Guolin Ke's avatar
Guolin Ke committed
196
197
198
  /*! \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
199
  std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_;
Guolin Ke's avatar
Guolin Ke committed
200
201
  /*! \brief Metric for validation data */
  std::vector<std::vector<const Metric*>> valid_metrics_;
wxchan's avatar
wxchan committed
202
203
  /*! \brief Number of rounds for early stopping */
  int early_stopping_round_;
wxchan's avatar
wxchan committed
204
205
  /*! \brief Best score(s) for early stopping */
  std::vector<std::vector<int>> best_iter_;
206
  std::vector<std::vector<double>> best_score_;
Guolin Ke's avatar
Guolin Ke committed
207
  /*! \brief Trained models(trees) */
Guolin Ke's avatar
Guolin Ke committed
208
  std::vector<std::unique_ptr<Tree>> models_;
Guolin Ke's avatar
Guolin Ke committed
209
210
211
  /*! \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
212
  std::vector<score_t> gradients_;
Guolin Ke's avatar
Guolin Ke committed
213
  /*! \brief Secend order derivative of training data */
Guolin Ke's avatar
Guolin Ke committed
214
  std::vector<score_t> hessians_;
Guolin Ke's avatar
Guolin Ke committed
215
  /*! \brief Store the data indices of out-of-bag */
Guolin Ke's avatar
Guolin Ke committed
216
  std::vector<data_size_t> out_of_bag_data_indices_;
Guolin Ke's avatar
Guolin Ke committed
217
218
219
  /*! \brief Number of out-of-bag data */
  data_size_t out_of_bag_data_cnt_;
  /*! \brief Store the indices of in-bag data */
Guolin Ke's avatar
Guolin Ke committed
220
  std::vector<data_size_t> bag_data_indices_;
Guolin Ke's avatar
Guolin Ke committed
221
222
  /*! \brief Number of in-bag data */
  data_size_t bag_data_cnt_;
223
  /*! \brief Number of training data */
Guolin Ke's avatar
Guolin Ke committed
224
  data_size_t num_data_;
225
226
  /*! \brief Number of classes */
  int num_class_;
Guolin Ke's avatar
Guolin Ke committed
227
228
229
230
  /*! \brief Random generator, used for bagging */
  Random random_;
  /*!
  *   \brief Sigmoid parameter, used for prediction.
231
  *          if > 0 means output score will transform by sigmoid function
Guolin Ke's avatar
Guolin Ke committed
232
  */
233
  double sigmoid_;
Guolin Ke's avatar
Guolin Ke committed
234
235
  /*! \brief Index of label column */
  data_size_t label_idx_;
236
  /*! \brief Saved number of models */
237
  int saved_model_size_;
238
239
  /*! \brief File to write models */
  std::ofstream model_output_file_;
240
241
  /*! \brief number of used model */
  int num_used_model_;
Guolin Ke's avatar
Guolin Ke committed
242
243
  /*! \brief Shrinkage rate for one iteration */
  double shrinkage_rate_;
Guolin Ke's avatar
Guolin Ke committed
244
245
246
};

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