predictor.hpp 6.61 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
28
#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
  * \param is_sigmoid True if need to predict result with sigmoid transform(if needed, like binary classification)
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
33
  Predictor(const Boosting* boosting, bool is_simgoid, bool is_predict_leaf_index, int num_used_model)
    : is_simgoid_(is_simgoid), is_predict_leaf_index_(is_predict_leaf_index),
      num_used_model_(num_used_model) {
Guolin Ke's avatar
Guolin Ke committed
34
35
36
37
38
39
40
    boosting_ = boosting;
    num_features_ = boosting_->MaxFeatureIdx() + 1;
#pragma omp parallel
#pragma omp master
    {
      num_threads_ = omp_get_num_threads();
    }
41
    features_ = new float*[num_threads_];
Guolin Ke's avatar
Guolin Ke committed
42
    for (int i = 0; i < num_threads_; ++i) {
43
      features_[i] = new float[num_features_];
Guolin Ke's avatar
Guolin Ke committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
    }
  }
  /*!
  * \brief Destructor
  */
  ~Predictor() {
    if (features_ != nullptr) {
      for (int i = 0; i < num_threads_; ++i) {
        delete[] features_[i];
      }
      delete[] features_;
    }
  }

  /*!
Qiwei Ye's avatar
Qiwei Ye committed
59
  * \brief prediction for one record, only raw result(without sigmoid transformation)
Guolin Ke's avatar
Guolin Ke committed
60
61
62
  * \param features Feature for this record
  * \return Prediction result
  */
63
  float PredictRawOneLine(const std::vector<std::pair<int, float>>& features) {
Guolin Ke's avatar
Guolin Ke committed
64
    const int tid = PutFeatureValuesToBuffer(features);
Qiwei Ye's avatar
Qiwei Ye committed
65
    // get result without sigmoid transformation
66
    return boosting_->PredictRaw(features_[tid], num_used_model_);
Guolin Ke's avatar
Guolin Ke committed
67
  }
wxchan's avatar
wxchan committed
68
69
70
71
72
73
  
  /*!
  * \brief prediction for one record, only raw result(without sigmoid transformation)
  * \param features Feature for this record
  * \return Predictied leaf index
  */
74
  std::vector<int> PredictLeafIndexOneLine(const std::vector<std::pair<int, float>>& features) {
Guolin Ke's avatar
Guolin Ke committed
75
    const int tid = PutFeatureValuesToBuffer(features);
wxchan's avatar
wxchan committed
76
    // get result for leaf index
77
    return boosting_->PredictLeafIndex(features_[tid], num_used_model_);
wxchan's avatar
wxchan committed
78
  }
Guolin Ke's avatar
Guolin Ke committed
79
80

  /*!
Qiwei Ye's avatar
Qiwei Ye committed
81
82
  * \brief prediction for one record, will use sigmoid transformation if needed(only enabled for binary classification noe)
  * \param features Feature of this record
Guolin Ke's avatar
Guolin Ke committed
83
84
  * \return Prediction result
  */
85
  float PredictOneLine(const std::vector<std::pair<int, float>>& features) {
Guolin Ke's avatar
Guolin Ke committed
86
87
    const int tid = PutFeatureValuesToBuffer(features);
    // get result with sigmoid transform if needed
88
    return boosting_->Predict(features_[tid], num_used_model_);
Guolin Ke's avatar
Guolin Ke committed
89
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) {
Qiwei Ye's avatar
Qiwei Ye committed
106
      Log::Fatal("Predition result file %s doesn't exists", 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) {
Qiwei Ye's avatar
Qiwei Ye committed
111
      Log::Fatal("Recongnizing input data format failed, filename %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, float>>*)> parser_fun;
    float 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, float>>* feature) {
Guolin Ke's avatar
Guolin Ke committed
119
120
121
      parser->ParseOneLine(buffer, feature, &tmp_label);
    };

122
123
124
    std::function<std::string(const std::vector<std::pair<int, float>>&)> predict_fun;
    if (is_predict_leaf_index_) {
      predict_fun = [this](const std::vector<std::pair<int, float>>& features){
wxchan's avatar
wxchan committed
125
126
127
128
129
130
131
132
133
        std::vector<int> predicted_leaf_index = PredictLeafIndexOneLine(features);
        std::stringstream result_ss;
        for (size_t i = 0; i < predicted_leaf_index.size(); ++i){
          if (i > 0) {
            result_ss << '\t';
          }
          result_ss << predicted_leaf_index[i];
        }
        return result_ss.str();  
Guolin Ke's avatar
Guolin Ke committed
134
135
      };
    }
wxchan's avatar
wxchan committed
136
137
    else {
      if (is_simgoid_) {
138
        predict_fun = [this](const std::vector<std::pair<int, float>>& features){
wxchan's avatar
wxchan committed
139
140
141
142
          return std::to_string(PredictOneLine(features));
        };
      } 
      else {
143
        predict_fun = [this](const std::vector<std::pair<int, float>>& features){
wxchan's avatar
wxchan committed
144
145
146
147
          return std::to_string(PredictRawOneLine(features));
        };
      } 
    }
Guolin Ke's avatar
Guolin Ke committed
148
149
150
    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) {
151
      std::vector<std::pair<int, float>> oneline_features;
wxchan's avatar
wxchan committed
152
      std::vector<std::string> pred_result(lines.size(), "");
Guolin Ke's avatar
Guolin Ke committed
153
#pragma omp parallel for schedule(static) private(oneline_features)
154
      for (data_size_t i = 0; i < static_cast<data_size_t>(lines.size()); ++i) {
Guolin Ke's avatar
Guolin Ke committed
155
156
157
158
159
160
161
162
        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
163
        fprintf(result_file, "%s\n", pred_result[i].c_str());
Guolin Ke's avatar
Guolin Ke committed
164
165
      }
    };
Guolin Ke's avatar
Guolin Ke committed
166
    TextReader<data_size_t> predict_data_reader(data_filename, has_header);
Guolin Ke's avatar
Guolin Ke committed
167
168
169
170
171
172
173
    predict_data_reader.ReadAllAndProcessParallel(process_fun);

    fclose(result_file);
    delete parser;
  }

private:
174
  int PutFeatureValuesToBuffer(const std::vector<std::pair<int, float>>& features) {
Guolin Ke's avatar
Guolin Ke committed
175
176
    int tid = omp_get_thread_num();
    // init feature value
177
    std::memset(features_[tid], 0, sizeof(float)*num_features_);
Guolin Ke's avatar
Guolin Ke committed
178
179
180
181
182
183
184
185
    // 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
186
187
188
  /*! \brief Boosting model */
  const Boosting* boosting_;
  /*! \brief Buffer for feature values */
189
  float** features_;
Guolin Ke's avatar
Guolin Ke committed
190
191
192
193
194
195
  /*! \brief Number of features */
  int num_features_;
  /*! \brief True if need to predict result with sigmoid transform */
  bool is_simgoid_;
  /*! \brief Number of threads */
  int num_threads_;
wxchan's avatar
wxchan committed
196
  /*! \brief True if output leaf index instead of prediction score */
197
198
199
  bool is_predict_leaf_index_;
  /*! \brief Number of used model */
  int num_used_model_;
Guolin Ke's avatar
Guolin Ke committed
200
201
202
203
};

}  // namespace LightGBM

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