predictor.hpp 9.96 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
#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>

9
#include <LightGBM/utils/openmp_wrapper.h>
Guolin Ke's avatar
Guolin Ke committed
10

ww's avatar
ww committed
11
#include <map>
Guolin Ke's avatar
Guolin Ke committed
12
13
14
15
16
17
#include <cstring>
#include <cstdio>
#include <vector>
#include <utility>
#include <functional>
#include <string>
Guolin Ke's avatar
Guolin Ke committed
18
#include <memory>
Guolin Ke's avatar
Guolin Ke committed
19
20
21
22

namespace LightGBM {

/*!
zhangyafeikimi's avatar
zhangyafeikimi committed
23
* \brief Used to predict data with input model
Guolin Ke's avatar
Guolin Ke committed
24
25
26
27
28
29
*/
class Predictor {
public:
  /*!
  * \brief Constructor
  * \param boosting Input boosting model
Guolin Ke's avatar
Guolin Ke committed
30
  * \param num_iteration Number of boosting round
31
  * \param is_raw_score True if need to predict result with raw score
32
33
  * \param is_predict_leaf_index True to output leaf index instead of prediction score
  * \param is_predict_contrib True to output feature contributions instead of prediction score
Guolin Ke's avatar
Guolin Ke committed
34
  */
Guolin Ke's avatar
Guolin Ke committed
35
  Predictor(Boosting* boosting, int num_iteration,
36
            bool is_raw_score, bool is_predict_leaf_index, bool is_predict_contrib,
37
38
39
40
41
            bool early_stop, int early_stop_freq, double early_stop_margin) {

    early_stop_ = CreatePredictionEarlyStopInstance("none", LightGBM::PredictionEarlyStopConfig());
    if (early_stop && !boosting->NeedAccuratePrediction()) {
      PredictionEarlyStopConfig pred_early_stop_config;
42
43
      CHECK(early_stop_freq > 0);
      CHECK(early_stop_margin >= 0);
44
45
46
47
48
49
50
51
52
      pred_early_stop_config.margin_threshold = early_stop_margin;
      pred_early_stop_config.round_period = early_stop_freq;
      if (boosting->NumberOfClasses() == 1) {
        early_stop_ = CreatePredictionEarlyStopInstance("binary", pred_early_stop_config);
      } else {
        early_stop_ = CreatePredictionEarlyStopInstance("multiclass", pred_early_stop_config);
      }
    }

Guolin Ke's avatar
Guolin Ke committed
53
54
55
56
57
    #pragma omp parallel
    #pragma omp master
    {
      num_threads_ = omp_get_num_threads();
    }
58
    boosting->InitPredict(num_iteration, is_predict_contrib);
Guolin Ke's avatar
Guolin Ke committed
59
    boosting_ = boosting;
60
    num_pred_one_row_ = boosting_->NumPredictOneRow(num_iteration, is_predict_leaf_index, is_predict_contrib);
61
62
    num_feature_ = boosting_->MaxFeatureIdx() + 1;
    predict_buf_ = std::vector<std::vector<double>>(num_threads_, std::vector<double>(num_feature_, 0.0f));
Guolin Ke's avatar
Guolin Ke committed
63
64
    const int kFeatureThreshold = 20000;
    const size_t KSparseThreshold = static_cast<size_t>(0.02 * num_feature_);
Guolin Ke's avatar
Guolin Ke committed
65
    if (is_predict_leaf_index) {
Guolin Ke's avatar
Guolin Ke committed
66
      predict_fun_ = [this, kFeatureThreshold, KSparseThreshold](const std::vector<std::pair<int, double>>& features, double* output) {
Guolin Ke's avatar
Guolin Ke committed
67
        int tid = omp_get_thread_num();
Guolin Ke's avatar
Guolin Ke committed
68
69
70
        if (num_feature_ > kFeatureThreshold && features.size() < KSparseThreshold) {
          auto buf = CopyToPredictMap(features);
          boosting_->PredictLeafIndexByMap(buf, output);
71
72
73
74
75
76
        } else {
          CopyToPredictBuffer(predict_buf_[tid].data(), features);
          // get result for leaf index
          boosting_->PredictLeafIndex(predict_buf_[tid].data(), output);
          ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features);
        }
Guolin Ke's avatar
Guolin Ke committed
77
      };
78
79
80
81
82
83
84
85
    } else if (is_predict_contrib) {
      predict_fun_ = [this](const std::vector<std::pair<int, double>>& features, double* output) {
        int tid = omp_get_thread_num();
        CopyToPredictBuffer(predict_buf_[tid].data(), features);
        // get result for leaf index
        boosting_->PredictContrib(predict_buf_[tid].data(), output, &early_stop_);
        ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features);
      };
Guolin Ke's avatar
Guolin Ke committed
86
    } else {
Guolin Ke's avatar
Guolin Ke committed
87
      if (is_raw_score) {
Guolin Ke's avatar
Guolin Ke committed
88
        predict_fun_ = [this, kFeatureThreshold, KSparseThreshold](const std::vector<std::pair<int, double>>& features, double* output) {
Guolin Ke's avatar
Guolin Ke committed
89
          int tid = omp_get_thread_num();
Guolin Ke's avatar
Guolin Ke committed
90
91
92
          if (num_feature_ > kFeatureThreshold && features.size() < KSparseThreshold) {
            auto buf = CopyToPredictMap(features);
            boosting_->PredictRawByMap(buf, output, &early_stop_);
93
94
95
96
97
          } else {
            CopyToPredictBuffer(predict_buf_[tid].data(), features);
            boosting_->PredictRaw(predict_buf_[tid].data(), output, &early_stop_);
            ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features);
          }
Guolin Ke's avatar
Guolin Ke committed
98
99
        };
      } else {
Guolin Ke's avatar
Guolin Ke committed
100
        predict_fun_ = [this, kFeatureThreshold, KSparseThreshold](const std::vector<std::pair<int, double>>& features, double* output) {
Guolin Ke's avatar
Guolin Ke committed
101
          int tid = omp_get_thread_num();
Guolin Ke's avatar
Guolin Ke committed
102
103
104
          if (num_feature_ > kFeatureThreshold && features.size() < KSparseThreshold) {
            auto buf = CopyToPredictMap(features);
            boosting_->PredictByMap(buf, output, &early_stop_);
105
106
107
108
109
          } else {
            CopyToPredictBuffer(predict_buf_[tid].data(), features);
            boosting_->Predict(predict_buf_[tid].data(), output, &early_stop_);
            ClearPredictBuffer(predict_buf_[tid].data(), predict_buf_[tid].size(), features);
          }
Guolin Ke's avatar
Guolin Ke committed
110
111
112
        };
      }
    }
Guolin Ke's avatar
Guolin Ke committed
113
  }
114

Guolin Ke's avatar
Guolin Ke committed
115
116
117
118
119
120
  /*!
  * \brief Destructor
  */
  ~Predictor() {
  }

zhangyafeikimi's avatar
zhangyafeikimi committed
121
  inline const PredictFunction& GetPredictFunction() const {
Guolin Ke's avatar
Guolin Ke committed
122
    return predict_fun_;
123
  }
124

Guolin Ke's avatar
Guolin Ke committed
125
  /*!
Qiwei Ye's avatar
Qiwei Ye committed
126
  * \brief predicting on data, then saving result to disk
Guolin Ke's avatar
Guolin Ke committed
127
128
129
  * \param data_filename Filename of data
  * \param result_filename Filename of output result
  */
Guolin Ke's avatar
Guolin Ke committed
130
  void Predict(const char* data_filename, const char* result_filename, bool has_header) {
131
132
    auto writer = VirtualFileWriter::Make(result_filename);
    if (!writer->Init()) {
Qiwei Ye's avatar
Qiwei Ye committed
133
      Log::Fatal("Prediction results file %s cannot be found.", result_filename);
Guolin Ke's avatar
Guolin Ke committed
134
    }
135
    auto parser = std::unique_ptr<Parser>(Parser::CreateParser(data_filename, has_header, boosting_->MaxFeatureIdx() + 1, boosting_->LabelIdx()));
Guolin Ke's avatar
Guolin Ke committed
136
137

    if (parser == nullptr) {
Qiwei Ye's avatar
Qiwei Ye committed
138
      Log::Fatal("Could not recognize the data format of data file %s.", data_filename);
Guolin Ke's avatar
Guolin Ke committed
139
140
    }

ww's avatar
ww committed
141
142
143
    TextReader<data_size_t> predict_data_reader(data_filename, has_header);
    std::unordered_map<int, int> feature_names_map_;
    bool need_adjust = false;
Guolin Ke's avatar
Guolin Ke committed
144
    if (has_header) {
ww's avatar
ww committed
145
146
147
      std::string first_line = predict_data_reader.first_line();
      std::vector<std::string> header = Common::Split(first_line.c_str(), "\t,");
      header.erase(header.begin() + boosting_->LabelIdx());
Guolin Ke's avatar
Guolin Ke committed
148
149
150
      for (int i = 0; i < static_cast<int>(header.size()); ++i) {
        for (int j = 0; j < static_cast<int>(boosting_->FeatureNames().size()); ++j) {
          if (header[i] == boosting_->FeatureNames()[j]) {
ww's avatar
ww committed
151
152
153
154
155
            feature_names_map_[i] = j;
            break;
          }
        }
      }
Guolin Ke's avatar
Guolin Ke committed
156
157
      for (auto s : feature_names_map_) {
        if (s.first != s.second) {
ww's avatar
ww committed
158
159
160
161
162
          need_adjust = true;
          break;
        }
      }
    }
Guolin Ke's avatar
Guolin Ke committed
163
    // function for parse data
164
165
    std::function<void(const char*, std::vector<std::pair<int, double>>*)> parser_fun;
    double tmp_label;
ww's avatar
ww committed
166
    parser_fun = [this, &parser, &tmp_label, &need_adjust, &feature_names_map_]
167
    (const char* buffer, std::vector<std::pair<int, double>>* feature) {
Guolin Ke's avatar
Guolin Ke committed
168
      parser->ParseOneLine(buffer, feature, &tmp_label);
Guolin Ke's avatar
Guolin Ke committed
169
      if (need_adjust) {
ww's avatar
ww committed
170
        int i = 0, j = static_cast<int>(feature->size());
Guolin Ke's avatar
Guolin Ke committed
171
172
        while (i < j) {
          if (feature_names_map_.find((*feature)[i].first) != feature_names_map_.end()) {
ww's avatar
ww committed
173
174
            (*feature)[i].first = feature_names_map_[(*feature)[i].first];
            ++i;
Guolin Ke's avatar
Guolin Ke committed
175
          } else {
ww's avatar
ww committed
176
177
178
179
180
181
            //move the non-used features to the end of the feature vector
            std::swap((*feature)[i], (*feature)[--j]);
          }
        }
        feature->resize(i);
      }
Guolin Ke's avatar
Guolin Ke committed
182
183
    };

Guolin Ke's avatar
Guolin Ke committed
184
    std::function<void(data_size_t, const std::vector<std::string>&)> process_fun =
185
      [this, &parser_fun, &writer]
Guolin Ke's avatar
Guolin Ke committed
186
    (data_size_t, const std::vector<std::string>& lines) {
187
      std::vector<std::pair<int, double>> oneline_features;
188
189
190
      std::vector<std::string> result_to_write(lines.size());
      OMP_INIT_EX();
      #pragma omp parallel for schedule(static) firstprivate(oneline_features)
191
      for (data_size_t i = 0; i < static_cast<data_size_t>(lines.size()); ++i) {
192
        OMP_LOOP_EX_BEGIN();
Guolin Ke's avatar
Guolin Ke committed
193
194
195
196
        oneline_features.clear();
        // parser
        parser_fun(lines[i].c_str(), &oneline_features);
        // predict
Guolin Ke's avatar
Guolin Ke committed
197
198
199
        std::vector<double> result(num_pred_one_row_);
        predict_fun_(oneline_features, result.data());
        auto str_result = Common::Join<double>(result, "\t");
200
201
202
203
204
        result_to_write[i] = str_result;
        OMP_LOOP_EX_END();
      }
      OMP_THROW_EX();
      for (data_size_t i = 0; i < static_cast<data_size_t>(result_to_write.size()); ++i) {
205
206
        writer->Write(result_to_write[i].c_str(), result_to_write[i].size());
        writer->Write("\n", 1);
Guolin Ke's avatar
Guolin Ke committed
207
208
209
210
211
212
      }
    };
    predict_data_reader.ReadAllAndProcessParallel(process_fun);
  }

private:
213

Guolin Ke's avatar
Guolin Ke committed
214
  void CopyToPredictBuffer(double* pred_buf, const std::vector<std::pair<int, double>>& features) {
Guolin Ke's avatar
Guolin Ke committed
215
216
    int loop_size = static_cast<int>(features.size());
    for (int i = 0; i < loop_size; ++i) {
217
218
219
      if (features[i].first < num_feature_) {
        pred_buf[features[i].first] = features[i].second;
      }
220
221
222
    }
  }

Guolin Ke's avatar
Guolin Ke committed
223
224
225
  void ClearPredictBuffer(double* pred_buf, size_t buf_size, const std::vector<std::pair<int, double>>& features) {
    if (features.size() < static_cast<size_t>(buf_size / 2)) {
      std::memset(pred_buf, 0, sizeof(double)*(buf_size));
226
227
228
    } else {
      int loop_size = static_cast<int>(features.size());
      for (int i = 0; i < loop_size; ++i) {
Guolin Ke's avatar
Guolin Ke committed
229
230
231
        if (features[i].first < num_feature_) {
          pred_buf[features[i].first] = 0.0f;
        }
Guolin Ke's avatar
Guolin Ke committed
232
233
234
      }
    }
  }
235

Guolin Ke's avatar
Guolin Ke committed
236
237
  std::unordered_map<int, double> CopyToPredictMap(const std::vector<std::pair<int, double>>& features) {
    std::unordered_map<int, double> buf;
238
239
240
    int loop_size = static_cast<int>(features.size());
    for (int i = 0; i < loop_size; ++i) {
      if (features[i].first < num_feature_) {
Guolin Ke's avatar
Guolin Ke committed
241
        buf[features[i].first] = features[i].second;
242
243
      }
    }
Guolin Ke's avatar
Guolin Ke committed
244
    return std::move(buf);
245
246
  }

Guolin Ke's avatar
Guolin Ke committed
247
248
  /*! \brief Boosting model */
  const Boosting* boosting_;
Guolin Ke's avatar
Guolin Ke committed
249
250
  /*! \brief function for prediction */
  PredictFunction predict_fun_;
251
  PredictionEarlyStopInstance early_stop_;
252
  int num_feature_;
Guolin Ke's avatar
Guolin Ke committed
253
  int num_pred_one_row_;
Guolin Ke's avatar
Guolin Ke committed
254
255
  int num_threads_;
  std::vector<std::vector<double>> predict_buf_;
Guolin Ke's avatar
Guolin Ke committed
256
257
258
259
};

}  // namespace LightGBM

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