celoss.py 2.4 KB
Newer Older
1
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
B
Bin Lu 已提交
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.

G
gaotingquan 已提交
15 16
import warnings

B
Bin Lu 已提交
17
import paddle
18
import paddle.nn as nn
B
Bin Lu 已提交
19 20
import paddle.nn.functional as F

G
gaotingquan 已提交
21 22
from ppcls.utils import logger

B
Bin Lu 已提交
23

24
class CELoss(nn.Layer):
C
cuicheng01 已提交
25 26 27 28
    """
    Cross entropy loss
    """

D
dongshuilong 已提交
29
    def __init__(self, reduction="mean", epsilon=None):
30 31 32 33
        super().__init__()
        if epsilon is not None and (epsilon <= 0 or epsilon >= 1):
            epsilon = None
        self.epsilon = epsilon
D
dongshuilong 已提交
34 35
        assert reduction in ["mean", "sum", "none"]
        self.reduction = reduction
B
Bin Lu 已提交
36

37
    def _labelsmoothing(self, target, class_num):
38
        if len(target.shape) == 1 or target.shape[-1] != class_num:
39
            one_hot_target = F.one_hot(target, class_num)
B
Bin Lu 已提交
40 41
        else:
            one_hot_target = target
42 43
        soft_target = F.label_smooth(one_hot_target, epsilon=self.epsilon)
        soft_target = paddle.reshape(soft_target, shape=[-1, class_num])
B
Bin Lu 已提交
44 45
        return soft_target

46 47 48 49 50 51 52 53
    def forward(self, x, label):
        if isinstance(x, dict):
            x = x["logits"]
        if self.epsilon is not None:
            class_num = x.shape[-1]
            label = self._labelsmoothing(label, class_num)
            x = -F.log_softmax(x, axis=-1)
            loss = paddle.sum(x * label, axis=-1)
D
dongshuilong 已提交
54
        else:
55 56 57 58 59
            if label.shape[-1] == x.shape[-1]:
                label = F.softmax(label, axis=-1)
                soft_label = True
            else:
                soft_label = False
D
dongshuilong 已提交
60 61 62 63 64
            loss = F.cross_entropy(
                x,
                label=label,
                soft_label=soft_label,
                reduction=self.reduction)
65
        return {"CELoss": loss}
C
cuicheng01 已提交
66 67


G
gaotingquan 已提交
68 69 70 71 72
class MixCELoss(object):
    def __init__(self, *args, **kwargs):
        msg = "\"MixCELos\" is deprecated, please use \"CELoss\" instead."
        logger.error(DeprecationWarning(msg))
        raise DeprecationWarning(msg)