gbdt.cpp 14.3 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "gbdt.h"

#include <LightGBM/utils/common.h>

#include <LightGBM/feature.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/metric.h>

#include <ctime>

#include <sstream>
#include <chrono>
#include <string>
#include <vector>
15
#include <utility>
Guolin Ke's avatar
Guolin Ke committed
16
17
18
19
20
21
22
23
24

namespace LightGBM {

GBDT::GBDT(const BoostingConfig* config)
  : tree_learner_(nullptr), train_score_updater_(nullptr),
  gradients_(nullptr), hessians_(nullptr),
  out_of_bag_data_indices_(nullptr), bag_data_indices_(nullptr) {
  max_feature_idx_ = 0;
  gbdt_config_ = dynamic_cast<const GBDTConfig*>(config);
wxchan's avatar
wxchan committed
25
  early_stopping_round_ = gbdt_config_->early_stopping_round;
Guolin Ke's avatar
Guolin Ke committed
26
27
28
29
30
31
32
33
34
35
36
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
}

GBDT::~GBDT() {
  if (tree_learner_ != nullptr) { delete tree_learner_; }
  if (gradients_ != nullptr) { delete[] gradients_; }
  if (hessians_ != nullptr) { delete[] hessians_; }
  if (out_of_bag_data_indices_ != nullptr) { delete[] out_of_bag_data_indices_; }
  if (bag_data_indices_ != nullptr) { delete[] bag_data_indices_; }
  for (auto& tree : models_) {
    if (tree != nullptr) { delete tree; }
  }
  if (train_score_updater_ != nullptr) { delete train_score_updater_; }
  for (auto& score_tracker : valid_score_updater_) {
    if (score_tracker != nullptr) { delete score_tracker; }
  }
}

void GBDT::Init(const Dataset* train_data, const ObjectiveFunction* object_function,
     const std::vector<const Metric*>& training_metrics, const char* output_model_filename) {
  train_data_ = train_data;
  // create tree learner
  tree_learner_ =
    TreeLearner::CreateTreeLearner(gbdt_config_->tree_learner_type, gbdt_config_->tree_config);
  // init tree learner
  tree_learner_->Init(train_data_);
  object_function_ = object_function;
  // push training metrics
  for (const auto& metric : training_metrics) {
    training_metrics_.push_back(metric);
  }
  // create score tracker
  train_score_updater_ = new ScoreUpdater(train_data_);
  num_data_ = train_data_->num_data();
  // create buffer for gradients and hessians
  gradients_ = new score_t[num_data_];
  hessians_ = new score_t[num_data_];

  // get max feature index
64
  max_feature_idx_ = train_data_->num_total_features() - 1;
Guolin Ke's avatar
Guolin Ke committed
65
66
  // get label index
  label_idx_ = train_data_->label_idx();
Guolin Ke's avatar
Guolin Ke committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
  // if need bagging, create buffer
  if (gbdt_config_->bagging_fraction < 1.0 && gbdt_config_->bagging_freq > 0) {
    out_of_bag_data_indices_ = new data_size_t[num_data_];
    bag_data_indices_ = new data_size_t[num_data_];
  } else {
    out_of_bag_data_cnt_ = 0;
    out_of_bag_data_indices_ = nullptr;
    bag_data_cnt_ = num_data_;
    bag_data_indices_ = nullptr;
  }
  // initialize random generator
  random_ = Random(gbdt_config_->bagging_seed);

  // open model output file
  #ifdef _MSC_VER
  fopen_s(&output_model_file, output_model_filename, "w");
  #else
  output_model_file = fopen(output_model_filename, "w");
  #endif
  // output models
  fprintf(output_model_file, "%s", this->ModelsToString().c_str());
}



void GBDT::AddDataset(const Dataset* valid_data,
         const std::vector<const Metric*>& valid_metrics) {
  // for a validation dataset, we need its score and metric
  valid_score_updater_.push_back(new ScoreUpdater(valid_data));
  valid_metrics_.emplace_back();
wxchan's avatar
wxchan committed
97
98
  best_iter_.emplace_back();
  best_score_.emplace_back();
Guolin Ke's avatar
Guolin Ke committed
99
100
  for (const auto& metric : valid_metrics) {
    valid_metrics_.back().push_back(metric);
wxchan's avatar
wxchan committed
101
102
    best_iter_.back().push_back(0);
    best_score_.back().push_back(-1);
Guolin Ke's avatar
Guolin Ke committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
  }
}


void GBDT::Bagging(int iter) {
  // if need bagging
  if (out_of_bag_data_indices_ != nullptr && iter % gbdt_config_->bagging_freq == 0) {
    // if doesn't have query data
    if (train_data_->metadata().query_boundaries() == nullptr) {
      bag_data_cnt_ =
        static_cast<data_size_t>(gbdt_config_->bagging_fraction * num_data_);
      out_of_bag_data_cnt_ = num_data_ - bag_data_cnt_;
      data_size_t cur_left_cnt = 0;
      data_size_t cur_right_cnt = 0;
      // random bagging, minimal unit is one record
      for (data_size_t i = 0; i < num_data_; ++i) {
        double prob =
          (bag_data_cnt_ - cur_left_cnt) / static_cast<double>(num_data_ - i);
        if (random_.NextDouble() < prob) {
          bag_data_indices_[cur_left_cnt++] = i;
        } else {
          out_of_bag_data_indices_[cur_right_cnt++] = i;
        }
      }
    } else {
      // if have query data
      const data_size_t* query_boundaries = train_data_->metadata().query_boundaries();
      data_size_t num_query = train_data_->metadata().num_queries();
      data_size_t bag_query_cnt =
          static_cast<data_size_t>(num_query * gbdt_config_->bagging_fraction);
      data_size_t cur_left_query_cnt = 0;
      data_size_t cur_left_cnt = 0;
      data_size_t cur_right_cnt = 0;
      // random bagging, minimal unit is one query
      for (data_size_t i = 0; i < num_query; ++i) {
        double prob =
            (bag_query_cnt - cur_left_query_cnt) / static_cast<double>(num_query - i);
        if (random_.NextDouble() < prob) {
          for (data_size_t j = query_boundaries[i]; j < query_boundaries[i + 1]; ++j) {
            bag_data_indices_[cur_left_cnt++] = j;
          }
          cur_left_query_cnt++;
        } else {
          for (data_size_t j = query_boundaries[i]; j < query_boundaries[i + 1]; ++j) {
            out_of_bag_data_indices_[cur_right_cnt++] = j;
          }
        }
      }
      bag_data_cnt_ = cur_left_cnt;
      out_of_bag_data_cnt_ = num_data_ - bag_data_cnt_;
    }
154
    Log::Info("re-bagging, using %d data to train", bag_data_cnt_);
Guolin Ke's avatar
Guolin Ke committed
155
156
157
158
159
160
    // set bagging data to tree learner
    tree_learner_->SetBaggingData(bag_data_indices_, bag_data_cnt_);
  }
}

void GBDT::UpdateScoreOutOfBag(const Tree* tree) {
Hui Xue's avatar
Hui Xue committed
161
  // we need to predict out-of-bag socres of data for boosting
Guolin Ke's avatar
Guolin Ke committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
  if (out_of_bag_data_indices_ != nullptr) {
    train_score_updater_->
      AddScore(tree, out_of_bag_data_indices_, out_of_bag_data_cnt_);
  }
}

void GBDT::Train() {
  // training start time
  auto start_time = std::chrono::high_resolution_clock::now();
  for (int iter = 0; iter < gbdt_config_->num_iterations; ++iter) {
    // boosting first
    Boosting();
    // bagging logic
    Bagging(iter);
    // train a new tree
    Tree * new_tree = TrainOneTree();
Hui Xue's avatar
Hui Xue committed
178
    // if cannot learn a new tree, then stop
Guolin Ke's avatar
Guolin Ke committed
179
    if (new_tree->num_leaves() <= 1) {
180
      Log::Info("Can't training anymore, there isn't any leaf meets split requirements.");
Guolin Ke's avatar
Guolin Ke committed
181
182
      break;
    }
Hui Xue's avatar
Hui Xue committed
183
    // shrinkage by learning rate
Guolin Ke's avatar
Guolin Ke committed
184
185
186
187
188
    new_tree->Shrinkage(gbdt_config_->learning_rate);
    // update score
    UpdateScore(new_tree);
    UpdateScoreOutOfBag(new_tree);
    // print message for metric
wxchan's avatar
wxchan committed
189
    bool is_early_stopping = OutputMetric(iter + 1);
Guolin Ke's avatar
Guolin Ke committed
190
191
    // add model
    models_.push_back(new_tree);
Hui Xue's avatar
Hui Xue committed
192
    // save model to file per iteration
wxchan's avatar
wxchan committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    if (early_stopping_round_ > 0){
        // if use early stopping, save previous model at (iter - early_stopping_round_) iteration
        if (iter >= early_stopping_round_){
            fprintf(output_model_file, "Tree=%d\n", iter - early_stopping_round_);
            Tree * printing_tree = models_.at(iter - early_stopping_round_);
            fprintf(output_model_file, "%s\n", printing_tree->ToString().c_str());
            fflush(output_model_file);
        }
    }
    else{
        fprintf(output_model_file, "Tree=%d\n", iter);
        fprintf(output_model_file, "%s\n", new_tree->ToString().c_str());
        fflush(output_model_file);
    }
Guolin Ke's avatar
Guolin Ke committed
207
    auto end_time = std::chrono::high_resolution_clock::now();
Hui Xue's avatar
Hui Xue committed
208
    // output used time per iteration
209
    Log::Info("%f seconds elapsed, finished %d iteration", std::chrono::duration<double,
Guolin Ke's avatar
Guolin Ke committed
210
                                     std::milli>(end_time - start_time) * 1e-3, iter + 1);
wxchan's avatar
wxchan committed
211
212
    if (is_early_stopping) {
        // close file with an early-stopping message
213
        Log::Info("Early stopping at iteration %d, the best iteration round is %d", iter + 1, iter + 1 - early_stopping_round_);
wxchan's avatar
wxchan committed
214
        FeatureImportance(iter - early_stopping_round_ + 1);
wxchan's avatar
wxchan committed
215
216
217
        fclose(output_model_file);
        return;
    }
Guolin Ke's avatar
Guolin Ke committed
218
219
  }
  // close file
wxchan's avatar
wxchan committed
220
221
  if (early_stopping_round_ > 0) {
      // save remaining models
Guolin Ke's avatar
Guolin Ke committed
222
      for (int iter = gbdt_config_->num_iterations - early_stopping_round_; iter < static_cast<int>(models_.size()); ++iter){
wxchan's avatar
wxchan committed
223
224
225
226
227
        fprintf(output_model_file, "Tree=%d\n", iter);
        fprintf(output_model_file, "%s\n", models_.at(iter)->ToString().c_str());
      }
      fflush(output_model_file);
  }
228
  FeatureImportance(static_cast<int>(models_.size()));
Guolin Ke's avatar
Guolin Ke committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
  fclose(output_model_file);
}

Tree* GBDT::TrainOneTree() {
  return tree_learner_->Train(gradients_, hessians_);
}

void GBDT::UpdateScore(const Tree* tree) {
  // update training score
  train_score_updater_->AddScore(tree_learner_);
  // update validation score
  for (auto& score_tracker : valid_score_updater_) {
    score_tracker->AddScore(tree);
  }
}

wxchan's avatar
wxchan committed
245
246
bool GBDT::OutputMetric(int iter) {
  bool ret = false;
Guolin Ke's avatar
Guolin Ke committed
247
248
  // print training metric
  for (auto& sub_metric : training_metrics_) {
wxchan's avatar
wxchan committed
249
    sub_metric->PrintAndGetLoss(iter, train_score_updater_->score());
Guolin Ke's avatar
Guolin Ke committed
250
251
252
  }
  // print validation metric
  for (size_t i = 0; i < valid_metrics_.size(); ++i) {
wxchan's avatar
wxchan committed
253
    for (size_t j = 0; j < valid_metrics_[i].size(); ++j) {
wxchan's avatar
wxchan committed
254
      score_t test_score_ = valid_metrics_[i][j]->PrintAndGetLoss(iter, valid_score_updater_[i]->score());
wxchan's avatar
wxchan committed
255
256
257
258
259
260
261
262
263
264
265
266
      if (!ret && early_stopping_round_ > 0){
        bool the_bigger_the_better_ = valid_metrics_[i][j]->the_bigger_the_better;
        if (best_score_[i][j] < 0 
            || (!the_bigger_the_better_ && test_score_ < best_score_[i][j])
            || ( the_bigger_the_better_ && test_score_ > best_score_[i][j])){
            best_score_[i][j] = test_score_;
            best_iter_[i][j] = iter;
        }
        else {
          if (iter - best_iter_[i][j] >= early_stopping_round_) ret = true;
        }
      }
Guolin Ke's avatar
Guolin Ke committed
267
268
    }
  }
wxchan's avatar
wxchan committed
269
  return ret;
Guolin Ke's avatar
Guolin Ke committed
270
271
272
}

void GBDT::Boosting() {
Hui Xue's avatar
Hui Xue committed
273
  // objective function will calculate gradients and hessians
Guolin Ke's avatar
Guolin Ke committed
274
275
276
277
278
279
280
  object_function_->
    GetGradients(train_score_updater_->score(), gradients_, hessians_);
}


std::string GBDT::ModelsToString() const {
  // serialize this object to string
Guolin Ke's avatar
Guolin Ke committed
281
  std::stringstream str_buf;
Guolin Ke's avatar
Guolin Ke committed
282
  // output label index
Guolin Ke's avatar
Guolin Ke committed
283
  str_buf << "label_index=" << label_idx_ << std::endl;
Guolin Ke's avatar
Guolin Ke committed
284
  // output max_feature_idx
Guolin Ke's avatar
Guolin Ke committed
285
  str_buf << "max_feature_idx=" << max_feature_idx_ << std::endl;
Guolin Ke's avatar
Guolin Ke committed
286
  // output sigmoid parameter
Guolin Ke's avatar
Guolin Ke committed
287
288
  str_buf << "sigmoid=" << object_function_->GetSigmoid() << std::endl;
  str_buf << std::endl;
Guolin Ke's avatar
Guolin Ke committed
289
290
291

  // output tree models
  for (size_t i = 0; i < models_.size(); ++i) {
Guolin Ke's avatar
Guolin Ke committed
292
293
    str_buf << "Tree=" << i << std::endl;
    str_buf << models_[i]->ToString() << std::endl;
Guolin Ke's avatar
Guolin Ke committed
294
  }
Guolin Ke's avatar
Guolin Ke committed
295
  return str_buf.str();
Guolin Ke's avatar
Guolin Ke committed
296
297
298
299
300
301
302
}

void GBDT::ModelsFromString(const std::string& model_str, int num_used_model) {
  // use serialized string to restore this object
  models_.clear();
  std::vector<std::string> lines = Common::Split(model_str.c_str(), '\n');
  size_t i = 0;
Guolin Ke's avatar
Guolin Ke committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320

  // get index of label
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("label_index=");
    if (find_pos != std::string::npos) {
      std::vector<std::string> strs = Common::Split(lines[i].c_str(), '=');
      Common::Atoi(strs[1].c_str(), &label_idx_);
      ++i;
      break;
    } else {
      ++i;
    }
  }
  if (i == lines.size()) {
    Log::Fatal("Model file doesn't contain label index");
    return;
  }

Guolin Ke's avatar
Guolin Ke committed
321
  // get max_feature_idx first
Guolin Ke's avatar
Guolin Ke committed
322
  i = 0;
Guolin Ke's avatar
Guolin Ke committed
323
324
325
326
327
328
329
330
331
332
333
334
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("max_feature_idx=");
    if (find_pos != std::string::npos) {
      std::vector<std::string> strs = Common::Split(lines[i].c_str(), '=');
      Common::Atoi(strs[1].c_str(), &max_feature_idx_);
      ++i;
      break;
    } else {
      ++i;
    }
  }
  if (i == lines.size()) {
335
    Log::Fatal("Model file doesn't contain max_feature_idx");
Guolin Ke's avatar
Guolin Ke committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    return;
  }
  // get sigmoid parameter
  i = 0;
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("sigmoid=");
    if (find_pos != std::string::npos) {
      std::vector<std::string> strs = Common::Split(lines[i].c_str(), '=');
      Common::Atof(strs[1].c_str(), &sigmoid_);
      ++i;
      break;
    } else {
      ++i;
    }
  }
  // if sigmoid doesn't exists
  if (i == lines.size()) {
    sigmoid_ = -1.0;
  }
  // get tree models
  i = 0;
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("Tree=");
    if (find_pos != std::string::npos) {
      ++i;
      int start = static_cast<int>(i);
      while (i < lines.size() && lines[i].find("Tree=") == std::string::npos) { ++i; }
      int end = static_cast<int>(i);
      std::string tree_str = Common::Join(lines, start, end, '\n');
      models_.push_back(new Tree(tree_str));
Guolin Ke's avatar
Guolin Ke committed
366
      if (num_used_model > 0 && models_.size() >= static_cast<size_t>(num_used_model)) {
Guolin Ke's avatar
Guolin Ke committed
367
368
369
370
371
372
373
        break;
      }
    } else {
      ++i;
    }
  }

374
  Log::Info("%d models has been loaded\n", models_.size());
Guolin Ke's avatar
Guolin Ke committed
375
376
}

wxchan's avatar
wxchan committed
377
void GBDT::FeatureImportance(const int last_iter) {
378
  std::vector<size_t> feature_importances(max_feature_idx_ + 1, 0);
wxchan's avatar
wxchan committed
379
    for (int iter = 0; iter < last_iter; ++iter) {
380
381
        for (int split_idx = 0; split_idx < models_[iter]->num_leaves() - 1; ++split_idx) {
            ++feature_importances[models_[iter]->split_feature_real(split_idx)];
wxchan's avatar
wxchan committed
382
383
        }
    }
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
    // store the importance first
    std::vector<std::pair<size_t, std::string>> pairs;
    for (size_t i = 0; i < feature_importances.size(); ++i) {
      pairs.emplace_back(feature_importances[i], train_data_->feature_names()[i]);
    }
    // sort the importance
    std::sort(pairs.begin(), pairs.end(),
      [](const std::pair<size_t, std::string>& lhs,
        const std::pair<size_t, std::string>& rhs) {
      return lhs.first > rhs.first; 
    });
    // write to model file
    fprintf(output_model_file, "\nfeature importances:\n");
    for (size_t i = 0; i < pairs.size(); ++i) {
      fprintf(output_model_file, "%s=%s\n", pairs[i].second.c_str(),
        std::to_string(pairs[i].first).c_str());
    }
wxchan's avatar
wxchan committed
401
402
403
    fflush(output_model_file);
}

Guolin Ke's avatar
Guolin Ke committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
double GBDT::PredictRaw(const double* value) const {
  double ret = 0.0;
  for (size_t i = 0; i < models_.size(); ++i) {
    ret += models_[i]->Predict(value);
  }
  return ret;
}

double GBDT::Predict(const double* value) const {
  double ret = 0.0;
  for (size_t i = 0; i < models_.size(); ++i) {
    ret += models_[i]->Predict(value);
  }
  // if need sigmoid transform
  if (sigmoid_ > 0) {
Guolin Ke's avatar
Guolin Ke committed
419
    ret = 1.0 / (1.0 + std::exp(- 2.0f * sigmoid_ * ret));
Guolin Ke's avatar
Guolin Ke committed
420
421
422
423
  }
  return ret;
}

wxchan's avatar
wxchan committed
424
425
426
427
428
429
430
431
std::vector<int> GBDT::PredictLeafIndex(const double* value) const {
  std::vector<int> ret;
  for (size_t i = 0; i < models_.size(); ++i) {
    ret.push_back(models_[i]->PredictLeafIndex(value));
  }
  return ret;
}

Guolin Ke's avatar
Guolin Ke committed
432
}  // namespace LightGBM