rec_ctc_head.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # copyright (c) 2019 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 math
  18. import paddle
  19. from paddle import ParamAttr, nn
  20. from paddle.nn import functional as F
  21. def get_para_bias_attr(l2_decay, k, name):
  22. regularizer = paddle.regularizer.L2Decay(l2_decay)
  23. stdv = 1.0 / math.sqrt(k * 1.0)
  24. initializer = nn.initializer.Uniform(-stdv, stdv)
  25. weight_attr = ParamAttr(
  26. regularizer=regularizer, initializer=initializer, name=name + "_w_attr")
  27. bias_attr = ParamAttr(
  28. regularizer=regularizer, initializer=initializer, name=name + "_b_attr")
  29. return [weight_attr, bias_attr]
  30. class CTCHead(nn.Layer):
  31. def __init__(self, in_channels, out_channels, fc_decay=0.0004, **kwargs):
  32. super(CTCHead, self).__init__()
  33. weight_attr, bias_attr = get_para_bias_attr(
  34. l2_decay=fc_decay, k=in_channels, name='ctc_fc')
  35. self.fc = nn.Linear(
  36. in_channels,
  37. out_channels,
  38. weight_attr=weight_attr,
  39. bias_attr=bias_attr,
  40. name='ctc_fc')
  41. self.out_channels = out_channels
  42. def forward(self, x, labels=None):
  43. predicts = self.fc(x)
  44. if not self.training:
  45. predicts = F.softmax(predicts, axis=2)
  46. return predicts