binary_objective.hpp 7.11 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_OBJECTIVE_BINARY_OBJECTIVE_HPP_
#define LIGHTGBM_OBJECTIVE_BINARY_OBJECTIVE_HPP_

#include <LightGBM/objective_function.h>

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

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

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

Guolin Ke's avatar
Guolin Ke committed
55
56
57
58
59
60
  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;
61
    // REMOVEME: remove the warning after 2.4 version release
62
63
    Log::Warning("Starting from the 2.1.2 version, default value for "
                 "the \"boost_from_average\" parameter in \"binary\" objective is true.\n"
64
                 "This may cause significantly different results comparing to the previous versions of LightGBM.\n"
65
                 "Try to set boost_from_average=false, if your old models produce bad results");
Guolin Ke's avatar
Guolin Ke committed
66
    // count for positive and negative samples
67
    #pragma omp parallel for schedule(static) reduction(+:cnt_positive, cnt_negative)
Guolin Ke's avatar
Guolin Ke committed
68
    for (data_size_t i = 0; i < num_data_; ++i) {
Guolin Ke's avatar
Guolin Ke committed
69
      if (is_pos_(label_[i])) {
Guolin Ke's avatar
Guolin Ke committed
70
71
72
73
74
        ++cnt_positive;
      } else {
        ++cnt_negative;
      }
    }
75
    need_train_ = true;
76
    if (cnt_negative == 0 || cnt_positive == 0) {
77
      Log::Warning("Contains only one class");
78
      // not need to boost.
79
      need_train_ = false;
80
    }
ProtD's avatar
ProtD committed
81
    Log::Info("Number of positive: %d, number of negative: %d", cnt_positive, cnt_negative);
Guolin Ke's avatar
Guolin Ke committed
82
83
84
85
86
87
88
    // 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
89
    if (is_unbalance_ && cnt_positive > 0 && cnt_negative > 0) {
90
91
      if (cnt_positive > cnt_negative) {
        label_weights_[1] = 1.0f;
92
        label_weights_[0] = static_cast<double>(cnt_positive) / cnt_negative;
93
      } else {
94
        label_weights_[1] = static_cast<double>(cnt_negative) / cnt_positive;
95
96
        label_weights_[0] = 1.0f;
      }
Guolin Ke's avatar
Guolin Ke committed
97
    }
Guolin Ke's avatar
Guolin Ke committed
98
    label_weights_[1] *= scale_pos_weight_;
Guolin Ke's avatar
Guolin Ke committed
99
100
  }

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

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

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

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

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

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

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

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

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