rec_ctc_head.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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):
  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(regularizer=regularizer, initializer=initializer)
  26. bias_attr = ParamAttr(regularizer=regularizer, initializer=initializer)
  27. return [weight_attr, bias_attr]
  28. class CTCHead(nn.Layer):
  29. def __init__(self,
  30. in_channels,
  31. out_channels,
  32. fc_decay=0.0004,
  33. mid_channels=None,
  34. return_feats=False,
  35. **kwargs):
  36. super(CTCHead, self).__init__()
  37. if mid_channels is None:
  38. weight_attr, bias_attr = get_para_bias_attr(
  39. l2_decay=fc_decay, k=in_channels)
  40. self.fc = nn.Linear(
  41. in_channels,
  42. out_channels,
  43. weight_attr=weight_attr,
  44. bias_attr=bias_attr)
  45. else:
  46. weight_attr1, bias_attr1 = get_para_bias_attr(
  47. l2_decay=fc_decay, k=in_channels)
  48. self.fc1 = nn.Linear(
  49. in_channels,
  50. mid_channels,
  51. weight_attr=weight_attr1,
  52. bias_attr=bias_attr1)
  53. weight_attr2, bias_attr2 = get_para_bias_attr(
  54. l2_decay=fc_decay, k=mid_channels)
  55. self.fc2 = nn.Linear(
  56. mid_channels,
  57. out_channels,
  58. weight_attr=weight_attr2,
  59. bias_attr=bias_attr2)
  60. self.out_channels = out_channels
  61. self.mid_channels = mid_channels
  62. self.return_feats = return_feats
  63. def forward(self, x, targets=None):
  64. if self.mid_channels is None:
  65. predicts = self.fc(x)
  66. else:
  67. x = self.fc1(x)
  68. predicts = self.fc2(x)
  69. if self.return_feats:
  70. result = (x, predicts)
  71. else:
  72. result = predicts
  73. if not self.training:
  74. predicts = F.softmax(predicts, axis=2)
  75. result = predicts
  76. return result