predictor.hpp 10.6 KB
Newer Older
1
2
3
4
/*!
 * Copyright (c) 2016 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
Guolin Ke's avatar
Guolin Ke committed
5
6
7
8
9
#ifndef LIGHTGBM_PREDICTOR_HPP_
#define LIGHTGBM_PREDICTOR_HPP_

#include <LightGBM/boosting.h>
#include <LightGBM/dataset.h>
10
#include <LightGBM/meta.h>
11
#include <LightGBM/utils/openmp_wrapper.h>
12
#include <LightGBM/utils/text_reader.h>
Guolin Ke's avatar
Guolin Ke committed
13

14
#include <string>
Guolin Ke's avatar
Guolin Ke committed
15
#include <cstdio>
16
#include <cstring>
Guolin Ke's avatar
Guolin Ke committed
17
#include <functional>
18
#include <map>
Guolin Ke's avatar
Guolin Ke committed
19
#include <memory>
20
21
22
#include <unordered_map>
#include <utility>
#include <vector>
Guolin Ke's avatar
Guolin Ke committed
23
24
25
26

namespace LightGBM {

/*!
zhangyafeikimi's avatar
zhangyafeikimi committed
27
* \brief Used to predict data with input model
Guolin Ke's avatar
Guolin Ke committed
28
29
*/
class Predictor {
Nikita Titov's avatar
Nikita Titov committed
30
 public:
Guolin Ke's avatar
Guolin Ke committed
31
32
33
  /*!
  * \brief Constructor
  * \param boosting Input boosting model
Guolin Ke's avatar
Guolin Ke committed
34
  * \param num_iteration Number of boosting round
35
  * \param is_raw_score True if need to predict result with raw score
Guolin Ke's avatar
Guolin Ke committed
36
37
  * \param predict_leaf_index True to output leaf index instead of prediction score
  * \param predict_contrib True to output feature contributions instead of prediction score
Guolin Ke's avatar
Guolin Ke committed
38
  */
Guolin Ke's avatar
Guolin Ke committed
39
  Predictor(Boosting* boosting, int num_iteration,
Guolin Ke's avatar
Guolin Ke committed
40
            bool is_raw_score, bool predict_leaf_index, bool predict_contrib,
41
42
43
44
            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;
45
46
      CHECK(early_stop_freq > 0);
      CHECK(early_stop_margin >= 0);
47
48
49
50
51
52
53
54
55
      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
56
57
58
59
60
    #pragma omp parallel
    #pragma omp master
    {
      num_threads_ = omp_get_num_threads();
    }
Guolin Ke's avatar
Guolin Ke committed
61
    boosting->InitPredict(num_iteration, predict_contrib);
Guolin Ke's avatar
Guolin Ke committed
62
    boosting_ = boosting;
Guolin Ke's avatar
Guolin Ke committed
63
    num_pred_one_row_ = boosting_->NumPredictOneRow(num_iteration, predict_leaf_index, predict_contrib);
64
65
    num_feature_ = boosting_->MaxFeatureIdx() + 1;
    predict_buf_ = std::vector<std::vector<double>>(num_threads_, std::vector<double>(num_feature_, 0.0f));
66
67
    const int kFeatureThreshold = 100000;
    const size_t KSparseThreshold = static_cast<size_t>(0.01 * num_feature_);
Guolin Ke's avatar
Guolin Ke committed
68
    if (predict_leaf_index) {
69
      predict_fun_ = [=](const std::vector<std::pair<int, double>>& features, double* output) {
Guolin Ke's avatar
Guolin Ke committed
70
        int tid = omp_get_thread_num();
Guolin Ke's avatar
Guolin Ke committed
71
72
73
        if (num_feature_ > kFeatureThreshold && features.size() < KSparseThreshold) {
          auto buf = CopyToPredictMap(features);
          boosting_->PredictLeafIndexByMap(buf, output);
74
75
76
77
78
79
        } 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
80
      };
Guolin Ke's avatar
Guolin Ke committed
81
    } else if (predict_contrib) {
82
83
84
        predict_fun_ = [=](const std::vector<std::pair<int, double>>& features, double* output) {
          int tid = omp_get_thread_num();
          CopyToPredictBuffer(predict_buf_[tid].data(), features);
85
86
87
88
          // 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
89
    } else {
Guolin Ke's avatar
Guolin Ke committed
90
      if (is_raw_score) {
91
        predict_fun_ = [=](const std::vector<std::pair<int, double>>& features, double* output) {
Guolin Ke's avatar
Guolin Ke committed
92
          int tid = omp_get_thread_num();
Guolin Ke's avatar
Guolin Ke committed
93
94
95
          if (num_feature_ > kFeatureThreshold && features.size() < KSparseThreshold) {
            auto buf = CopyToPredictMap(features);
            boosting_->PredictRawByMap(buf, output, &early_stop_);
96
97
98
99
100
          } 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
101
102
        };
      } else {
103
        predict_fun_ = [=](const std::vector<std::pair<int, double>>& features, double* output) {
Guolin Ke's avatar
Guolin Ke committed
104
          int tid = omp_get_thread_num();
Guolin Ke's avatar
Guolin Ke committed
105
106
107
          if (num_feature_ > kFeatureThreshold && features.size() < KSparseThreshold) {
            auto buf = CopyToPredictMap(features);
            boosting_->PredictByMap(buf, output, &early_stop_);
108
109
110
111
112
          } 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
113
114
115
        };
      }
    }
Guolin Ke's avatar
Guolin Ke committed
116
  }
117

Guolin Ke's avatar
Guolin Ke committed
118
119
120
121
122
123
  /*!
  * \brief Destructor
  */
  ~Predictor() {
  }

zhangyafeikimi's avatar
zhangyafeikimi committed
124
  inline const PredictFunction& GetPredictFunction() const {
Guolin Ke's avatar
Guolin Ke committed
125
    return predict_fun_;
126
  }
127

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

    if (parser == nullptr) {
142
      Log::Fatal("Could not recognize the data format of data file %s", data_filename);
Guolin Ke's avatar
Guolin Ke committed
143
    }
Guolin Ke's avatar
Guolin Ke committed
144
    if (!header && parser->NumFeatures() != boosting_->MaxFeatureIdx() + 1) {
145
146
      Log::Fatal("The number of features in data (%d) is not the same as it was in training data (%d).", parser->NumFeatures(), boosting_->MaxFeatureIdx() + 1);
    }
Guolin Ke's avatar
Guolin Ke committed
147
    TextReader<data_size_t> predict_data_reader(data_filename, header);
Guolin Ke's avatar
Guolin Ke committed
148
    std::vector<int> feature_remapper(parser->NumFeatures(), -1);
ww's avatar
ww committed
149
    bool need_adjust = false;
Guolin Ke's avatar
Guolin Ke committed
150
    if (header) {
ww's avatar
ww committed
151
      std::string first_line = predict_data_reader.first_line();
Guolin Ke's avatar
Guolin Ke committed
152
      std::vector<std::string> header_words = Common::Split(first_line.c_str(), "\t,");
Guolin Ke's avatar
Guolin Ke committed
153
      std::unordered_map<std::string, int> header_mapper;
Guolin Ke's avatar
Guolin Ke committed
154
      for (int i = 0; i < static_cast<int>(header_words.size()); ++i) {
Guolin Ke's avatar
Guolin Ke committed
155
156
157
158
159
160
161
162
163
164
165
        if (header_mapper.count(header_words[i]) > 0) {
          Log::Fatal("Feature (%s) appears more than one time.", header_words[i].c_str());
        }
        header_mapper[header_words[i]] = i;
      }
      const auto& fnames = boosting_->FeatureNames();
      for (int i = 0; i < static_cast<int>(fnames.size()); ++i) {
        if (header_mapper.count(fnames[i]) <= 0) {
          Log::Warning("Feature (%s) is missed in data file. If it is weight/query/group/ignore_column, you can ignore this warning.", fnames[i].c_str());
        } else {
          feature_remapper[header_mapper.at(fnames[i])] = i;
ww's avatar
ww committed
166
167
        }
      }
Guolin Ke's avatar
Guolin Ke committed
168
169
      for (int i = 0; i < static_cast<int>(feature_remapper.size()); ++i) {
        if (feature_remapper[i] >= 0 && i != feature_remapper[i]) {
ww's avatar
ww committed
170
171
172
173
174
          need_adjust = true;
          break;
        }
      }
    }
Guolin Ke's avatar
Guolin Ke committed
175
    // function for parse data
176
177
    std::function<void(const char*, std::vector<std::pair<int, double>>*)> parser_fun;
    double tmp_label;
178
    parser_fun = [&]
179
    (const char* buffer, std::vector<std::pair<int, double>>* feature) {
Guolin Ke's avatar
Guolin Ke committed
180
      parser->ParseOneLine(buffer, feature, &tmp_label);
Guolin Ke's avatar
Guolin Ke committed
181
      if (need_adjust) {
ww's avatar
ww committed
182
        int i = 0, j = static_cast<int>(feature->size());
Guolin Ke's avatar
Guolin Ke committed
183
        while (i < j) {
Guolin Ke's avatar
Guolin Ke committed
184
185
          if (feature_remapper[(*feature)[i].first] >= 0) {
            (*feature)[i].first = feature_remapper[(*feature)[i].first];
ww's avatar
ww committed
186
            ++i;
Guolin Ke's avatar
Guolin Ke committed
187
          } else {
188
            // move the non-used features to the end of the feature vector
ww's avatar
ww committed
189
190
191
192
193
            std::swap((*feature)[i], (*feature)[--j]);
          }
        }
        feature->resize(i);
      }
Guolin Ke's avatar
Guolin Ke committed
194
195
    };

196
197
    std::function<void(data_size_t, const std::vector<std::string>&)> process_fun = [&]
    (data_size_t, const std::vector<std::string>& lines) {
198
      std::vector<std::pair<int, double>> oneline_features;
199
200
201
      std::vector<std::string> result_to_write(lines.size());
      OMP_INIT_EX();
      #pragma omp parallel for schedule(static) firstprivate(oneline_features)
202
      for (data_size_t i = 0; i < static_cast<data_size_t>(lines.size()); ++i) {
203
        OMP_LOOP_EX_BEGIN();
Guolin Ke's avatar
Guolin Ke committed
204
205
206
207
        oneline_features.clear();
        // parser
        parser_fun(lines[i].c_str(), &oneline_features);
        // predict
Guolin Ke's avatar
Guolin Ke committed
208
209
210
        std::vector<double> result(num_pred_one_row_);
        predict_fun_(oneline_features, result.data());
        auto str_result = Common::Join<double>(result, "\t");
211
212
213
214
215
        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) {
216
217
        writer->Write(result_to_write[i].c_str(), result_to_write[i].size());
        writer->Write("\n", 1);
Guolin Ke's avatar
Guolin Ke committed
218
219
220
221
222
      }
    };
    predict_data_reader.ReadAllAndProcessParallel(process_fun);
  }

Nikita Titov's avatar
Nikita Titov committed
223
 private:
Guolin Ke's avatar
Guolin Ke committed
224
  void CopyToPredictBuffer(double* pred_buf, const std::vector<std::pair<int, double>>& features) {
Guolin Ke's avatar
Guolin Ke committed
225
226
    int loop_size = static_cast<int>(features.size());
    for (int i = 0; i < loop_size; ++i) {
227
228
229
      if (features[i].first < num_feature_) {
        pred_buf[features[i].first] = features[i].second;
      }
230
231
232
    }
  }

Guolin Ke's avatar
Guolin Ke committed
233
  void ClearPredictBuffer(double* pred_buf, size_t buf_size, const std::vector<std::pair<int, double>>& features) {
234
    if (features.size() > static_cast<size_t>(buf_size / 2)) {
Guolin Ke's avatar
Guolin Ke committed
235
      std::memset(pred_buf, 0, sizeof(double)*(buf_size));
236
237
238
    } else {
      int loop_size = static_cast<int>(features.size());
      for (int i = 0; i < loop_size; ++i) {
Guolin Ke's avatar
Guolin Ke committed
239
240
241
        if (features[i].first < num_feature_) {
          pred_buf[features[i].first] = 0.0f;
        }
Guolin Ke's avatar
Guolin Ke committed
242
243
244
      }
    }
  }
245

Guolin Ke's avatar
Guolin Ke committed
246
247
  std::unordered_map<int, double> CopyToPredictMap(const std::vector<std::pair<int, double>>& features) {
    std::unordered_map<int, double> buf;
248
249
250
    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
251
        buf[features[i].first] = features[i].second;
252
253
      }
    }
254
    return buf;
255
256
  }

Guolin Ke's avatar
Guolin Ke committed
257
258
  /*! \brief Boosting model */
  const Boosting* boosting_;
Guolin Ke's avatar
Guolin Ke committed
259
260
  /*! \brief function for prediction */
  PredictFunction predict_fun_;
261
  PredictionEarlyStopInstance early_stop_;
262
  int num_feature_;
Guolin Ke's avatar
Guolin Ke committed
263
  int num_pred_one_row_;
Guolin Ke's avatar
Guolin Ke committed
264
265
  int num_threads_;
  std::vector<std::vector<double>> predict_buf_;
Guolin Ke's avatar
Guolin Ke committed
266
267
268
269
};

}  // namespace LightGBM

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