infer_nets.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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. import paddle
  15. class PostProcessor(paddle.nn.Layer):
  16. def __init__(self, model_type):
  17. super(PostProcessor, self).__init__()
  18. self.model_type = model_type
  19. def forward(self, net_outputs):
  20. if self.model_type == 'classifier':
  21. outputs = paddle.nn.functional.softmax(net_outputs, axis=1)
  22. elif self.model_type == 'segmenter':
  23. # score_map, label_map
  24. outputs = paddle.transpose(paddle.nn.functional.softmax(net_outputs, axis=1), perm=[0, 2, 3, 1]), \
  25. paddle.transpose(paddle.argmax(net_outputs, axis=1, keepdim=True, dtype='int32'),
  26. perm=[0, 2, 3, 1])
  27. else:
  28. outputs = net_outputs
  29. return outputs
  30. class InferNet(paddle.nn.Layer):
  31. def __init__(self, net, model_type):
  32. super(InferNet, self).__init__()
  33. self.net = net
  34. self.postprocessor = PostProcessor(model_type)
  35. def forward(self, x):
  36. net_outputs = self.net(x)[0]
  37. outputs = self.postprocessor(net_outputs)
  38. return outputs