infer_nets.py 1.5 KB

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