ssd.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Copyright (c) 2020 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from paddlex.ppdet.core.workspace import register, create
  18. from .meta_arch import BaseArch
  19. __all__ = ['SSD']
  20. @register
  21. class SSD(BaseArch):
  22. """
  23. Single Shot MultiBox Detector, see https://arxiv.org/abs/1512.02325
  24. Args:
  25. backbone (nn.Layer): backbone instance
  26. ssd_head (nn.Layer): `SSDHead` instance
  27. post_process (object): `BBoxPostProcess` instance
  28. """
  29. __category__ = 'architecture'
  30. __inject__ = ['post_process']
  31. def __init__(self, backbone, ssd_head, post_process):
  32. super(SSD, self).__init__()
  33. self.backbone = backbone
  34. self.ssd_head = ssd_head
  35. self.post_process = post_process
  36. @classmethod
  37. def from_config(cls, cfg, *args, **kwargs):
  38. # backbone
  39. backbone = create(cfg['backbone'])
  40. # head
  41. kwargs = {'input_shape': backbone.out_shape}
  42. ssd_head = create(cfg['ssd_head'], **kwargs)
  43. return {
  44. 'backbone': backbone,
  45. "ssd_head": ssd_head,
  46. }
  47. def _forward(self):
  48. # Backbone
  49. body_feats = self.backbone(self.inputs)
  50. # SSD Head
  51. if self.training:
  52. return self.ssd_head(body_feats, self.inputs['image'],
  53. self.inputs['gt_bbox'],
  54. self.inputs['gt_class'])
  55. else:
  56. preds, anchors = self.ssd_head(body_feats, self.inputs['image'])
  57. bbox, bbox_num = self.post_process(preds, anchors,
  58. self.inputs['im_shape'],
  59. self.inputs['scale_factor'])
  60. return bbox, bbox_num
  61. def get_loss(self, ):
  62. return {"loss": self._forward()}
  63. def get_pred(self):
  64. bbox_pred, bbox_num = self._forward()
  65. output = {
  66. "bbox": bbox_pred,
  67. "bbox_num": bbox_num,
  68. }
  69. return output