celoss.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import warnings
  15. import paddle
  16. import paddle.nn as nn
  17. import paddle.nn.functional as F
  18. from paddlex.ppcls.utils import logger
  19. class CELoss(nn.Layer):
  20. """
  21. Cross entropy loss
  22. """
  23. def __init__(self, epsilon=None):
  24. super().__init__()
  25. if epsilon is not None and (epsilon <= 0 or epsilon >= 1):
  26. epsilon = None
  27. self.epsilon = epsilon
  28. def _labelsmoothing(self, target, class_num):
  29. if len(target.shape) == 1 or target.shape[-1] != class_num:
  30. one_hot_target = F.one_hot(target, class_num)
  31. else:
  32. one_hot_target = target
  33. soft_target = F.label_smooth(one_hot_target, epsilon=self.epsilon)
  34. soft_target = paddle.reshape(soft_target, shape=[-1, class_num])
  35. return soft_target
  36. def forward(self, x, label):
  37. if isinstance(x, dict):
  38. x = x["logits"]
  39. if self.epsilon is not None:
  40. class_num = x.shape[-1]
  41. label = self._labelsmoothing(label, class_num)
  42. x = -F.log_softmax(x, axis=-1)
  43. loss = paddle.sum(x * label, axis=-1)
  44. else:
  45. if label.shape[-1] == x.shape[-1]:
  46. label = F.softmax(label, axis=-1)
  47. soft_label = True
  48. else:
  49. soft_label = False
  50. loss = F.cross_entropy(x, label=label, soft_label=soft_label)
  51. loss = loss.mean()
  52. return {"CELoss": loss}
  53. class MixCELoss(object):
  54. def __init__(self, *args, **kwargs):
  55. msg = "\"MixCELos\" is deprecated, please use \"CELoss\" instead."
  56. logger.error(DeprecationWarning(msg))
  57. raise DeprecationWarning(msg)