table_master_loss.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. )
  26. self.box_loss = nn.L1Loss(reduction="sum")
  27. self.eps = 1e-12
  28. def forward(self, predicts, batch):
  29. # structure_loss
  30. structure_probs = predicts["structure_probs"]
  31. structure_targets = batch[1]
  32. structure_targets = structure_targets[:, 1:]
  33. structure_probs = structure_probs.reshape([-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(
  47. masked_bboxes_preds[:, :, 0::2], masked_bboxes_targets[:, :, 0::2]
  48. )
  49. horizon_loss = horizon_sum_loss / (bbox_masks.sum() + self.eps)
  50. # vertical loss (y and height)
  51. vertical_sum_loss = self.box_loss(
  52. masked_bboxes_preds[:, :, 1::2], masked_bboxes_targets[:, :, 1::2]
  53. )
  54. vertical_loss = vertical_sum_loss / (bbox_masks.sum() + self.eps)
  55. horizon_loss = horizon_loss.mean()
  56. vertical_loss = vertical_loss.mean()
  57. all_loss = structure_loss + horizon_loss + vertical_loss
  58. losses.update(
  59. {
  60. "loss": all_loss,
  61. "horizon_bbox_loss": horizon_loss,
  62. "vertical_bbox_loss": vertical_loss,
  63. }
  64. )
  65. return losses