loss_utils.py 1.53 KB
Newer Older
Yeqing Li's avatar
Yeqing Li committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Zhenyu Tan's avatar
Zhenyu Tan 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

Zhenyu Tan's avatar
Zhenyu Tan committed
15
16
17
18
19
20
21
22
"""Losses utilities for detection models."""

import tensorflow as tf


def multi_level_flatten(multi_level_inputs, last_dim=None):
  """Flattens a multi-level input.

23
  Args:
Zhenyu Tan's avatar
Zhenyu Tan committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    multi_level_inputs: Ordered Dict with level to [batch, d1, ..., dm].
    last_dim: Whether the output should be [batch_size, None], or [batch_size,
      None, last_dim]. Defaults to `None`.

  Returns:
    Concatenated output [batch_size, None], or [batch_size, None, dm]
  """
  flattened_inputs = []
  batch_size = None
  for level in multi_level_inputs.keys():
    single_input = multi_level_inputs[level]
    if batch_size is None:
      batch_size = single_input.shape[0] or tf.shape(single_input)[0]
    if last_dim is not None:
      flattened_input = tf.reshape(single_input, [batch_size, -1, last_dim])
    else:
      flattened_input = tf.reshape(single_input, [batch_size, -1])
    flattened_inputs.append(flattened_input)
  return tf.concat(flattened_inputs, axis=1)