faster_rcnn.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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. import paddle
  18. from ppdet.core.workspace import register, create
  19. from .meta_arch import BaseArch
  20. import numpy as np
  21. __all__ = ['FasterRCNN']
  22. @register
  23. class FasterRCNN(BaseArch):
  24. """
  25. Faster R-CNN network, see https://arxiv.org/abs/1506.01497
  26. Args:
  27. backbone (object): backbone instance
  28. rpn_head (object): `RPNHead` instance
  29. bbox_head (object): `BBoxHead` instance
  30. bbox_post_process (object): `BBoxPostProcess` instance
  31. neck (object): 'FPN' instance
  32. """
  33. __category__ = 'architecture'
  34. __inject__ = ['bbox_post_process']
  35. def __init__(self,
  36. backbone,
  37. rpn_head,
  38. bbox_head,
  39. bbox_post_process,
  40. neck=None):
  41. super(FasterRCNN, self).__init__()
  42. self.backbone = backbone
  43. self.neck = neck
  44. self.rpn_head = rpn_head
  45. self.bbox_head = bbox_head
  46. self.bbox_post_process = bbox_post_process
  47. def init_cot_head(self, relationship):
  48. self.bbox_head.init_cot_head(relationship)
  49. @classmethod
  50. def from_config(cls, cfg, *args, **kwargs):
  51. backbone = create(cfg['backbone'])
  52. kwargs = {'input_shape': backbone.out_shape}
  53. neck = cfg['neck'] and create(cfg['neck'], **kwargs)
  54. out_shape = neck and neck.out_shape or backbone.out_shape
  55. kwargs = {'input_shape': out_shape}
  56. rpn_head = create(cfg['rpn_head'], **kwargs)
  57. bbox_head = create(cfg['bbox_head'], **kwargs)
  58. return {
  59. 'backbone': backbone,
  60. 'neck': neck,
  61. "rpn_head": rpn_head,
  62. "bbox_head": bbox_head,
  63. }
  64. def _forward(self):
  65. body_feats = self.backbone(self.inputs)
  66. if self.neck is not None:
  67. body_feats = self.neck(body_feats)
  68. if self.training:
  69. rois, rois_num, rpn_loss = self.rpn_head(body_feats, self.inputs)
  70. bbox_loss, _ = self.bbox_head(body_feats, rois, rois_num,
  71. self.inputs)
  72. return rpn_loss, bbox_loss
  73. else:
  74. rois, rois_num, _ = self.rpn_head(body_feats, self.inputs)
  75. preds, _ = self.bbox_head(body_feats, rois, rois_num, None)
  76. im_shape = self.inputs['im_shape']
  77. scale_factor = self.inputs['scale_factor']
  78. bbox, bbox_num = self.bbox_post_process(preds, (rois, rois_num),
  79. im_shape, scale_factor)
  80. # rescale the prediction back to origin image
  81. bboxes, bbox_pred, bbox_num = self.bbox_post_process.get_pred(
  82. bbox, bbox_num, im_shape, scale_factor)
  83. return bbox_pred, bbox_num
  84. def get_loss(self, ):
  85. rpn_loss, bbox_loss = self._forward()
  86. loss = {}
  87. loss.update(rpn_loss)
  88. loss.update(bbox_loss)
  89. total_loss = paddle.add_n(list(loss.values()))
  90. loss.update({'loss': total_loss})
  91. return loss
  92. def get_pred(self):
  93. bbox_pred, bbox_num = self._forward()
  94. output = {'bbox': bbox_pred, 'bbox_num': bbox_num}
  95. return output
  96. def target_bbox_forward(self, data):
  97. body_feats = self.backbone(data)
  98. if self.neck is not None:
  99. body_feats = self.neck(body_feats)
  100. rois = [roi for roi in data['gt_bbox']]
  101. rois_num = paddle.concat([paddle.shape(roi)[0] for roi in rois])
  102. preds, _ = self.bbox_head(body_feats, rois, rois_num, None, cot=True)
  103. return preds
  104. def relationship_learning(self, loader, num_classes_novel):
  105. print('computing relationship')
  106. train_labels_list = []
  107. label_list = []
  108. for step_id, data in enumerate(loader):
  109. _, bbox_prob = self.target_bbox_forward(data)
  110. batch_size = data['im_id'].shape[0]
  111. for i in range(batch_size):
  112. num_bbox = data['gt_class'][i].shape[0]
  113. train_labels = data['gt_class'][i]
  114. train_labels_list.append(train_labels.numpy().squeeze(1))
  115. base_labels = bbox_prob.detach().numpy()[:,:-1]
  116. label_list.append(base_labels)
  117. labels = np.concatenate(train_labels_list, 0)
  118. probabilities = np.concatenate(label_list, 0)
  119. N_t = np.max(labels) + 1
  120. conditional = []
  121. for i in range(N_t):
  122. this_class = probabilities[labels == i]
  123. average = np.mean(this_class, axis=0, keepdims=True)
  124. conditional.append(average)
  125. return np.concatenate(conditional)