rec_ctc_head.py 2.8 KB

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