boosting.h 9.81 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
#ifndef LIGHTGBM_BOOSTING_H_
#define LIGHTGBM_BOOSTING_H_

#include <LightGBM/meta.h>
#include <LightGBM/config.h>

#include <vector>
#include <string>
9
#include <map>
Guolin Ke's avatar
Guolin Ke committed
10
11
12
13
14
15
16

namespace LightGBM {

/*! \brief forward declaration */
class Dataset;
class ObjectiveFunction;
class Metric;
17
struct PredictionEarlyStopInstance;
Guolin Ke's avatar
Guolin Ke committed
18
19
20
21

/*!
* \brief The interface for Boosting
*/
22
class LIGHTGBM_EXPORT Boosting {
Nikita Titov's avatar
Nikita Titov committed
23
 public:
Guolin Ke's avatar
Guolin Ke committed
24
25
26
27
  /*! \brief virtual destructor */
  virtual ~Boosting() {}

  /*!
Qiwei Ye's avatar
Qiwei Ye committed
28
29
  * \brief Initialization logic
  * \param config Configs for boosting
Guolin Ke's avatar
Guolin Ke committed
30
  * \param train_data Training data
31
  * \param objective_function Training objective function
Guolin Ke's avatar
Guolin Ke committed
32
33
  * \param training_metrics Training metric
  */
34
  virtual void Init(
Guolin Ke's avatar
Guolin Ke committed
35
    const Config* config,
36
    const Dataset* train_data,
37
    const ObjectiveFunction* objective_function,
38
    const std::vector<const Metric*>& training_metrics) = 0;
Guolin Ke's avatar
Guolin Ke committed
39

wxchan's avatar
wxchan committed
40
41
  /*!
  * \brief Merge model from other boosting object
Guolin Ke's avatar
Guolin Ke committed
42
  Will insert to the front of current boosting object
wxchan's avatar
wxchan committed
43
44
45
46
  * \param other
  */
  virtual void MergeFrom(const Boosting* other) = 0;

47
48
49
  /*!
  * \brief Shuffle Existing Models
  */
50
  virtual void ShuffleModels(int start_iter, int end_iter) = 0;
51

52
53
54
  virtual void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function,
                                 const std::vector<const Metric*>& training_metrics) = 0;

Guolin Ke's avatar
Guolin Ke committed
55
  virtual void ResetConfig(const Config* config) = 0;
wxchan's avatar
wxchan committed
56

57
58


Guolin Ke's avatar
Guolin Ke committed
59
60
61
62
63
  /*!
  * \brief Add a validation data
  * \param valid_data Validation data
  * \param valid_metrics Metric for validation data
  */
wxchan's avatar
wxchan committed
64
  virtual void AddValidDataset(const Dataset* valid_data,
Guolin Ke's avatar
Guolin Ke committed
65
                               const std::vector<const Metric*>& valid_metrics) = 0;
Guolin Ke's avatar
Guolin Ke committed
66

Guolin Ke's avatar
Guolin Ke committed
67
68
  virtual void Train(int snapshot_freq, const std::string& model_output_path) = 0;

69
70
71
72
73
  /*!
  * \brief Update the tree output by new training data
  */
  virtual void RefitTree(const std::vector<std::vector<int>>& tree_leaf_prediction) = 0;

Guolin Ke's avatar
Guolin Ke committed
74
75
  /*!
  * \brief Training logic
Guolin Ke's avatar
Guolin Ke committed
76
77
78
  * \param gradients nullptr for using default objective, otherwise use self-defined boosting
  * \param hessians nullptr for using default objective, otherwise use self-defined boosting
  * \return True if cannot train anymore
Guolin Ke's avatar
Guolin Ke committed
79
  */
Guolin Ke's avatar
Guolin Ke committed
80
  virtual bool TrainOneIter(const score_t* gradients, const score_t* hessians) = 0;
81

wxchan's avatar
wxchan committed
82
83
84
85
86
87
88
89
90
91
  /*!
  * \brief Rollback one iteration
  */
  virtual void RollbackOneIter() = 0;

  /*!
  * \brief return current iteration
  */
  virtual int GetCurrentIteration() const = 0;

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

Guolin Ke's avatar
Guolin Ke committed
99
100
  /*!
  * \brief Get current training score
Guolin Ke's avatar
Guolin Ke committed
101
  * \param out_len length of returned score
Guolin Ke's avatar
Guolin Ke committed
102
103
  * \return training score
  */
104
  virtual const double* GetTrainingScore(int64_t* out_len) = 0;
Guolin Ke's avatar
Guolin Ke committed
105

Guolin Ke's avatar
Guolin Ke committed
106
107
108
  /*!
  * \brief Get prediction result at data_idx data
  * \param data_idx 0: training data, 1: 1st validation data
109
  * \return out_len length of returned score
Guolin Ke's avatar
Guolin Ke committed
110
111
  */
  virtual int64_t GetNumPredictAt(int data_idx) const = 0;
Guolin Ke's avatar
Guolin Ke committed
112

Guolin Ke's avatar
Guolin Ke committed
113
114
115
116
  /*!
  * \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
117
  * \param out_len length of returned score
Guolin Ke's avatar
Guolin Ke committed
118
  */
Guolin Ke's avatar
Guolin Ke committed
119
  virtual void GetPredictAt(int data_idx, double* result, int64_t* out_len) = 0;
Guolin Ke's avatar
Guolin Ke committed
120

121
  virtual int NumPredictOneRow(int num_iteration, bool is_pred_leaf, bool is_pred_contrib) const = 0;
Guolin Ke's avatar
Guolin Ke committed
122

Guolin Ke's avatar
Guolin Ke committed
123
  /*!
Hui Xue's avatar
Hui Xue committed
124
  * \brief Prediction for one record, not sigmoid transform
Guolin Ke's avatar
Guolin Ke committed
125
  * \param feature_values Feature value on this record
Guolin Ke's avatar
Guolin Ke committed
126
  * \param output Prediction result for this record
Guolin Ke's avatar
Guolin Ke committed
127
  * \param early_stop Early stopping instance. If nullptr, no early stopping is applied and all models are evaluated.
Guolin Ke's avatar
Guolin Ke committed
128
  */
cbecker's avatar
cbecker committed
129
  virtual void PredictRaw(const double* features, double* output,
130
                          const PredictionEarlyStopInstance* early_stop) const = 0;
Guolin Ke's avatar
Guolin Ke committed
131

Guolin Ke's avatar
Guolin Ke committed
132
133
  virtual void PredictRawByMap(const std::unordered_map<int, double>& features, double* output,
                               const PredictionEarlyStopInstance* early_stop) const = 0;
134
135


Guolin Ke's avatar
Guolin Ke committed
136
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
137
  * \brief Prediction for one record, sigmoid transformation will be used if needed
Guolin Ke's avatar
Guolin Ke committed
138
  * \param feature_values Feature value on this record
Guolin Ke's avatar
Guolin Ke committed
139
  * \param output Prediction result for this record
Guolin Ke's avatar
Guolin Ke committed
140
  * \param early_stop Early stopping instance. If nullptr, no early stopping is applied and all models are evaluated.
Guolin Ke's avatar
Guolin Ke committed
141
  */
cbecker's avatar
cbecker committed
142
  virtual void Predict(const double* features, double* output,
143
                       const PredictionEarlyStopInstance* early_stop) const = 0;
144

Guolin Ke's avatar
Guolin Ke committed
145
146
  virtual void PredictByMap(const std::unordered_map<int, double>& features, double* output,
                            const PredictionEarlyStopInstance* early_stop) const = 0;
147
148


wxchan's avatar
wxchan committed
149
  /*!
150
  * \brief Prediction for one record with leaf index
wxchan's avatar
wxchan committed
151
  * \param feature_values Feature value on this record
Guolin Ke's avatar
Guolin Ke committed
152
  * \param output Prediction result for this record
wxchan's avatar
wxchan committed
153
  */
Guolin Ke's avatar
Guolin Ke committed
154
  virtual void PredictLeafIndex(
155
    const double* features, double* output) const = 0;
156

157
158
159
  virtual void PredictLeafIndexByMap(
    const std::unordered_map<int, double>& features, double* output) const = 0;

Guolin Ke's avatar
Guolin Ke committed
160
  /*!
161
162
163
  * \brief Feature contributions for the model's prediction of one record
  * \param feature_values Feature value on this record
  * \param output Prediction result for this record
Guolin Ke's avatar
Guolin Ke committed
164
  * \param early_stop Early stopping instance. If nullptr, no early stopping is applied and all models are evaluated.
165
166
  */
  virtual void PredictContrib(const double* features, double* output,
Guolin Ke's avatar
Guolin Ke committed
167
                              const PredictionEarlyStopInstance* early_stop) const = 0;
168

Guolin Ke's avatar
Guolin Ke committed
169
  /*!
wxchan's avatar
wxchan committed
170
  * \brief Dump model to json format string
171
  * \param start_iteration The model will be saved start from
172
  * \param num_iteration Number of iterations that want to dump, -1 means dump all
wxchan's avatar
wxchan committed
173
174
  * \return Json format string of model
  */
175
  virtual std::string DumpModel(int start_iteration, int num_iteration) const = 0;
wxchan's avatar
wxchan committed
176

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
  /*!
  * \brief Translate model to if-else statement
  * \param num_iteration Number of iterations that want to translate, -1 means translate all
  * \return if-else format codes of model
  */
  virtual std::string ModelToIfElse(int num_iteration) const = 0;

  /*!
  * \brief Translate model to if-else statement
  * \param num_iteration Number of iterations that want to translate, -1 means translate all
  * \param filename Filename that want to save to
  * \return is_finish Is training finished or not
  */
  virtual bool SaveModelToIfElse(int num_iteration, const char* filename) const = 0;

wxchan's avatar
wxchan committed
192
193
  /*!
  * \brief Save model to file
194
  * \param start_iteration The model will be saved start from
wxchan's avatar
wxchan committed
195
  * \param num_iterations Number of model that want to save, -1 means save all
wxchan's avatar
wxchan committed
196
197
  * \param is_finish Is training finished or not
  * \param filename Filename that want to save to
198
  * \return true if succeeded
Guolin Ke's avatar
Guolin Ke committed
199
  */
200
  virtual bool SaveModelToFile(int start_iteration, int num_iterations, const char* filename) const = 0;
Guolin Ke's avatar
Guolin Ke committed
201

202
203
  /*!
  * \brief Save model to string
204
  * \param start_iteration The model will be saved start from
wxchan's avatar
wxchan committed
205
  * \param num_iterations Number of model that want to save, -1 means save all
206
207
  * \return Non-empty string if succeeded
  */
208
  virtual std::string SaveModelToString(int start_iteration, int num_iterations) const = 0;
209

Guolin Ke's avatar
Guolin Ke committed
210
211
  /*!
  * \brief Restore from a serialized string
212
213
  * \param buffer The content of model
  * \param len The length of buffer
wxchan's avatar
wxchan committed
214
215
  * \return true if succeeded
  */
216
  virtual bool LoadModelFromString(const char* buffer, size_t len) = 0;
wxchan's avatar
wxchan committed
217

218
219
220
221
222
223
224
  /*!
  * \brief Calculate feature importances
  * \param num_iteration Number of model that want to use for feature importance, -1 means use all
  * \param importance_type: 0 for split, 1 for gain
  * \return vector of feature_importance
  */
  virtual std::vector<double> FeatureImportance(int num_iteration, int importance_type) const = 0;
Guolin Ke's avatar
Guolin Ke committed
225
226
227
228
229
230
231

  /*!
  * \brief Get max feature index of this model
  * \return Max feature index of this model
  */
  virtual int MaxFeatureIdx() const = 0;

wxchan's avatar
wxchan committed
232
233
234
235
236
237
  /*!
  * \brief Get feature names of this model
  * \return Feature names of this model
  */
  virtual std::vector<std::string> FeatureNames() const = 0;

Guolin Ke's avatar
Guolin Ke committed
238
239
240
241
242
243
  /*!
  * \brief Get index of label column
  * \return index of label column
  */
  virtual int LabelIdx() const = 0;

Guolin Ke's avatar
Guolin Ke committed
244
245
246
247
  /*!
  * \brief Get number of weak sub-models
  * \return Number of weak sub-models
  */
wxchan's avatar
wxchan committed
248
  virtual int NumberOfTotalModel() const = 0;
249

Guolin Ke's avatar
Guolin Ke committed
250
  /*!
Guolin Ke's avatar
Guolin Ke committed
251
252
  * \brief Get number of models per iteration
  * \return Number of models per iteration
Guolin Ke's avatar
Guolin Ke committed
253
  */
Guolin Ke's avatar
Guolin Ke committed
254
  virtual int NumModelPerIteration() const = 0;
Guolin Ke's avatar
Guolin Ke committed
255

256
257
258
259
  /*!
  * \brief Get number of classes
  * \return Number of classes
  */
Guolin Ke's avatar
Guolin Ke committed
260
  virtual int NumberOfClasses() const = 0;
261

262
263
264
  /*! \brief The prediction should be accurate or not. True will disable early stopping for prediction. */
  virtual bool NeedAccuratePrediction() const = 0;

265
  /*!
Guolin Ke's avatar
Guolin Ke committed
266
267
  * \brief Initial work for the prediction
  * \param num_iteration number of used iteration
268
  * \param is_pred_contrib
269
  */
270
  virtual void InitPredict(int num_iteration, bool is_pred_contrib) = 0;
271

272
  /*!
Guolin Ke's avatar
Guolin Ke committed
273
  * \brief Name of submodel
274
  */
Guolin Ke's avatar
Guolin Ke committed
275
  virtual const char* SubModelName() const = 0;
276

Guolin Ke's avatar
Guolin Ke committed
277
278
279
280
281
282
  Boosting() = default;
  /*! \brief Disable copy */
  Boosting& operator=(const Boosting&) = delete;
  /*! \brief Disable copy */
  Boosting(const Boosting&) = delete;

283
  static bool LoadFileToBoosting(Boosting* boosting, const char* filename);
wxchan's avatar
wxchan committed
284

Guolin Ke's avatar
Guolin Ke committed
285
286
287
  /*!
  * \brief Create boosting object
  * \param type Type of boosting
wxchan's avatar
wxchan committed
288
  * \param format Format of model
289
290
  * \param config config for boosting
  * \param filename name of model file, if existing will continue to train from this model
Guolin Ke's avatar
Guolin Ke committed
291
292
  * \return The boosting object
  */
293
  static Boosting* CreateBoosting(const std::string& type, const char* filename);
Guolin Ke's avatar
Guolin Ke committed
294
295
};

Guolin Ke's avatar
Guolin Ke committed
296
class GBDTBase : public Boosting {
Nikita Titov's avatar
Nikita Titov committed
297
 public:
Guolin Ke's avatar
Guolin Ke committed
298
299
300
301
  virtual double GetLeafValue(int tree_idx, int leaf_idx) const = 0;
  virtual void SetLeafValue(int tree_idx, int leaf_idx, double val) = 0;
};

Guolin Ke's avatar
Guolin Ke committed
302
303
}  // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
304
#endif   // LightGBM_BOOSTING_H_