auc_op.cc 5.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
T
typhoonzero 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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

W
Wu Yi 已提交
15
#include "paddle/fluid/operators/metrics/auc_op.h"
T
typhoonzero 已提交
16 17 18 19

namespace paddle {
namespace operators {

T
update  
typhoonzero 已提交
20
class AucOp : public framework::OperatorWithKernel {
T
typhoonzero 已提交
21 22 23 24
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
武毅 已提交
25
  void InferShape(framework::InferShapeContext *ctx) const override {
26 27
    OP_INOUT_CHECK(ctx->HasInput("Predict"), "Input", "Predict", "Auc");
    OP_INOUT_CHECK(ctx->HasInput("Label"), "Input", "Label", "Auc");
28 29
    auto predict_dims = ctx->GetInputDim("Predict");
    auto label_dims = ctx->GetInputDim("Label");
30 31 32 33 34 35 36
    PADDLE_ENFORCE_GE(
        predict_dims.size(), 2,
        platform::errors::InvalidArgument(
            "The Input(Predict) has not been initialized properly. The "
            "shape of Input(Predict) = [%s], the shape size must be "
            "greater_equal 2.",
            predict_dims));
37 38
    auto predict_width = predict_dims[1];
    PADDLE_ENFORCE_NE(
39
        phi::product(predict_dims), 0,
40 41 42 43 44
        platform::errors::InvalidArgument(
            "The Input(Predict) has not been initialized properly. The "
            "shape of Input(Predict) = [%s], the shape can not involes 0.",
            predict_dims));
    PADDLE_ENFORCE_NE(
45
        phi::product(label_dims), 0,
46 47 48 49
        platform::errors::InvalidArgument(
            "The Input(Label) has not been initialized properly. The "
            "shape of Input(Label) = [%s], the shape can not involes 0.",
            label_dims));
50 51
    if (ctx->IsRuntime()) {
      PADDLE_ENFORCE_LE(predict_width, 2,
52 53 54
                        platform::errors::InvalidArgument(
                            "Only support binary classification,"
                            "prediction dims[1] should be 1 or 2"));
55
    }
Q
Qiao Longfei 已提交
56
    auto predict_height = ctx->GetInputDim("Predict")[0];
武毅 已提交
57
    auto label_height = ctx->GetInputDim("Label")[0];
T
typhoonzero 已提交
58

59 60
    if (ctx->IsRuntime()) {
      PADDLE_ENFORCE_EQ(predict_height, label_height,
61 62
                        platform::errors::InvalidArgument(
                            "Out and Label should have same height."));
63
    }
T
typhoonzero 已提交
64

T
tangwei12 已提交
65
    int num_pred_buckets = ctx->Attrs().Get<int>("num_thresholds") + 1;
T
tangwei12 已提交
66 67
    int slide_steps = ctx->Attrs().Get<int>("slide_steps");

68 69 70 71 72 73
    PADDLE_ENFORCE_GE(
        num_pred_buckets, 1,
        platform::errors::InvalidArgument("num_thresholds must larger than 1"));
    PADDLE_ENFORCE_GE(slide_steps, 0,
                      platform::errors::InvalidArgument(
                          "slide_steps must be natural number"));
W
Wu Yi 已提交
74

T
typhoonzero 已提交
75
    ctx->SetOutputDim("AUC", {1});
T
tangwei12 已提交
76

H
hutuxian 已提交
77 78 79 80 81 82 83 84 85
    if (slide_steps) {
      ctx->SetOutputDim("StatPosOut",
                        {(1 + slide_steps) * num_pred_buckets + 1});
      ctx->SetOutputDim("StatNegOut",
                        {(1 + slide_steps) * num_pred_buckets + 1});
    } else {
      ctx->SetOutputDim("StatPosOut", {1, num_pred_buckets});
      ctx->SetOutputDim("StatNegOut", {1, num_pred_buckets});
    }
武毅 已提交
86 87 88
  }

 protected:
89
  framework::OpKernelType GetExpectedKernelType(
武毅 已提交
90
      const framework::ExecutionContext &ctx) const override {
91 92
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Predict"),
93
        ctx.device_context());
T
typhoonzero 已提交
94 95 96 97 98
  }
};

class AucOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
99
  void Make() override {
Q
Qiao Longfei 已提交
100 101 102
    AddInput("Predict",
             "A floating point 2D tensor with shape [batch_size, 2], values "
             "are in the range [0, 1]."
武毅 已提交
103
             "Typically, this tensor indicates the probability of each label");
T
auc_op  
typhoonzero 已提交
104
    AddInput("Label",
Q
Qiao Longfei 已提交
105 106
             "A 2D int tensor indicating the label of the training data. "
             "shape: [batch_size, 1]");
T
tangwei12 已提交
107

T
auc_op  
typhoonzero 已提交
108
    // TODO(typhoonzero): support weight input
T
tangwei12 已提交
109 110 111
    AddInput("StatPos", "Statistic value when label = 1");
    AddInput("StatNeg", "Statistic value when label = 0");

T
auc_op  
typhoonzero 已提交
112
    AddOutput("AUC",
T
typhoonzero 已提交
113
              "A scalar representing the "
114
              "current area-under-the-curve.");
T
tangwei12 已提交
115

T
tangwei12 已提交
116 117
    AddOutput("StatPosOut", "Statistic value when label = 1");
    AddOutput("StatNegOut", "Statistic value when label = 0");
T
typhoonzero 已提交
118

T
typhoonzero 已提交
119
    AddAttr<std::string>("curve", "Curve type, can be 'ROC' or 'PR'.")
T
typhoonzero 已提交
120
        .SetDefault("ROC");
T
tangwei12 已提交
121

T
tangwei12 已提交
122 123 124
    AddAttr<int>(
        "num_thresholds",
        "The number of thresholds to use when discretizing the roc curve.")
T
tangwei12 已提交
125
        .SetDefault((2 << 12) - 1);
T
tangwei12 已提交
126 127
    AddAttr<int>("slide_steps", "Use slide steps to calc batch auc.")
        .SetDefault(1);
128 129
    AddComment(R"DOC(
Area Under The Curve (AUC) Operator.
武毅 已提交
130

131 132
This implementation computes the AUC according to forward output and label.
It is used very widely in binary classification evaluation. As a note:
武毅 已提交
133
If input label contains values other than 0 and 1, it will be cast
134
to bool. You can find the relevant definitions here:
武毅 已提交
135 136
https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve

137 138 139
There are two types of possible curves:
1. ROC: Receiver operating characteristic
2. PR: Precision Recall
武毅 已提交
140
)DOC");
T
typhoonzero 已提交
141 142 143 144 145 146 147
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
T
update  
typhoonzero 已提交
148
REGISTER_OP_WITHOUT_GRADIENT(auc, ops::AucOp, ops::AucOpMaker);
T
typhoonzero 已提交
149
REGISTER_OP_CPU_KERNEL(auc, ops::AucKernel<paddle::platform::CPUPlace, float>);