binary_objective.hpp 7.05 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
#ifndef LIGHTGBM_OBJECTIVE_BINARY_OBJECTIVE_HPP_
#define LIGHTGBM_OBJECTIVE_BINARY_OBJECTIVE_HPP_

8
9
10
#include <LightGBM/network.h>
#include <LightGBM/objective_function.h>

11
12
#include <string>
#include <algorithm>
Guolin Ke's avatar
Guolin Ke committed
13
#include <cmath>
14
15
#include <cstring>
#include <vector>
Guolin Ke's avatar
Guolin Ke committed
16
17
18

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

39
40
41
  explicit BinaryLogloss(const std::vector<std::string>& strs) {
    sigmoid_ = -1;
    for (auto str : strs) {
Guolin Ke's avatar
Guolin Ke committed
42
      auto tokens = Common::Split(str.c_str(), ':');
43
44
45
46
47
48
49
50
51
52
53
      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
54
  ~BinaryLogloss() {}
Guolin Ke's avatar
Guolin Ke committed
55

Guolin Ke's avatar
Guolin Ke committed
56
57
58
59
60
61
62
  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
63
    #pragma omp parallel for schedule(static) reduction(+:cnt_positive, cnt_negative)
Guolin Ke's avatar
Guolin Ke committed
64
    for (data_size_t i = 0; i < num_data_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
65
      if (is_pos_(label_[i])) {
Guolin Ke's avatar
Guolin Ke committed
66
67
68
69
70
        ++cnt_positive;
      } else {
        ++cnt_negative;
      }
    }
71
72
73
74
75
    num_pos_data_ = cnt_positive;
    if (Network::num_machines() > 1) {
      cnt_positive = Network::GlobalSyncUpBySum(cnt_positive);
      cnt_negative = Network::GlobalSyncUpBySum(cnt_negative);
    }
76
    need_train_ = true;
77
    if (cnt_negative == 0 || cnt_positive == 0) {
78
      Log::Warning("Contains only one class");
79
      // not need to boost.
80
      need_train_ = false;
81
    }
ProtD's avatar
ProtD committed
82
    Log::Info("Number of positive: %d, number of negative: %d", cnt_positive, cnt_negative);
Guolin Ke's avatar
Guolin Ke committed
83
84
85
86
87
88
89
    // 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
90
    if (is_unbalance_ && cnt_positive > 0 && cnt_negative > 0) {
91
92
      if (cnt_positive > cnt_negative) {
        label_weights_[1] = 1.0f;
93
        label_weights_[0] = static_cast<double>(cnt_positive) / cnt_negative;
94
      } else {
95
        label_weights_[1] = static_cast<double>(cnt_negative) / cnt_positive;
96
97
        label_weights_[0] = 1.0f;
      }
Guolin Ke's avatar
Guolin Ke committed
98
    }
Guolin Ke's avatar
Guolin Ke committed
99
    label_weights_[1] *= scale_pos_weight_;
Guolin Ke's avatar
Guolin Ke committed
100
101
  }

102
  void GetGradients(const double* score, score_t* gradients, score_t* hessians) const override {
103
104
105
    if (!need_train_) {
      return;
    }
Guolin Ke's avatar
Guolin Ke committed
106
107
108
109
    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
110
        const int is_pos = is_pos_(label_[i]);
Guolin Ke's avatar
Guolin Ke committed
111
112
        const int label = label_val_[is_pos];
        const double label_weight = label_weights_[is_pos];
Guolin Ke's avatar
Guolin Ke committed
113
        // calculate gradients and hessians
114
        const double response = -label * sigmoid_ / (1.0f + std::exp(label * sigmoid_ * score[i]));
115
        const double abs_response = fabs(response);
116
117
        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
118
119
120
121
122
      }
    } 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
123
        const int is_pos = is_pos_(label_[i]);
Guolin Ke's avatar
Guolin Ke committed
124
125
        const int label = label_val_[is_pos];
        const double label_weight = label_weights_[is_pos];
Guolin Ke's avatar
Guolin Ke committed
126
        // calculate gradients and hessians
127
        const double response = -label * sigmoid_ / (1.0f + std::exp(label * sigmoid_ * score[i]));
128
        const double abs_response = fabs(response);
129
130
        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
131
132
133
      }
    }
  }
134

135
  // implement custom average to boost from (if enabled among options)
136
  double BoostFromScore(int) const override {
137
138
139
    double suml = 0.0f;
    double sumw = 0.0f;
    if (weights_ != nullptr) {
140
      #pragma omp parallel for schedule(static) reduction(+:suml, sumw)
141
      for (data_size_t i = 0; i < num_data_; ++i) {
142
        suml += is_pos_(label_[i]) * weights_[i];
143
144
145
146
147
148
        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) {
149
        suml += is_pos_(label_[i]);
150
151
152
      }
    }
    double pavg = suml / sumw;
153
154
    pavg = std::min(pavg, 1.0 - kEpsilon);
    pavg = std::max<double>(pavg, kEpsilon);
155
156
157
158
    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
159

160
  bool ClassNeedTrain(int /*class_id*/) const override {
161
    return need_train_;
162
163
  }

Guolin Ke's avatar
Guolin Ke committed
164
165
  const char* GetName() const override {
    return "binary";
Guolin Ke's avatar
Guolin Ke committed
166
167
  }

Guolin Ke's avatar
Guolin Ke committed
168
169
  void ConvertOutput(const double* input, double* output) const override {
    output[0] = 1.0f / (1.0f + std::exp(-sigmoid_ * input[0]));
170
171
172
173
174
175
176
177
178
179
180
  }

  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; }

181
182
  bool NeedAccuratePrediction() const override { return false; }

Guolin Ke's avatar
Guolin Ke committed
183
184
  data_size_t NumPositiveData() const override { return num_pos_data_; }

Nikita Titov's avatar
Nikita Titov committed
185
 private:
Guolin Ke's avatar
Guolin Ke committed
186
187
  /*! \brief Number of data */
  data_size_t num_data_;
Guolin Ke's avatar
Guolin Ke committed
188
189
  /*! \brief Number of positive samples */
  data_size_t num_pos_data_;
Guolin Ke's avatar
Guolin Ke committed
190
  /*! \brief Pointer of label */
191
  const label_t* label_;
Guolin Ke's avatar
Guolin Ke committed
192
193
194
  /*! \brief True if using unbalance training */
  bool is_unbalance_;
  /*! \brief Sigmoid parameter */
195
  double sigmoid_;
Guolin Ke's avatar
Guolin Ke committed
196
197
198
  /*! \brief Values for positive and negative labels */
  int label_val_[2];
  /*! \brief Weights for positive and negative labels */
199
  double label_weights_[2];
Guolin Ke's avatar
Guolin Ke committed
200
  /*! \brief Weights for data */
201
  const label_t* weights_;
202
  double scale_pos_weight_;
203
  std::function<bool(label_t)> is_pos_;
204
  bool need_train_;
Guolin Ke's avatar
Guolin Ke committed
205
206
207
};

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