edge_attention_loss.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. from paddle import nn
  16. import paddle.nn.functional as F
  17. from paddlex.paddleseg.cvlibs import manager
  18. from paddlex.paddleseg.models import losses
  19. @manager.LOSSES.add_component
  20. class EdgeAttentionLoss(nn.Layer):
  21. """
  22. Implements the cross entropy loss function. It only compute the edge part.
  23. Args:
  24. edge_threshold (float): The pixels greater edge_threshold as edges.
  25. ignore_index (int64): Specifies a target value that is ignored
  26. and does not contribute to the input gradient. Default ``255``.
  27. """
  28. def __init__(self, edge_threshold=0.8, ignore_index=255):
  29. super().__init__()
  30. self.edge_threshold = edge_threshold
  31. self.ignore_index = ignore_index
  32. self.EPS = 1e-10
  33. self.mean_mask = 1
  34. def forward(self, logits, label):
  35. """
  36. Forward computation.
  37. Args:
  38. logits (tuple|list): (seg_logit, edge_logit) Tensor, the data type is float32, float64. Shape is
  39. (N, C), where C is number of classes, and if shape is more than 2D, this
  40. is (N, C, D1, D2,..., Dk), k >= 1. C =1 of edge_logit .
  41. label (Tensor): Label tensor, the data type is int64. Shape is (N, C), where each
  42. value is 0 <= label[i] <= C-1, and if shape is more than 2D, this is
  43. (N, C, D1, D2,..., Dk), k >= 1.
  44. """
  45. seg_logit, edge_logit = logits[0], logits[1]
  46. if len(label.shape) != len(seg_logit.shape):
  47. label = paddle.unsqueeze(label, 1)
  48. if edge_logit.shape != label.shape:
  49. raise ValueError(
  50. 'The shape of edge_logit should equal to the label, but they are {} != {}'
  51. .format(edge_logit.shape, label.shape))
  52. filler = paddle.ones_like(label) * self.ignore_index
  53. label = paddle.where(edge_logit > self.edge_threshold, label, filler)
  54. seg_logit = paddle.transpose(seg_logit, [0, 2, 3, 1])
  55. label = paddle.transpose(label, [0, 2, 3, 1])
  56. loss = F.softmax_with_cross_entropy(
  57. seg_logit, label, ignore_index=self.ignore_index, axis=-1)
  58. mask = label != self.ignore_index
  59. mask = paddle.cast(mask, 'float32')
  60. loss = loss * mask
  61. avg_loss = paddle.mean(loss) / (paddle.mean(mask) + self.EPS)
  62. if paddle.mean(mask) < self.mean_mask:
  63. self.mean_mask = paddle.mean(mask)
  64. label.stop_gradient = True
  65. mask.stop_gradient = True
  66. return avg_loss