distanceloss.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 paddle
  15. import paddle.nn as nn
  16. import paddle.nn.functional as F
  17. from paddle.nn import L1Loss
  18. from paddle.nn import MSELoss as L2Loss
  19. from paddle.nn import SmoothL1Loss
  20. class DistanceLoss(nn.Layer):
  21. """
  22. DistanceLoss:
  23. mode: loss mode
  24. """
  25. def __init__(self, mode="l2", **kargs):
  26. super().__init__()
  27. assert mode in ["l1", "l2", "smooth_l1"]
  28. if mode == "l1":
  29. self.loss_func = nn.L1Loss(**kargs)
  30. elif mode == "l2":
  31. self.loss_func = nn.MSELoss(**kargs)
  32. elif mode == "smooth_l1":
  33. self.loss_func = nn.SmoothL1Loss(**kargs)
  34. self.mode = mode
  35. def forward(self, x, y):
  36. loss = self.loss_func(x, y)
  37. return {"loss_{}".format(self.mode): loss}