smooth_l1.py 1.81 KB
Newer Older
zhanggzh's avatar
zhanggzh committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
# Copyright 2022 The KerasCV Authors
#
# 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
#
#     https://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.

import tensorflow as tf


# --- Implementing Smooth L1 loss and Focal Loss as keras custom losses ---
class SmoothL1Loss(tf.keras.losses.Loss):
    """Implements Smooth L1 loss.

    SmoothL1Loss implements the SmoothL1 function, where values less than `l1_cutoff`
    contribute to the overall loss based on their squared difference, and values greater
    than l1_cutoff contribute based on their raw difference.

    Args:
        l1_cutoff: differences between y_true and y_pred that are larger than `l1_cutoff` are
            treated as `L1` values
    """

    def __init__(self, l1_cutoff=1.0, **kwargs):
        super().__init__(**kwargs)
        self.l1_cutoff = l1_cutoff

    def call(self, y_true, y_pred):
        difference = y_true - y_pred
        absolute_difference = tf.abs(difference)
        squared_difference = difference**2
        loss = tf.where(
            absolute_difference < self.l1_cutoff,
            0.5 * squared_difference,
            absolute_difference - 0.5,
        )
        return tf.keras.backend.mean(loss, axis=-1)

    def get_config(self):
        config = {
            "l1_cutoff": self.l1_cutoff,
        }
        base_config = super().get_config()
        return dict(list(base_config.items()) + list(config.items()))