precision_recall_op.h 6.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
yangyaming 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once
Y
Yi Wang 已提交
16 17
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
Y
yangyaming 已提交
18 19 20 21 22 23 24 25 26 27 28

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;

enum StateVariable { TP = 0, FP, TN, FN };

Q
QI JUN 已提交
29
template <typename DeviceContext, typename T>
Y
yangyaming 已提交
30 31 32
class PrecisionRecallKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
yangyaming 已提交
33
    auto* in0 = ctx.Input<Tensor>("Indices");
Y
yangyaming 已提交
34 35 36 37 38 39 40
    auto* in1 = ctx.Input<Tensor>("Labels");
    auto* in2 = ctx.Input<Tensor>("Weights");
    auto* in3 = ctx.Input<Tensor>("StatesInfo");
    auto* out0 = ctx.Output<Tensor>("BatchMetrics");
    auto* out1 = ctx.Output<Tensor>("AccumMetrics");
    auto* out2 = ctx.Output<Tensor>("AccumStatesInfo");

Y
yangyaming 已提交
41
    const int* ids_data = in0->data<int>();
Y
yangyaming 已提交
42
    const int* labels_data = in1->data<int>();
Y
yangyaming 已提交
43
    size_t cls_num = static_cast<size_t>(ctx.Attr<int>("class_number"));
Y
yangyaming 已提交
44 45
    const T* weights_data = in2 ? in2->data<T>() : nullptr;
    const T* states_data = in3 ? in3->data<T>() : nullptr;
46 47
    double* batch_metrics_data = out0->mutable_data<double>(ctx.GetPlace());
    double* accum_metrics_data = out1->mutable_data<double>(ctx.GetPlace());
Y
yangyaming 已提交
48 49 50
    out2->mutable_data<T>(ctx.GetPlace());
    auto accum_states = EigenMatrix<T>::From(*out2);
    accum_states.setZero();
Y
yangyaming 已提交
51
    T* accum_states_data = out2->data<T>();
Y
yangyaming 已提交
52 53 54 55 56 57

    size_t sample_num = in0->dims()[0];
    size_t state_var_num = 4;  // TP FP TN FN

    // get states info for current batch
    for (size_t i = 0; i < sample_num; ++i) {
Y
yangyaming 已提交
58 59 60
      size_t idx = ids_data[i];
      size_t label = labels_data[i];

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
      PADDLE_ENFORCE_GE(idx, 0, platform::errors::InvalidArgument(
                                    "Class index of each instance should be "
                                    "larger than 0, But received (%d)",
                                    idx));
      PADDLE_ENFORCE_LT(idx, cls_num,
                        platform::errors::InvalidArgument(
                            "Class index of each instance should be less than "
                            "cls_num (%d), But received (%d)",
                            cls_num, idx));

      PADDLE_ENFORCE_GE(label, 0, platform::errors::InvalidArgument(
                                      "Label of each instance should be larger "
                                      "than 0, But received (%d)",
                                      label));
      PADDLE_ENFORCE_LT(label, cls_num,
                        platform::errors::InvalidArgument(
                            "Label of each instance should be less than "
                            "cls_num (%d), But received (%d)",
                            cls_num, label));
Y
yangyaming 已提交
80 81

      T w = weights_data ? weights_data[i] : 1.0;
Y
yangyaming 已提交
82 83 84
      if (idx == label) {
        accum_states_data[idx * state_var_num + TP] += w;
        for (size_t j = 0; j < cls_num; ++j) {
Y
yangyaming 已提交
85 86
          accum_states_data[j * state_var_num + TN] += w;
        }
Y
yangyaming 已提交
87
        accum_states_data[idx * state_var_num + TN] -= w;
Y
yangyaming 已提交
88
      } else {
Y
yangyaming 已提交
89 90 91
        accum_states_data[label * state_var_num + FN] += w;
        accum_states_data[idx * state_var_num + FP] += w;
        for (size_t j = 0; j < cls_num; ++j) {
Y
yangyaming 已提交
92 93
          accum_states_data[j * state_var_num + TN] += w;
        }
Y
yangyaming 已提交
94 95
        accum_states_data[idx * state_var_num + TN] -= w;
        accum_states_data[label * state_var_num + TN] -= w;
Y
yangyaming 已提交
96 97 98 99
      }
    }

    ComputeMetrics(accum_states_data, batch_metrics_data, state_var_num,
Y
yangyaming 已提交
100
                   cls_num);
Y
yangyaming 已提交
101 102

    if (states_data) {
Y
yangyaming 已提交
103
      for (size_t i = 0; i < cls_num; ++i) {
Y
yangyaming 已提交
104 105 106 107 108 109 110 111
        for (size_t j = 0; j < state_var_num; ++j) {
          size_t idx = i * state_var_num + j;
          accum_states_data[idx] += states_data[idx];
        }
      }
    }

    ComputeMetrics(accum_states_data, accum_metrics_data, state_var_num,
Y
yangyaming 已提交
112
                   cls_num);
Y
yangyaming 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126
  }

  // expose to be reused
  static inline T CalcPrecision(T tp_count, T fp_count) {
    if (tp_count > 0.0 || fp_count > 0.0) {
      return tp_count / (tp_count + fp_count);
    }
    return 1.0;
  }

  static inline T CalcRecall(T tp_count, T fn_count) {
    if (tp_count > 0.0 || fn_count > 0.0) {
      return tp_count / (tp_count + fn_count);
    }
Y
yangyaming 已提交
127
    return 1.0;
Y
yangyaming 已提交
128 129 130 131 132 133 134 135 136 137
  }

  static inline T CalcF1Score(T precision, T recall) {
    if (precision > 0.0 || recall > 0.0) {
      return 2 * precision * recall / (precision + recall);
    }
    return 0.0;
  }

 protected:
138
  void ComputeMetrics(const T* states_data, double* metrics_data,
Y
yangyaming 已提交
139
                      size_t state_var_num, size_t cls_num) const {
Y
yangyaming 已提交
140 141 142 143 144 145
    T total_tp_count = 0;
    T total_fp_count = 0;
    T total_fn_count = 0;
    T macro_avg_precision = 0.0;
    T macro_avg_recall = 0.0;

Y
yangyaming 已提交
146
    for (size_t i = 0; i < cls_num; ++i) {
Y
yangyaming 已提交
147 148 149 150 151 152 153 154 155
      T tp_count = states_data[i * state_var_num + TP];
      T fp_count = states_data[i * state_var_num + FP];
      T fn_count = states_data[i * state_var_num + FN];
      total_tp_count += tp_count;
      total_fp_count += fp_count;
      total_fn_count += fn_count;
      macro_avg_precision += CalcPrecision(tp_count, fp_count);
      macro_avg_recall += CalcRecall(tp_count, fn_count);
    }
Y
yangyaming 已提交
156 157
    macro_avg_precision /= cls_num;
    macro_avg_recall /= cls_num;
Y
yangyaming 已提交
158 159 160 161
    T macro_f1_score = CalcF1Score(macro_avg_precision, macro_avg_recall);

    T micro_avg_precision = CalcPrecision(total_tp_count, total_fp_count);
    T micro_avg_recall = CalcRecall(total_tp_count, total_fn_count);
Y
yangyaming 已提交
162
    T micro_f1_score = CalcF1Score(micro_avg_precision, micro_avg_recall);
Y
yangyaming 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175

    // fill metrics data
    metrics_data[0] = macro_avg_precision;
    metrics_data[1] = macro_avg_recall;
    metrics_data[2] = macro_f1_score;
    metrics_data[3] = micro_avg_precision;
    metrics_data[4] = micro_avg_recall;
    metrics_data[5] = micro_f1_score;
  }
};

}  // namespace operators
}  // namespace paddle