basnet_losses.py 2 KB
Newer Older
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Gunho Park's avatar
Gunho Park committed
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# 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.

15
"""Losses used for BASNet models."""
Gunho Park's avatar
Gunho Park committed
16
17
18
19
import tensorflow as tf

EPSILON = 1e-5

20

Gunho Park's avatar
Gunho Park committed
21
22
23
24
25
26
27
28
29
30
31
32
33
class BASNetLoss:
  """BASNet hybrid loss."""

  def __init__(self):
    self._binary_crossentropy = tf.keras.losses.BinaryCrossentropy(
        reduction=tf.keras.losses.Reduction.SUM, from_logits=False)
    self._ssim = tf.image.ssim

  def __call__(self, sigmoids, labels):
    levels = sorted(sigmoids.keys())

    labels_bce = tf.squeeze(labels, axis=-1)
    labels = tf.cast(labels, tf.float32)
34

Gunho Park's avatar
Gunho Park committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    bce_losses = []
    ssim_losses = []
    iou_losses = []

    for level in levels:
      bce_losses.append(
          self._binary_crossentropy(labels_bce, sigmoids[level]))
      ssim_losses.append(
          1 - self._ssim(sigmoids[level], labels, max_val=1.0))
      iou_losses.append(
          self._iou_loss(sigmoids[level], labels))

    total_bce_loss = tf.math.add_n(bce_losses)
    total_ssim_loss = tf.math.add_n(ssim_losses)
    total_iou_loss = tf.math.add_n(iou_losses)
50

Gunho Park's avatar
Gunho Park committed
51
    total_loss = total_bce_loss + total_ssim_loss + total_iou_loss
Gunho Park's avatar
Gunho Park committed
52
    total_loss = total_loss / len(levels)
Gunho Park's avatar
Gunho Park committed
53
54
55
56
57

    return total_loss

  def _iou_loss(self, sigmoids, labels):
    total_iou_loss = 0
58
59
60
61
62
63

    intersection = tf.reduce_sum(sigmoids[:, :, :, :] * labels[:, :, :, :])
    union = tf.reduce_sum(sigmoids[:, :, :, :]) + tf.reduce_sum(
        labels[:, :, :, :]) - intersection
    iou = intersection / union
    total_iou_loss += 1-iou
Gunho Park's avatar
Gunho Park committed
64
65

    return total_iou_loss