precision_recall_op.cc 7.7 KB
Newer Older
Y
yangyaming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* 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. */

Y
yangyaming 已提交
15 16
#include "paddle/operators/precision_recall_op.h"

Y
yangyaming 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
namespace paddle {
namespace operators {

class PrecisionRecallOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Predictions"),
                   "Input(Predictions) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Labels"),
                   "Input(Labels) should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("BatchMetrics"),
                   "Output(BatchMetrics) should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("AccumMetrics"),
                   "Output(AccumMetrics) should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("AccumStatesInfo"),
                   "Output(AccumStatesInfo) should not be null.");

    auto predictions_dims = ctx->GetInputDim("Predictions");
    auto labels_dims = ctx->GetInputDim("Labels");

    if (ctx->HasInput("Weights")) {
      auto weights_dims = ctx->GetInputDim("Weights");
Y
yangyaming 已提交
41 42
      PADDLE_ENFORCE_EQ(weights_dims,
                        framework::make_ddim({predictions_dims[0], 1}),
Y
yangyaming 已提交
43 44 45 46 47
                        "The shape of Input(Weights) should be "
                        "[batch_size, 1].");
    }
    if (ctx->HasInput("StatesInfo")) {
      auto states_dims = ctx->GetInputDim("StatesInfo");
Y
yangyaming 已提交
48 49
      PADDLE_ENFORCE_EQ(states_dims,
                        framework::make_ddim({predictions_dims[1], 4}),
Y
yangyaming 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
                        "The shape of Input(StatesInfo) should be "
                        "[class_number, 4].");
    }
    PADDLE_ENFORCE_EQ(predictions_dims[0], labels_dims[0],
                      "The 1st dimension of Input(Predictions) and "
                      "Input(Labels) both are batch_size and the shape should "
                      "be the same.");
    PADDLE_ENFORCE_EQ(labels_dims[1], 1,
                      "The 2nd dimension of Input(Labels) "
                      "contains instance label and the shape should be equal "
                      "to 1");
    PADDLE_ENFORCE_GE(predictions_dims[1], 1,
                      "The shape of Input(Predictions)'s 2nd dimension is "
                      "equal to class number and should be at least 1.");

    // Layouts of BatchMetrics and AccumMetrics both are:
    // [
    //  macro average precision, macro average recall, macro average F1 score,
    //  micro average precision, micro average recall, micro average F1 score
    // ]
    ctx->SetOutputDim("BatchMetrics", {6});
    ctx->SetOutputDim("AccumMetrics", {6});
    // Shape of AccumStatesInfo is [class_number, 4]
    // The layout of each row is:
    // [ TP, FP, TN, FN ]
    ctx->SetOutputDim("AccumStatesInfo", {predictions_dims[1], 4});
  }
Y
yangyaming 已提交
77 78 79 80 81 82

 protected:
  framework::DataType IndicateDataType(
      const framework::ExecutionContext &ctx) const override {
    return framework::ToDataType(ctx.Input<Tensor>("Predictions")->type());
  }
Y
yangyaming 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
};

class PrecisionRecallOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  PrecisionRecallOpMaker(framework::OpProto *proto,
                         framework::OpAttrChecker *op_checker)
      : OpProtoAndCheckerMaker(proto, op_checker) {
    AddInput("Predictions",
             "(Tensor, default Tensor<float>), a 2-D tensor with shape N x D, "
             "where N is the batch size and D is the number of classes. "
             "Each row contains probabilities for an instance which computed "
             "by the previous operator.");
    AddInput("Labels",
             "(Tensor, default Tensor<int>), a 2-D tensor with shape N x 1, "
             "where N is the batch size. Each element is a label and the "
             "value should be in [0, class_number - 1].");
    AddInput("Weights",
             "(Tensor, default Tensor<float>), a 2-D tensor with shape N x 1, "
             "where N is the batch size. This input is optional. If provided, "
             "weight of instance would be considered when computing metrics.")
        .AsDispensable();
    AddInput("StatesInfo",
             "(Tensor, default Tensor<int>), a 2-D tensor with shape D x 4, "
             "where D is the number of classes. This input is optional. If "
             "provided, current state will be accumulated to this state and "
             "the accumulation state will be as the output state.")
        .AsDispensable();
Y
yangyaming 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    AddOutput("BatchMetrics",
              "(Tensor, default Tensor<float>), a 1-D tensor with shape {6}."
              "This output tensor contains metrics for current batch data."
              "The layout is [macro average precision, macro average recall, "
              "macro f1 score, micro average precision, micro average recall, "
              "micro f1 score]");
    AddOutput("AccumMetrics",
              "(Tensor, default Tensor<float>), a 1-D tensor with shape {6}."
              "This output tensor contains metrics for accumulated data."
              "The layout is [macro average precision, macro average recall, "
              "macro f1 score, micro average precision, micro average recall, "
              "micro f1 score]");
    AddOutput("AccumStatesInfo",
              "(Tensor, default Tensor<float>), a 2-D tensor with shape D x 4, "
              "where D is equal to class number. This output tensor contains "
              "accumulated state variables used to compute metrics. The layout "
              "for each class is [true positives, false positives, "
              "true negatives, false negatives].");
Y
yangyaming 已提交
128 129

    AddComment(R"DOC(
Y
yangyaming 已提交
130 131 132 133 134 135 136 137 138
When given 'Input(Predictions)' and 'Input(Labels)', this operator can be used
to compute various metrics including:
  - macro average precision
  - macro average recall
  - macro f1 score
  - micro average precision
  - micro average recall
  - micro f1 score

139
To compute the above metrics, we need to do statistics for true positives,
Y
yangyaming 已提交
140
false positives and false negatives. Here count of true negatives is not
141
necessary, but counting it may provide potential usage and the cost is
Y
yangyaming 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
trivial, so the operator also provides count of true negatives.

We define state as a 2-D tensor with shape [class number, 4]. Each row of a
state contains statistic variables for corresponding class. Layout of each row
is: TP(true positives), FP(false positives), TN(true negatives),
FN(false negatives). If 'Input(Weights)' provided, TP, FP, TN, FN will be
calculated by given weight instead of instance count.

This operator also supports metrics computing for cross-batch situation. To
achieve this, 'Input(StatesInfo)' should be provided. State of current batch
data will be accumulated to 'Input(StatesInfo)' and 'Output(AccumStatesInfo)'
is the accumulation state.

'Output(BatchMetrics)' is metrics of current batch data while
'Output(AccumStatesInfo)' is metrics of accumulation data.

Y
yangyaming 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170
)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_WITHOUT_GRADIENT(precision_recall, ops::PrecisionRecallOp,
                             ops::PrecisionRecallOpMaker);
REGISTER_OP_CPU_KERNEL(
    precision_recall,
    ops::PrecisionRecallKernel<paddle::platform::CPUPlace, float>,
Y
yangyaming 已提交
171
    ops::PrecisionRecallKernel<paddle::platform::CPUPlace, double>);