gbdt_prediction.cpp 1.8 KB
Newer Older
1
2
3
4
5
6
7
8
#include "gbdt.h"

#include <LightGBM/utils/openmp_wrapper.h>

#include <LightGBM/utils/common.h>

#include <LightGBM/objective_function.h>
#include <LightGBM/metric.h>
cbecker's avatar
cbecker committed
9
#include <LightGBM/prediction_early_stop.h>
10
11
12
13
14
15
16
17
18

#include <ctime>

#include <sstream>
#include <chrono>
#include <string>
#include <vector>
#include <utility>

cbecker's avatar
cbecker committed
19
20
21
22
23
24
namespace
{
    /// Singleton used when earlyStop is nullptr in PredictRaw()
    const auto noEarlyStop = LightGBM::createPredictionEarlyStopInstance("none", LightGBM::PredictionEarlyStopConfig());
}

25
26
namespace LightGBM {

cbecker's avatar
cbecker committed
27
28
29
30
void GBDT::PredictRaw(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const {
  if (earlyStop == nullptr)
  {
    earlyStop = &noEarlyStop;
31
32
  }

cbecker's avatar
cbecker committed
33
34
35
  int earlyStopRoundCounter = 0;
  for (int i = 0; i < num_iteration_for_pred_; ++i) {
    // predict all the trees for one iteration
36
    for (int k = 0; k < num_tree_per_iteration_; ++k) {
cbecker's avatar
cbecker committed
37
      output[k] += models_[i * num_tree_per_iteration_ + k]->Predict(features);
38
    }
cbecker's avatar
cbecker committed
39
40
41
42
43
44

    // check early stopping
    ++earlyStopRoundCounter;
    if (earlyStop->roundPeriod == earlyStopRoundCounter) {
      if (earlyStop->callbackFunction(output, num_tree_per_iteration_)) {
        return;
45
      }
cbecker's avatar
cbecker committed
46
      earlyStopRoundCounter = 0;
47
48
    }
  }
cbecker's avatar
cbecker committed
49
50
51
52
53
}

void GBDT::Predict(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const {
  PredictRaw(features, output, earlyStop);

54
55
56
57
58
59
60
61
62
63
64
65
66
  if (objective_function_ != nullptr) {
    objective_function_->ConvertOutput(output, output);
  }
}

void GBDT::PredictLeafIndex(const double* features, double* output) const {
  int total_tree = num_iteration_for_pred_ * num_tree_per_iteration_;
  #pragma omp parallel for schedule(static)
  for (int i = 0; i < total_tree; ++i) {
    output[i] = models_[i]->PredictLeafIndex(features);
  }
}

cbecker's avatar
cbecker committed
67
}  // namespace LightGBM