infer_nets.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. self.model_type = model_type
  18. def forward(self, net_outputs):
  19. if self.model_type == 'classifier':
  20. outputs = paddle.nn.functional.softmax(net_outputs, axis=1)
  21. elif self.model_type == 'segmenter':
  22. outputs = paddle.squeeze(paddle.nn.functional.softmax(net_outputs, axis=1)), \
  23. paddle.squeeze(paddle.argmax(net_outputs, axis=1))
  24. else:
  25. outputs = net_outputs
  26. return outputs
  27. class InferNet(paddle.nn.Layer):
  28. def __init__(self, net, model_type):
  29. super(InferNet, self).__init__()
  30. self.net = net
  31. self.postprocessor = PostProcessor(model_type)
  32. def forward(self, x):
  33. net_outputs = self.net(x)
  34. outputs = self.postprocessor(net_outputs)
  35. return outputs