binary_objective.hpp 6.18 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
10
#ifndef LIGHTGBM_OBJECTIVE_BINARY_OBJECTIVE_HPP_
#define LIGHTGBM_OBJECTIVE_BINARY_OBJECTIVE_HPP_

#include <LightGBM/objective_function.h>

#include <cstring>
#include <cmath>

namespace LightGBM {
/*!
11
* \brief Objective function for binary classification
Guolin Ke's avatar
Guolin Ke committed
12
13
14
*/
class BinaryLogloss: public ObjectiveFunction {
public:
15
  explicit BinaryLogloss(const ObjectiveConfig& config, std::function<bool(label_t)> is_pos = nullptr) {
16
    sigmoid_ = static_cast<double>(config.sigmoid);
Guolin Ke's avatar
Guolin Ke committed
17
    if (sigmoid_ <= 0.0) {
18
      Log::Fatal("Sigmoid parameter %f should be greater than zero", sigmoid_);
Guolin Ke's avatar
Guolin Ke committed
19
    }
20
    is_unbalance_ = config.is_unbalance;
21
    scale_pos_weight_ = static_cast<double>(config.scale_pos_weight);
22
    if(is_unbalance_ && std::fabs(scale_pos_weight_ - 1.0f) > 1e-6) {
23
      Log::Fatal("Cannot set is_unbalance and scale_pos_weight at the same time");
24
    }
Guolin Ke's avatar
Guolin Ke committed
25
26
    is_pos_ = is_pos;
    if (is_pos_ == nullptr) {
27
      is_pos_ = [](label_t label) {return label > 0; };
Guolin Ke's avatar
Guolin Ke committed
28
    }
Guolin Ke's avatar
Guolin Ke committed
29
  }
Guolin Ke's avatar
Guolin Ke committed
30

31
32
33
  explicit BinaryLogloss(const std::vector<std::string>& strs) {
    sigmoid_ = -1;
    for (auto str : strs) {
Guolin Ke's avatar
Guolin Ke committed
34
      auto tokens = Common::Split(str.c_str(), ':');
35
36
37
38
39
40
41
42
43
44
45
      if (tokens.size() == 2) {
        if (tokens[0] == std::string("sigmoid")) {
          Common::Atof(tokens[1].c_str(), &sigmoid_);
        }
      }
    }
    if (sigmoid_ <= 0.0) {
      Log::Fatal("Sigmoid parameter %f should be greater than zero", sigmoid_);
    }
  }

Guolin Ke's avatar
Guolin Ke committed
46
  ~BinaryLogloss() {}
Guolin Ke's avatar
Guolin Ke committed
47

Guolin Ke's avatar
Guolin Ke committed
48
49
50
51
52
53
54
  void Init(const Metadata& metadata, data_size_t num_data) override {
    num_data_ = num_data;
    label_ = metadata.label();
    weights_ = metadata.weights();
    data_size_t cnt_positive = 0;
    data_size_t cnt_negative = 0;
    // count for positive and negative samples
55
    #pragma omp parallel for schedule(static) reduction(+:cnt_positive, cnt_negative)
Guolin Ke's avatar
Guolin Ke committed
56
    for (data_size_t i = 0; i < num_data_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
57
      if (is_pos_(label_[i])) {
Guolin Ke's avatar
Guolin Ke committed
58
59
60
61
62
        ++cnt_positive;
      } else {
        ++cnt_negative;
      }
    }
63
    if (cnt_negative == 0 || cnt_positive == 0) {
64
      Log::Warning("Contains only one class");
65
66
67
      // not need to boost.
      num_data_ = 0;
    }
ProtD's avatar
ProtD committed
68
    Log::Info("Number of positive: %d, number of negative: %d", cnt_positive, cnt_negative);
Guolin Ke's avatar
Guolin Ke committed
69
70
71
72
73
74
75
    // use -1 for negative class, and 1 for positive class
    label_val_[0] = -1;
    label_val_[1] = 1;
    // weight for label
    label_weights_[0] = 1.0f;
    label_weights_[1] = 1.0f;
    // if using unbalance, change the labels weight
76
    if (is_unbalance_ && cnt_positive > 0 && cnt_negative > 0) {
77
78
      if (cnt_positive > cnt_negative) {
        label_weights_[1] = 1.0f;
79
        label_weights_[0] = static_cast<double>(cnt_positive) / cnt_negative;
80
      } else {
81
        label_weights_[1] = static_cast<double>(cnt_negative) / cnt_positive;
82
83
        label_weights_[0] = 1.0f;
      }
Guolin Ke's avatar
Guolin Ke committed
84
    }
Guolin Ke's avatar
Guolin Ke committed
85
    label_weights_[1] *= scale_pos_weight_;
Guolin Ke's avatar
Guolin Ke committed
86
87
  }

88
  void GetGradients(const double* score, score_t* gradients, score_t* hessians) const override {
Guolin Ke's avatar
Guolin Ke committed
89
90
91
92
    if (weights_ == nullptr) {
      #pragma omp parallel for schedule(static)
      for (data_size_t i = 0; i < num_data_; ++i) {
        // get label and label weights
Guolin Ke's avatar
Guolin Ke committed
93
        const int is_pos = is_pos_(label_[i]);
Guolin Ke's avatar
Guolin Ke committed
94
95
        const int label = label_val_[is_pos];
        const double label_weight = label_weights_[is_pos];
Guolin Ke's avatar
Guolin Ke committed
96
        // calculate gradients and hessians
97
        const double response = -label * sigmoid_ / (1.0f + std::exp(label * sigmoid_ * score[i]));
98
        const double abs_response = fabs(response);
99
100
        gradients[i] = static_cast<score_t>(response * label_weight);
        hessians[i] = static_cast<score_t>(abs_response * (sigmoid_ - abs_response) * label_weight);
Guolin Ke's avatar
Guolin Ke committed
101
102
103
104
105
      }
    } else {
      #pragma omp parallel for schedule(static)
      for (data_size_t i = 0; i < num_data_; ++i) {
        // get label and label weights
Guolin Ke's avatar
Guolin Ke committed
106
        const int is_pos = is_pos_(label_[i]);
Guolin Ke's avatar
Guolin Ke committed
107
108
        const int label = label_val_[is_pos];
        const double label_weight = label_weights_[is_pos];
Guolin Ke's avatar
Guolin Ke committed
109
        // calculate gradients and hessians
110
        const double response = -label * sigmoid_ / (1.0f + std::exp(label * sigmoid_ * score[i]));
111
        const double abs_response = fabs(response);
112
113
        gradients[i] = static_cast<score_t>(response * label_weight  * weights_[i]);
        hessians[i] = static_cast<score_t>(abs_response * (sigmoid_ - abs_response) * label_weight * weights_[i]);
Guolin Ke's avatar
Guolin Ke committed
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
  
  // implement custom average to boost from (if enabled among options)
  double BoostFromScore() const override {
    double suml = 0.0f;
    double sumw = 0.0f;
    if (weights_ != nullptr) {
      #pragma omp parallel for schedule(static) reduction(+:suml,sumw)
      for (data_size_t i = 0; i < num_data_; ++i) {
        suml += label_[i] * weights_[i];
        sumw += weights_[i];
      }
    } else {
      sumw = static_cast<double>(num_data_);
      #pragma omp parallel for schedule(static) reduction(+:suml)
      for (data_size_t i = 0; i < num_data_; ++i) {
        suml += label_[i];
      }
    }
    double pavg = suml / sumw;
    double initscore = std::log(pavg / (1.0f - pavg)) / sigmoid_;
    Log::Info("[%s:%s]: pavg=%f -> initscore=%f",  GetName(), __func__, pavg, initscore);
    return initscore;
  }
Guolin Ke's avatar
Guolin Ke committed
140

Guolin Ke's avatar
Guolin Ke committed
141
142
  const char* GetName() const override {
    return "binary";
Guolin Ke's avatar
Guolin Ke committed
143
144
  }

Guolin Ke's avatar
Guolin Ke committed
145
146
  void ConvertOutput(const double* input, double* output) const override {
    output[0] = 1.0f / (1.0f + std::exp(-sigmoid_ * input[0]));
147
148
149
150
151
152
153
154
155
156
157
  }

  std::string ToString() const override {
    std::stringstream str_buf;
    str_buf << GetName() << " ";
    str_buf << "sigmoid:" << sigmoid_;
    return str_buf.str();
  }

  bool SkipEmptyClass() const override { return true; }

158
159
  bool NeedAccuratePrediction() const override { return false; }

Guolin Ke's avatar
Guolin Ke committed
160
161
162
163
private:
  /*! \brief Number of data */
  data_size_t num_data_;
  /*! \brief Pointer of label */
164
  const label_t* label_;
Guolin Ke's avatar
Guolin Ke committed
165
166
167
  /*! \brief True if using unbalance training */
  bool is_unbalance_;
  /*! \brief Sigmoid parameter */
168
  double sigmoid_;
Guolin Ke's avatar
Guolin Ke committed
169
170
171
  /*! \brief Values for positive and negative labels */
  int label_val_[2];
  /*! \brief Weights for positive and negative labels */
172
  double label_weights_[2];
Guolin Ke's avatar
Guolin Ke committed
173
  /*! \brief Weights for data */
174
  const label_t* weights_;
175
  double scale_pos_weight_;
176
  std::function<bool(label_t)> is_pos_;
Guolin Ke's avatar
Guolin Ke committed
177
178
179
};

}  // namespace LightGBM
Guolin Ke's avatar
Guolin Ke committed
180
#endif   // LightGBM_OBJECTIVE_BINARY_OBJECTIVE_HPP_