ohem_edge_attention_loss.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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 OhemEdgeAttentionLoss(nn.Layer):
  21. """
  22. Implements the cross entropy loss function. It only compute the edge part.
  23. Args:
  24. edge_threshold (float, optional): The pixels greater edge_threshold as edges. Default: 0.8.
  25. thresh (float, optional): The threshold of ohem. Default: 0.7.
  26. min_kept (int, optional): The min number to keep in loss computation. Default: 5000.
  27. ignore_index (int64, optional): Specifies a target value that is ignored
  28. and does not contribute to the input gradient. Default ``255``.
  29. """
  30. def __init__(self,
  31. edge_threshold=0.8,
  32. thresh=0.7,
  33. min_kept=5000,
  34. ignore_index=255):
  35. super().__init__()
  36. self.edge_threshold = edge_threshold
  37. self.thresh = thresh
  38. self.min_kept = min_kept
  39. self.ignore_index = ignore_index
  40. self.EPS = 1e-10
  41. def forward(self, logits, label):
  42. """
  43. Forward computation.
  44. Args:
  45. logits (tuple|list): (seg_logit, edge_logit) Tensor, the data type is float32, float64. Shape is
  46. (N, C), where C is number of classes, and if shape is more than 2D, this
  47. is (N, C, D1, D2,..., Dk), k >= 1. C =1 of edge_logit .
  48. label (Tensor): Label tensor, the data type is int64. Shape is (N, C), where each
  49. value is 0 <= label[i] <= C-1, and if shape is more than 2D, this is
  50. (N, C, D1, D2,..., Dk), k >= 1.
  51. """
  52. seg_logit, edge_logit = logits[0], logits[1]
  53. if len(label.shape) != len(seg_logit.shape):
  54. label = paddle.unsqueeze(label, 1)
  55. if edge_logit.shape != label.shape:
  56. raise ValueError(
  57. 'The shape of edge_logit should equal to the label, but they are {} != {}'
  58. .format(edge_logit.shape, label.shape))
  59. # Filter out edge
  60. filler = paddle.ones_like(label) * self.ignore_index
  61. label = paddle.where(edge_logit > self.edge_threshold, label, filler)
  62. # ohem
  63. n, c, h, w = seg_logit.shape
  64. label = label.reshape((-1, ))
  65. valid_mask = (label != self.ignore_index).astype('int64')
  66. num_valid = valid_mask.sum()
  67. label = label * valid_mask
  68. prob = F.softmax(seg_logit, axis=1)
  69. prob = prob.transpose((1, 0, 2, 3)).reshape((c, -1))
  70. if self.min_kept < num_valid and num_valid > 0:
  71. # let the value which ignored greater than 1
  72. prob = prob + (1 - valid_mask)
  73. # get the prob of relevant label
  74. label_onehot = F.one_hot(label, c)
  75. label_onehot = label_onehot.transpose((1, 0))
  76. prob = prob * label_onehot
  77. prob = paddle.sum(prob, axis=0)
  78. threshold = self.thresh
  79. if self.min_kept > 0:
  80. index = prob.argsort()
  81. threshold_index = index[min(len(index), self.min_kept) - 1]
  82. threshold_index = int(threshold_index.numpy()[0])
  83. if prob[threshold_index] > self.thresh:
  84. threshold = prob[threshold_index]
  85. kept_mask = (prob < threshold).astype('int64')
  86. label = label * kept_mask
  87. valid_mask = valid_mask * kept_mask
  88. # make the invalid region as ignore
  89. label = label + (1 - valid_mask) * self.ignore_index
  90. label = label.reshape((n, 1, h, w))
  91. valid_mask = valid_mask.reshape((n, 1, h, w)).astype('float32')
  92. loss = F.softmax_with_cross_entropy(
  93. seg_logit, label, ignore_index=self.ignore_index, axis=1)
  94. loss = loss * valid_mask
  95. avg_loss = paddle.mean(loss) / (paddle.mean(valid_mask) + self.EPS)
  96. label.stop_gradient = True
  97. valid_mask.stop_gradient = True
  98. return avg_loss