infer_nets.py 1.6 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. else:
  23. # score_map, label_map
  24. logit = net_outputs[0]
  25. outputs = paddle.transpose(paddle.nn.functional.softmax(logit, axis=1), perm=[0, 2, 3, 1]), \
  26. paddle.transpose(paddle.argmax(logit, axis=1, keepdim=True, dtype='int32'),
  27. perm=[0, 2, 3, 1])
  28. return outputs
  29. class InferNet(paddle.nn.Layer):
  30. def __init__(self, net, model_type):
  31. super(InferNet, self).__init__()
  32. self.net = net
  33. self.postprocessor = PostProcessor(model_type)
  34. def forward(self, x):
  35. net_outputs = self.net(x)
  36. outputs = self.postprocessor(net_outputs)
  37. return outputs