binary_metric.hpp 6.98 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
#ifndef LIGHTGBM_METRIC_BINARY_METRIC_HPP_
#define LIGHTGBM_METRIC_BINARY_METRIC_HPP_

#include <LightGBM/utils/log.h>

#include <LightGBM/metric.h>

#include <algorithm>
#include <vector>
10
#include <sstream>
Guolin Ke's avatar
Guolin Ke committed
11
12
13
14
15
16
17
18
19
20
21
22
23

namespace LightGBM {

/*!
* \brief Metric for binary classification task.
* Use static class "PointWiseLossCalculator" to calculate loss point-wise
*/
template<typename PointWiseLossCalculator>
class BinaryMetric: public Metric {
public:
  explicit BinaryMetric(const MetricConfig& config) {
    sigmoid_ = static_cast<score_t>(config.sigmoid);
    if (sigmoid_ <= 0.0f) {
24
      Log::Fatal("Sigmoid parameter %f should greater than zero", sigmoid_);
Guolin Ke's avatar
Guolin Ke committed
25
26
27
28
29
30
31
32
    }
  }

  virtual ~BinaryMetric() {

  }

  void Init(const char* test_name, const Metadata& metadata, data_size_t num_data) override {
33

34
    std::stringstream str_buf;
35
36
37
    str_buf << test_name << "'s : " << PointWiseLossCalculator::Name();
    name_.emplace_back(str_buf.str());

Guolin Ke's avatar
Guolin Ke committed
38
39
40
41
42
43
44
45
    num_data_ = num_data;
    // get label
    label_ = metadata.label();

    // get weights
    weights_ = metadata.weights();

    if (weights_ == nullptr) {
46
      sum_weights_ = static_cast<double>(num_data_);
Guolin Ke's avatar
Guolin Ke committed
47
48
49
50
51
52
53
54
    } else {
      sum_weights_ = 0.0f;
      for (data_size_t i = 0; i < num_data; ++i) {
        sum_weights_ += weights_[i];
      }
    }
  }

55
56
  std::vector<std::string> GetName() const override {
    return name_;
57
58
  }

59
60
  score_t factor_to_bigger_better() const override {
    return -1.0f;
61
62
  }

63
64
  std::vector<double> Eval(const score_t* score) const override {
    double sum_loss = 0.0f;
65
66
67
68
69
70
71
    if (weights_ == nullptr) {
#pragma omp parallel for schedule(static) reduction(+:sum_loss)
      for (data_size_t i = 0; i < num_data_; ++i) {
        // sigmoid transform
        score_t prob = 1.0f / (1.0f + std::exp(-2.0f * sigmoid_ * score[i]));
        // add loss
        sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], prob);
Guolin Ke's avatar
Guolin Ke committed
72
      }
73
74
75
76
77
78
79
    } else {
#pragma omp parallel for schedule(static) reduction(+:sum_loss)
      for (data_size_t i = 0; i < num_data_; ++i) {
        // sigmoid transform
        score_t prob = 1.0f / (1.0f + std::exp(-2.0f * sigmoid_ * score[i]));
        // add loss
        sum_loss += PointWiseLossCalculator::LossOnPoint(label_[i], prob) * weights_[i];
wxchan's avatar
wxchan committed
80
      }
Guolin Ke's avatar
Guolin Ke committed
81
    }
82
83
    double loss = sum_loss / sum_weights_;
    return std::vector<double>(1, loss);
Guolin Ke's avatar
Guolin Ke committed
84
85
86
87
88
89
90
91
92
93
  }

private:
  /*! \brief Number of data */
  data_size_t num_data_;
  /*! \brief Pointer of label */
  const float* label_;
  /*! \brief Pointer of weighs */
  const float* weights_;
  /*! \brief Sum weights */
94
  double sum_weights_;
Guolin Ke's avatar
Guolin Ke committed
95
  /*! \brief Name of test set */
96
  std::vector<std::string> name_;
Guolin Ke's avatar
Guolin Ke committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
  /*! \brief Sigmoid parameter */
  score_t sigmoid_;
};

/*!
* \brief Log loss metric for binary classification task.
*/
class BinaryLoglossMetric: public BinaryMetric<BinaryLoglossMetric> {
public:
  explicit BinaryLoglossMetric(const MetricConfig& config) :BinaryMetric<BinaryLoglossMetric>(config) {}

  inline static score_t LossOnPoint(float label, score_t prob) {
    if (label == 0) {
      if (1.0f - prob > kEpsilon) {
        return -std::log(1.0f - prob);
      }
    } else {
      if (prob > kEpsilon) {
        return -std::log(prob);
      }
    }
    return -std::log(kEpsilon);
  }

  inline static const char* Name() {
    return "log loss";
  }
};
/*!
* \brief Error rate metric for binary classification task.
*/
class BinaryErrorMetric: public BinaryMetric<BinaryErrorMetric> {
public:
  explicit BinaryErrorMetric(const MetricConfig& config) :BinaryMetric<BinaryErrorMetric>(config) {}

  inline static score_t LossOnPoint(float label, score_t prob) {
    if (prob < 0.5f) {
      return label;
    } else {
      return 1.0f - label;
    }
  }

  inline static const char* Name() {
    return "error rate";
  }
};

/*!
* \brief Auc Metric for binary classification task.
*/
class AUCMetric: public Metric {
public:
150
151
  explicit AUCMetric(const MetricConfig&) {

Guolin Ke's avatar
Guolin Ke committed
152
153
154
155
156
  }

  virtual ~AUCMetric() {
  }

157
158
  std::vector<std::string> GetName() const override {
    return name_;
159
160
  }

161
162
  score_t factor_to_bigger_better() const override {
    return 1.0f;
163
164
  }

Guolin Ke's avatar
Guolin Ke committed
165
  void Init(const char* test_name, const Metadata& metadata, data_size_t num_data) override {
166
    std::stringstream str_buf;
167
168
    str_buf << test_name << "'s : AUC";
    name_.emplace_back(str_buf.str());
169

Guolin Ke's avatar
Guolin Ke committed
170
171
172
173
174
175
176
    num_data_ = num_data;
    // get label
    label_ = metadata.label();
    // get weights
    weights_ = metadata.weights();

    if (weights_ == nullptr) {
177
      sum_weights_ = static_cast<double>(num_data_);
Guolin Ke's avatar
Guolin Ke committed
178
179
180
181
182
183
184
185
    } else {
      sum_weights_ = 0.0f;
      for (data_size_t i = 0; i < num_data; ++i) {
        sum_weights_ += weights_[i];
      }
    }
  }

186
  std::vector<double> Eval(const score_t* score) const override {
187
188
189
190
191
192
193
    // get indices sorted by score, descent order
    std::vector<data_size_t> sorted_idx;
    for (data_size_t i = 0; i < num_data_; ++i) {
      sorted_idx.emplace_back(i);
    }
    std::sort(sorted_idx.begin(), sorted_idx.end(), [score](data_size_t a, data_size_t b) {return score[a] > score[b]; });
    // temp sum of postive label
194
    double cur_pos = 0.0f;
195
    // total sum of postive label
196
    double sum_pos = 0.0f;
197
    // accumlate of auc
198
    double accum = 0.0f;
199
    // temp sum of negative label
200
    double cur_neg = 0.0f;
201
202
    score_t threshold = score[sorted_idx[0]];
    if (weights_ == nullptr) {  // no weights
Guolin Ke's avatar
Guolin Ke committed
203
      for (data_size_t i = 0; i < num_data_; ++i) {
204
205
206
207
208
209
210
211
212
213
        const float cur_label = label_[sorted_idx[i]];
        const score_t cur_score = score[sorted_idx[i]];
        // new threshold
        if (cur_score != threshold) {
          threshold = cur_score;
          // accmulate
          accum += cur_neg*(cur_pos * 0.5f + sum_pos);
          sum_pos += cur_pos;
          // reset
          cur_neg = cur_pos = 0.0f;
Guolin Ke's avatar
Guolin Ke committed
214
        }
215
216
        cur_neg += 1.0f - cur_label;
        cur_pos += cur_label;
Guolin Ke's avatar
Guolin Ke committed
217
      }
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    } else {  // has weights
      for (data_size_t i = 0; i < num_data_; ++i) {
        const float cur_label = label_[sorted_idx[i]];
        const score_t cur_score = score[sorted_idx[i]];
        const float cur_weight = weights_[sorted_idx[i]];
        // new threshold
        if (cur_score != threshold) {
          threshold = cur_score;
          // accmulate
          accum += cur_neg*(cur_pos * 0.5f + sum_pos);
          sum_pos += cur_pos;
          // reset
          cur_neg = cur_pos = 0.0f;
        }
        cur_neg += (1.0f - cur_label)*cur_weight;
        cur_pos += cur_label*cur_weight;
wxchan's avatar
wxchan committed
234
      }
Guolin Ke's avatar
Guolin Ke committed
235
    }
236
237
    accum += cur_neg*(cur_pos * 0.5f + sum_pos);
    sum_pos += cur_pos;
238
    double auc = 1.0f;
239
240
241
    if (sum_pos > 0.0f && sum_pos != sum_weights_) {
      auc = accum / (sum_pos *(sum_weights_ - sum_pos));
    }
242
    return std::vector<double>(1, auc);
Guolin Ke's avatar
Guolin Ke committed
243
244
245
246
247
248
249
250
251
252
  }

private:
  /*! \brief Number of data */
  data_size_t num_data_;
  /*! \brief Pointer of label */
  const float* label_;
  /*! \brief Pointer of weighs */
  const float* weights_;
  /*! \brief Sum weights */
253
  double sum_weights_;
Guolin Ke's avatar
Guolin Ke committed
254
  /*! \brief Name of test set */
255
  std::vector<std::string> name_;
Guolin Ke's avatar
Guolin Ke committed
256
257
258
};

}  // namespace LightGBM
Guolin Ke's avatar
Guolin Ke committed
259
#endif   // LightGBM_METRIC_BINARY_METRIC_HPP_