rec_spin_att_loss.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. from paddle import nn
  19. '''This code is refer from:
  20. https://github.com/hikopensource/DAVAR-Lab-OCR
  21. '''
  22. class SPINAttentionLoss(nn.Layer):
  23. def __init__(self, reduction='mean', ignore_index=-100, **kwargs):
  24. super(SPINAttentionLoss, self).__init__()
  25. self.loss_func = nn.CrossEntropyLoss(weight=None, reduction=reduction, ignore_index=ignore_index)
  26. def forward(self, predicts, batch):
  27. targets = batch[1].astype("int64")
  28. targets = targets[:, 1:] # remove [eos] in label
  29. label_lengths = batch[2].astype('int64')
  30. batch_size, num_steps, num_classes = predicts.shape[0], predicts.shape[
  31. 1], predicts.shape[2]
  32. assert len(targets.shape) == len(list(predicts.shape)) - 1, \
  33. "The target's shape and inputs's shape is [N, d] and [N, num_steps]"
  34. inputs = paddle.reshape(predicts, [-1, predicts.shape[-1]])
  35. targets = paddle.reshape(targets, [-1])
  36. return {'loss': self.loss_func(inputs, targets)}