rec_nrtr_mtb.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # copyright (c) 2020 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 paddle import nn
  15. import paddle
  16. class MTB(nn.Layer):
  17. def __init__(self, cnn_num, in_channels):
  18. super(MTB, self).__init__()
  19. self.block = nn.Sequential()
  20. self.out_channels = in_channels
  21. self.cnn_num = cnn_num
  22. if self.cnn_num == 2:
  23. for i in range(self.cnn_num):
  24. self.block.add_sublayer(
  25. 'conv_{}'.format(i),
  26. nn.Conv2D(
  27. in_channels=in_channels
  28. if i == 0 else 32 * (2**(i - 1)),
  29. out_channels=32 * (2**i),
  30. kernel_size=3,
  31. stride=2,
  32. padding=1))
  33. self.block.add_sublayer('relu_{}'.format(i), nn.ReLU())
  34. self.block.add_sublayer('bn_{}'.format(i),
  35. nn.BatchNorm2D(32 * (2**i)))
  36. def forward(self, images):
  37. x = self.block(images)
  38. if self.cnn_num == 2:
  39. # (b, w, h, c)
  40. x = paddle.transpose(x, [0, 3, 2, 1])
  41. x_shape = paddle.shape(x)
  42. x = paddle.reshape(
  43. x, [x_shape[0], x_shape[1], x_shape[2] * x_shape[3]])
  44. return x