rec_sar_loss.py 1.1 KB

1234567891011121314151617181920212223242526272829
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. import paddle
  5. from paddle import nn
  6. class SARLoss(nn.Layer):
  7. def __init__(self, **kwargs):
  8. super(SARLoss, self).__init__()
  9. ignore_index = kwargs.get('ignore_index', 92) # 6626
  10. self.loss_func = paddle.nn.loss.CrossEntropyLoss(
  11. reduction="mean", ignore_index=ignore_index)
  12. def forward(self, predicts, batch):
  13. predict = predicts[:, :
  14. -1, :] # ignore last index of outputs to be in same seq_len with targets
  15. label = batch[1].astype(
  16. "int64")[:, 1:] # ignore first index of target in loss calculation
  17. batch_size, num_steps, num_classes = predict.shape[0], predict.shape[
  18. 1], predict.shape[2]
  19. assert len(label.shape) == len(list(predict.shape)) - 1, \
  20. "The target's shape and inputs's shape is [N, d] and [N, num_steps]"
  21. inputs = paddle.reshape(predict, [-1, num_classes])
  22. targets = paddle.reshape(label, [-1])
  23. loss = self.loss_func(inputs, targets)
  24. return {'loss': loss}