rec_rfl_loss.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # copyright (c) 2022 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. """
  15. This code is refer from:
  16. https://github.com/hikopensource/DAVAR-Lab-OCR/blob/main/davarocr/davar_common/models/loss/cross_entropy_loss.py
  17. """
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21. import paddle
  22. from paddle import nn
  23. from .basic_loss import CELoss, DistanceLoss
  24. class RFLLoss(nn.Layer):
  25. def __init__(self, ignore_index=-100, **kwargs):
  26. super().__init__()
  27. self.cnt_loss = nn.MSELoss(**kwargs)
  28. self.seq_loss = nn.CrossEntropyLoss(ignore_index=ignore_index)
  29. def forward(self, predicts, batch):
  30. self.total_loss = {}
  31. total_loss = 0.0
  32. if isinstance(predicts, tuple) or isinstance(predicts, list):
  33. cnt_outputs, seq_outputs = predicts
  34. else:
  35. cnt_outputs, seq_outputs = predicts, None
  36. # batch [image, label, length, cnt_label]
  37. if cnt_outputs is not None:
  38. cnt_loss = self.cnt_loss(cnt_outputs,
  39. paddle.cast(batch[3], paddle.float32))
  40. self.total_loss['cnt_loss'] = cnt_loss
  41. total_loss += cnt_loss
  42. if seq_outputs is not None:
  43. targets = batch[1].astype("int64")
  44. label_lengths = batch[2].astype('int64')
  45. batch_size, num_steps, num_classes = seq_outputs.shape[
  46. 0], seq_outputs.shape[1], seq_outputs.shape[2]
  47. assert len(targets.shape) == len(list(seq_outputs.shape)) - 1, \
  48. "The target's shape and inputs's shape is [N, d] and [N, num_steps]"
  49. inputs = seq_outputs[:, :-1, :]
  50. targets = targets[:, 1:]
  51. inputs = paddle.reshape(inputs, [-1, inputs.shape[-1]])
  52. targets = paddle.reshape(targets, [-1])
  53. seq_loss = self.seq_loss(inputs, targets)
  54. self.total_loss['seq_loss'] = seq_loss
  55. total_loss += seq_loss
  56. self.total_loss['loss'] = total_loss
  57. return self.total_loss