log_loss_op.cc 4.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
K
kavyasrinet 已提交
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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/log_loss_op.h"
S
sneaxiy 已提交
16
#include <memory>
K
kavyasrinet 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Predicted"),
                   "Input(Predicted) must be initialized.");
    PADDLE_ENFORCE(ctx->HasInput("Labels"),
                   "Input(Labels) must be initialized.");

    auto pred_dims = ctx->GetInputDim("Predicted");
    auto label_dims = ctx->GetInputDim("Labels");

    PADDLE_ENFORCE_EQ(pred_dims, label_dims);
    PADDLE_ENFORCE_EQ(pred_dims.size(), 2,
                      "The rank of Input(Predicted) must be 2 and the shape is "
                      "[batch_size, 1].");
    PADDLE_ENFORCE_EQ(pred_dims[1], 1,
                      "Each row of Input(Predicted) contains a real value, "
                      "so the 2nd dimension of Input(X) must be 1.");

    ctx->SetOutputDim("Loss", {pred_dims[0], 1});
    ctx->ShareLoD("Predicted", "Loss");
  }
};

template <typename AttrType>
class LogLossOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
50
  void Make() override {
K
kavyasrinet 已提交
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    AddInput("Predicted",
             "The input value (Predicted) of Log loss op."
             "Predicted is a 2-D tensor with shape [batch_size, 1].");
    AddInput("Labels",
             "The target value (Labels) of Log loss op."
             "Labels is a 2-D tensor with shape [batch_size, 1].");
    AddOutput("Loss",
              "The output tensor with shape [batch_size, 1] "
              "which represents the log loss.");
    AddAttr<AttrType>("epsilon", "Epsilon in log loss.");
    AddComment(R"DOC(
LogLoss Operator.

Log loss is a loss function used for binary classification. Log Loss quantifies
the accuracy of a classifier by penalising false classifications. Minimising the
Log Loss is equivalent to maximising the accuracy of the classifier. We define
Predicted as the values predicted by our model and Labels as the target ground
truth value. Log loss can evaluate how close the predicted values are to the
target. The shapes of Predicted and Labels are both [batch_size, 1].
The equation is:

$$
Loss = - Labels * log(Predicted + \epsilon) -
        (1 - Labels) * log(1 - Predicted + \epsilon)
$$

)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Predicted"),
                   "Input(Predicted) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Labels"),
                   "Input(Labels) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Loss")),
                   "Input(Loss@GRAD) should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Predicted")),
                   "Output(Predicted@GRAD) should not be null.");

    auto pred_dims = ctx->GetInputDim("Predicted");
    auto loss_grad_dims = ctx->GetInputDim(framework::GradVarName("Loss"));
    PADDLE_ENFORCE_EQ(loss_grad_dims, pred_dims);

    auto pred_grad_name = framework::GradVarName("Predicted");
    ctx->SetOutputDim(pred_grad_name, pred_dims);
  }
};

S
sneaxiy 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
class LogLossGradDescMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    std::unique_ptr<framework::OpDesc> op(new framework::OpDesc());
    op->SetType("log_loss_grad");
    op->SetInput("Predicted", Input("Predicted"));
    op->SetInput("Labels", Input("Labels"));
    op->SetInput(framework::GradVarName("Loss"), OutputGrad("Loss"));
    op->SetOutput(framework::GradVarName("Predicted"), InputGrad("Predicted"));
    op->SetAttrMap(Attrs());
    return op;
  }
};

K
kavyasrinet 已提交
121 122 123 124
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
125
REGISTER_OPERATOR(log_loss, ops::LogLossOp, ops::LogLossOpMaker<float>,
S
sneaxiy 已提交
126
                  ops::LogLossGradDescMaker);
127
REGISTER_OPERATOR(log_loss_grad, ops::LogLossGradOp);
K
kavyasrinet 已提交
128
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
129 130 131 132
    log_loss, ops::LogLossKernel<paddle::platform::CPUDeviceContext, float>);
REGISTER_OP_CPU_KERNEL(
    log_loss_grad,
    ops::LogLossGradKernel<paddle::platform::CPUDeviceContext, float>);