retinanet_model.py 5.29 KB
Newer Older
Yeqing Li's avatar
Yeqing Li committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
2
3
4
5
6
7
8
9
10
11
12
13
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Yeqing Li's avatar
Yeqing Li committed
14

Abdullah Rashwan's avatar
Abdullah Rashwan committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""RetinaNet."""

# Import libraries
import tensorflow as tf


@tf.keras.utils.register_keras_serializable(package='Vision')
class RetinaNetModel(tf.keras.Model):
  """The RetinaNet model class."""

  def __init__(self,
               backbone,
               decoder,
               head,
               detection_generator,
               **kwargs):
    """Classification initialization function.

    Args:
      backbone: `tf.keras.Model` a backbone network.
      decoder: `tf.keras.Model` a decoder network.
      head: `RetinaNetHead`, the RetinaNet head.
      detection_generator: the detection generator.
      **kwargs: keyword arguments to be passed.
    """
    super(RetinaNetModel, self).__init__(**kwargs)
    self._config_dict = {
        'backbone': backbone,
        'decoder': decoder,
        'head': head,
        'detection_generator': detection_generator,
    }
    self._backbone = backbone
    self._decoder = decoder
    self._head = head
    self._detection_generator = detection_generator

  def call(self,
           images,
           image_shape=None,
           anchor_boxes=None,
           training=None):
    """Forward pass of the RetinaNet model.

    Args:
      images: `Tensor`, the input batched images, whose shape is
        [batch, height, width, 3].
      image_shape: `Tensor`, the actual shape of the input images, whose shape
        is [batch, 2] where the last dimension is [height, width]. Note that
        this is the actual image shape excluding paddings. For example, images
        in the batch may be resized into different shapes before padding to the
        fixed size.
      anchor_boxes: a dict of tensors which includes multilevel anchors.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
68
        - key: `str`, the level of the multilevel predictions.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
69
70
71
72
73
74
        - values: `Tensor`, the anchor coordinates of a particular feature
            level, whose shape is [height_l, width_l, num_anchors_per_location].
      training: `bool`, indicating whether it is in training mode.

    Returns:
      scores: a dict of tensors which includes scores of the predictions.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
75
        - key: `str`, the level of the multilevel predictions.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
76
77
78
79
        - values: `Tensor`, the box scores predicted from a particular feature
            level, whose shape is
            [batch, height_l, width_l, num_classes * num_anchors_per_location].
      boxes: a dict of tensors which includes coordinates of the predictions.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
80
        - key: `str`, the level of the multilevel predictions.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
81
82
83
        - values: `Tensor`, the box coordinates predicted from a particular
            feature level, whose shape is
            [batch, height_l, width_l, 4 * num_anchors_per_location].
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
84
85
86
87
88
89
      attributes: a dict of (attribute_name, attribute_predictions). Each
        attribute prediction is a dict that includes:
        - key: `str`, the level of the multilevel predictions.
        - values: `Tensor`, the attribute predictions from a particular
            feature level, whose shape is
            [batch, height_l, width_l, att_size * num_anchors_per_location].
Abdullah Rashwan's avatar
Abdullah Rashwan committed
90
91
92
93
94
95
    """
    # Feature extraction.
    features = self.backbone(images)
    if self.decoder:
      features = self.decoder(features)

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
96
97
    # Dense prediction. `raw_attributes` can be empty.
    raw_scores, raw_boxes, raw_attributes = self.head(features)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
98
99
100
101
102

    if training:
      return {
          'cls_outputs': raw_scores,
          'box_outputs': raw_boxes,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
103
          'att_outputs': raw_attributes,
Abdullah Rashwan's avatar
Abdullah Rashwan committed
104
105
106
      }
    else:
      # Post-processing.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
107
108
109
      final_results = self.detection_generator(raw_boxes, raw_scores,
                                               anchor_boxes, image_shape,
                                               raw_attributes)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
110
111
112
113
      return {
          'detection_boxes': final_results['detection_boxes'],
          'detection_scores': final_results['detection_scores'],
          'detection_classes': final_results['detection_classes'],
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
114
          'detection_attributes': final_results['detection_attributes'],
Abdullah Rashwan's avatar
Abdullah Rashwan committed
115
116
          'num_detections': final_results['num_detections'],
          'cls_outputs': raw_scores,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
117
118
          'box_outputs': raw_boxes,
          'att_outputs': raw_attributes,
Abdullah Rashwan's avatar
Abdullah Rashwan committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
      }

  @property
  def checkpoint_items(self):
    """Returns a dictionary of items to be additionally checkpointed."""
    items = dict(backbone=self.backbone, head=self.head)
    if self.decoder is not None:
      items.update(decoder=self.decoder)

    return items

  @property
  def backbone(self):
    return self._backbone

  @property
  def decoder(self):
    return self._decoder

  @property
  def head(self):
    return self._head

  @property
  def detection_generator(self):
    return self._detection_generator

  def get_config(self):
    return self._config_dict

  @classmethod
  def from_config(cls, config):
    return cls(**config)