table_master_loss.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright (c) 2021 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. """
  15. This code is refer from:
  16. https://github.com/JiaquanYe/TableMASTER-mmocr/tree/master/mmocr/models/textrecog/losses
  17. """
  18. import paddle
  19. from paddle import nn
  20. class TableMasterLoss(nn.Layer):
  21. def __init__(self, ignore_index=-1):
  22. super(TableMasterLoss, self).__init__()
  23. self.structure_loss = nn.CrossEntropyLoss(
  24. ignore_index=ignore_index, reduction='mean')
  25. self.box_loss = nn.L1Loss(reduction='sum')
  26. self.eps = 1e-12
  27. def forward(self, predicts, batch):
  28. # structure_loss
  29. structure_probs = predicts['structure_probs']
  30. structure_targets = batch[1]
  31. structure_targets = structure_targets[:, 1:]
  32. structure_probs = structure_probs.reshape(
  33. [-1, structure_probs.shape[-1]])
  34. structure_targets = structure_targets.reshape([-1])
  35. structure_loss = self.structure_loss(structure_probs, structure_targets)
  36. structure_loss = structure_loss.mean()
  37. losses = dict(structure_loss=structure_loss)
  38. # box loss
  39. bboxes_preds = predicts['loc_preds']
  40. bboxes_targets = batch[2][:, 1:, :]
  41. bbox_masks = batch[3][:, 1:]
  42. # mask empty-bbox or non-bbox structure token's bbox.
  43. masked_bboxes_preds = bboxes_preds * bbox_masks
  44. masked_bboxes_targets = bboxes_targets * bbox_masks
  45. # horizon loss (x and width)
  46. horizon_sum_loss = self.box_loss(masked_bboxes_preds[:, :, 0::2],
  47. masked_bboxes_targets[:, :, 0::2])
  48. horizon_loss = horizon_sum_loss / (bbox_masks.sum() + self.eps)
  49. # vertical loss (y and height)
  50. vertical_sum_loss = self.box_loss(masked_bboxes_preds[:, :, 1::2],
  51. masked_bboxes_targets[:, :, 1::2])
  52. vertical_loss = vertical_sum_loss / (bbox_masks.sum() + self.eps)
  53. horizon_loss = horizon_loss.mean()
  54. vertical_loss = vertical_loss.mean()
  55. all_loss = structure_loss + horizon_loss + vertical_loss
  56. losses.update({
  57. 'loss': all_loss,
  58. 'horizon_bbox_loss': horizon_loss,
  59. 'vertical_bbox_loss': vertical_loss
  60. })
  61. return losses