predictor.hpp 6.22 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#ifndef LIGHTGBM_PREDICTOR_HPP_
#define LIGHTGBM_PREDICTOR_HPP_

#include <LightGBM/meta.h>
#include <LightGBM/boosting.h>
#include <LightGBM/utils/text_reader.h>
#include <LightGBM/dataset.h>

#include <omp.h>

#include <cstring>
#include <cstdio>
#include <vector>
#include <utility>
#include <functional>
#include <string>

namespace LightGBM {

/*!
* \brief Used to prediction data with input model
*/
class Predictor {
public:
  /*!
  * \brief Constructor
  * \param boosting Input boosting model
28
  * \param is_raw_score True if need to predict result with raw score
wxchan's avatar
wxchan committed
29
  * \param predict_leaf_index True if output leaf index instead of prediction score
Guolin Ke's avatar
Guolin Ke committed
30
  */
31
32
  Predictor(const Boosting* boosting, bool is_raw_score, bool is_predict_leaf_index)
    : is_raw_score_(is_raw_score), is_predict_leaf_index_(is_predict_leaf_index) {
Guolin Ke's avatar
Guolin Ke committed
33
34
35
36
37
38
39
    boosting_ = boosting;
    num_features_ = boosting_->MaxFeatureIdx() + 1;
#pragma omp parallel
#pragma omp master
    {
      num_threads_ = omp_get_num_threads();
    }
40
    features_ = new double*[num_threads_];
Guolin Ke's avatar
Guolin Ke committed
41
    for (int i = 0; i < num_threads_; ++i) {
42
      features_[i] = new double[num_features_];
Guolin Ke's avatar
Guolin Ke committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    }
  }
  /*!
  * \brief Destructor
  */
  ~Predictor() {
    if (features_ != nullptr) {
      for (int i = 0; i < num_threads_; ++i) {
        delete[] features_[i];
      }
      delete[] features_;
    }
  }

  /*!
58
  * \brief prediction for one record, only raw result (without sigmoid transformation)
Guolin Ke's avatar
Guolin Ke committed
59
60
61
  * \param features Feature for this record
  * \return Prediction result
  */
62
  std::vector<double> PredictRawOneLine(const std::vector<std::pair<int, double>>& features) {
Guolin Ke's avatar
Guolin Ke committed
63
    const int tid = PutFeatureValuesToBuffer(features);
Qiwei Ye's avatar
Qiwei Ye committed
64
    // get result without sigmoid transformation
65
    return boosting_->PredictRaw(features_[tid]);
Guolin Ke's avatar
Guolin Ke committed
66
  }
67

wxchan's avatar
wxchan committed
68
  /*!
69
  * \brief prediction for one record, only raw result (without sigmoid transformation)
wxchan's avatar
wxchan committed
70
71
72
  * \param features Feature for this record
  * \return Predictied leaf index
  */
73
  std::vector<int> PredictLeafIndexOneLine(const std::vector<std::pair<int, double>>& features) {
Guolin Ke's avatar
Guolin Ke committed
74
    const int tid = PutFeatureValuesToBuffer(features);
wxchan's avatar
wxchan committed
75
    // get result for leaf index
76
    return boosting_->PredictLeafIndex(features_[tid]);
wxchan's avatar
wxchan committed
77
  }
Guolin Ke's avatar
Guolin Ke committed
78
79

  /*!
80
  * \brief prediction for one record, will use sigmoid transformation if needed (only enabled for binary classification noe)
Qiwei Ye's avatar
Qiwei Ye committed
81
  * \param features Feature of this record
Guolin Ke's avatar
Guolin Ke committed
82
83
  * \return Prediction result
  */
84
  std::vector<double> PredictOneLine(const std::vector<std::pair<int, double>>& features) {
Guolin Ke's avatar
Guolin Ke committed
85
86
    const int tid = PutFeatureValuesToBuffer(features);
    // get result with sigmoid transform if needed
87
    return boosting_->Predict(features_[tid]);
88
  }
89

Guolin Ke's avatar
Guolin Ke committed
90
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
91
  * \brief predicting on data, then saving result to disk
Guolin Ke's avatar
Guolin Ke committed
92
93
94
95
  * \param data_filename Filename of data
  * \param has_label True if this data contains label
  * \param result_filename Filename of output result
  */
Guolin Ke's avatar
Guolin Ke committed
96
  void Predict(const char* data_filename, const char* result_filename, bool has_header) {
Guolin Ke's avatar
Guolin Ke committed
97
98
99
100
101
102
103
104
105
    FILE* result_file;

#ifdef _MSC_VER
    fopen_s(&result_file, result_filename, "w");
#else
    result_file = fopen(result_filename, "w");
#endif

    if (result_file == NULL) {
106
      Log::Fatal("Prediction results file %s doesn't exist", data_filename);
Guolin Ke's avatar
Guolin Ke committed
107
    }
Guolin Ke's avatar
Guolin Ke committed
108
    Parser* parser = Parser::CreateParser(data_filename, has_header, num_features_, boosting_->LabelIdx());
Guolin Ke's avatar
Guolin Ke committed
109
110

    if (parser == nullptr) {
111
      Log::Fatal("Could not recognize the data format of data file %s", data_filename);
Guolin Ke's avatar
Guolin Ke committed
112
113
114
    }

    // function for parse data
115
116
    std::function<void(const char*, std::vector<std::pair<int, double>>*)> parser_fun;
    double tmp_label;
Guolin Ke's avatar
Guolin Ke committed
117
    parser_fun = [this, &parser, &tmp_label]
118
    (const char* buffer, std::vector<std::pair<int, double>>* feature) {
Guolin Ke's avatar
Guolin Ke committed
119
120
121
      parser->ParseOneLine(buffer, feature, &tmp_label);
    };

122
    std::function<std::string(const std::vector<std::pair<int, double>>&)> predict_fun;
123
    if (is_predict_leaf_index_) {
124
      predict_fun = [this](const std::vector<std::pair<int, double>>& features){
125
        return Common::Join<int>(PredictLeafIndexOneLine(features), '\t');
Guolin Ke's avatar
Guolin Ke committed
126
127
      };
    }
wxchan's avatar
wxchan committed
128
    else {
129
      if (is_raw_score_) {
130
        predict_fun = [this](const std::vector<std::pair<int, double>>& features){
131
          return Common::Join<double>(PredictRawOneLine(features), '\t');
wxchan's avatar
wxchan committed
132
        };
133
      }
wxchan's avatar
wxchan committed
134
      else {
135
        predict_fun = [this](const std::vector<std::pair<int, double>>& features){
136
          return Common::Join<double>(PredictOneLine(features), '\t');
wxchan's avatar
wxchan committed
137
        };
138
      }
wxchan's avatar
wxchan committed
139
    }
Guolin Ke's avatar
Guolin Ke committed
140
141
142
    std::function<void(data_size_t, const std::vector<std::string>&)> process_fun =
      [this, &parser_fun, &predict_fun, &result_file]
    (data_size_t, const std::vector<std::string>& lines) {
143
      std::vector<std::pair<int, double>> oneline_features;
wxchan's avatar
wxchan committed
144
      std::vector<std::string> pred_result(lines.size(), "");
Guolin Ke's avatar
Guolin Ke committed
145
#pragma omp parallel for schedule(static) private(oneline_features)
146
      for (data_size_t i = 0; i < static_cast<data_size_t>(lines.size()); ++i) {
Guolin Ke's avatar
Guolin Ke committed
147
148
149
150
151
152
153
154
        oneline_features.clear();
        // parser
        parser_fun(lines[i].c_str(), &oneline_features);
        // predict
        pred_result[i] = predict_fun(oneline_features);
      }

      for (size_t i = 0; i < pred_result.size(); ++i) {
wxchan's avatar
wxchan committed
155
        fprintf(result_file, "%s\n", pred_result[i].c_str());
Guolin Ke's avatar
Guolin Ke committed
156
157
      }
    };
Guolin Ke's avatar
Guolin Ke committed
158
    TextReader<data_size_t> predict_data_reader(data_filename, has_header);
Guolin Ke's avatar
Guolin Ke committed
159
160
161
162
163
164
165
    predict_data_reader.ReadAllAndProcessParallel(process_fun);

    fclose(result_file);
    delete parser;
  }

private:
166
  int PutFeatureValuesToBuffer(const std::vector<std::pair<int, double>>& features) {
Guolin Ke's avatar
Guolin Ke committed
167
168
    int tid = omp_get_thread_num();
    // init feature value
169
    std::memset(features_[tid], 0, sizeof(double)*num_features_);
Guolin Ke's avatar
Guolin Ke committed
170
171
172
173
174
175
176
177
    // put feature value
    for (const auto& p : features) {
      if (p.first < num_features_) {
        features_[tid][p.first] = p.second;
      }
    }
    return tid;
  }
Guolin Ke's avatar
Guolin Ke committed
178
179
180
  /*! \brief Boosting model */
  const Boosting* boosting_;
  /*! \brief Buffer for feature values */
181
  double** features_;
Guolin Ke's avatar
Guolin Ke committed
182
183
184
  /*! \brief Number of features */
  int num_features_;
  /*! \brief True if need to predict result with sigmoid transform */
185
  bool is_raw_score_;
Guolin Ke's avatar
Guolin Ke committed
186
187
  /*! \brief Number of threads */
  int num_threads_;
wxchan's avatar
wxchan committed
188
  /*! \brief True if output leaf index instead of prediction score */
189
  bool is_predict_leaf_index_;
Guolin Ke's avatar
Guolin Ke committed
190
191
192
193
};

}  // namespace LightGBM

Guolin Ke's avatar
Guolin Ke committed
194
#endif   // LightGBM_PREDICTOR_HPP_