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

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
yangyaming 已提交
16 17
#include "paddle/framework/eigen.h"
#include "paddle/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 61 62 63 64 65
      size_t idx = ids_data[i];
      size_t label = labels_data[i];

      PADDLE_ENFORCE(idx >= 0 && idx < cls_num,
                     "Class index of each instance should be in "
                     "[0, class_number).");
      PADDLE_ENFORCE(label >= 0 && label < cls_num,
                     "Label of each instance should be in [0, class_number).");
Y
yangyaming 已提交
66 67

      T w = weights_data ? weights_data[i] : 1.0;
Y
yangyaming 已提交
68 69 70
      if (idx == label) {
        accum_states_data[idx * state_var_num + TP] += w;
        for (size_t j = 0; j < cls_num; ++j) {
Y
yangyaming 已提交
71 72
          accum_states_data[j * state_var_num + TN] += w;
        }
Y
yangyaming 已提交
73
        accum_states_data[idx * state_var_num + TN] -= w;
Y
yangyaming 已提交
74
      } else {
Y
yangyaming 已提交
75 76 77
        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 已提交
78 79
          accum_states_data[j * state_var_num + TN] += w;
        }
Y
yangyaming 已提交
80 81
        accum_states_data[idx * state_var_num + TN] -= w;
        accum_states_data[label * state_var_num + TN] -= w;
Y
yangyaming 已提交
82 83 84 85
      }
    }

    ComputeMetrics(accum_states_data, batch_metrics_data, state_var_num,
Y
yangyaming 已提交
86
                   cls_num);
Y
yangyaming 已提交
87 88

    if (states_data) {
Y
yangyaming 已提交
89
      for (size_t i = 0; i < cls_num; ++i) {
Y
yangyaming 已提交
90 91 92 93 94 95 96 97
        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 已提交
98
                   cls_num);
Y
yangyaming 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112
  }

  // 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 已提交
113
    return 1.0;
Y
yangyaming 已提交
114 115 116 117 118 119 120 121 122 123
  }

  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:
124
  void ComputeMetrics(const T* states_data, double* metrics_data,
Y
yangyaming 已提交
125
                      size_t state_var_num, size_t cls_num) const {
Y
yangyaming 已提交
126 127 128 129 130 131
    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 已提交
132
    for (size_t i = 0; i < cls_num; ++i) {
Y
yangyaming 已提交
133 134 135 136 137 138 139 140 141
      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 已提交
142 143
    macro_avg_precision /= cls_num;
    macro_avg_recall /= cls_num;
Y
yangyaming 已提交
144 145 146 147
    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 已提交
148
    T micro_f1_score = CalcF1Score(micro_avg_precision, micro_avg_recall);
Y
yangyaming 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161

    // 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