Skip to content

Commit bcb85b7

Browse files
committed
Merge branch 'staging'
2 parents fbbdf55 + 50f895d commit bcb85b7

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

lib/model/losses/loss.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ class FocalFrequencyLoss(): # pylint:disable=too-few-public-methods
4444
batch_matrix: bool, Optional
4545
``True`` to calculate the spectrum weight matrix using batch-based statistics otherwise
4646
``False``. Default: ``False``
47+
epsilon : float, Optional
48+
Small epsilon for safer weights scaling division. Default: `1e-6`
49+
4750
4851
References
4952
----------
@@ -56,13 +59,15 @@ def __init__(self,
5659
patch_factor: int = 1,
5760
ave_spectrum: bool = False,
5861
log_matrix: bool = False,
59-
batch_matrix: bool = False) -> None:
62+
batch_matrix: bool = False,
63+
epsilon: float = 1e-6) -> None:
6064
self._alpha = alpha
6165
# TODO Fix bug where FFT will be incorrect if patch_factor > 1
6266
self._patch_factor = patch_factor
6367
self._ave_spectrum = ave_spectrum
6468
self._log_matrix = log_matrix
6569
self._batch_matrix = batch_matrix
70+
self._epsilon = epsilon
6671
self._dims: tuple[int, int] = (0, 0)
6772

6873
def _get_patches(self, inputs: tf.Tensor) -> tf.Tensor:
@@ -145,11 +150,11 @@ def _get_weight_matrix(self, freq_true: tf.Tensor, freq_pred: tf.Tensor) -> tf.T
145150
weights = K.log(weights + 1.0)
146151

147152
if self._batch_matrix: # calculate the spectrum weight matrix using batch-based statistics
148-
weights = weights / K.max(weights)
153+
scale = K.max(weights)
149154
else:
150-
weights = weights / K.max(K.max(weights, axis=-2), axis=-2)[..., None, None, :]
155+
scale = K.max(weights, axis=(-2, -3), keepdims=True)
156+
weights = weights / K.maximum(scale, self._epsilon)
151157

152-
weights = K.switch(tf.math.is_nan(weights), K.zeros_like(weights), weights)
153158
weights = K.clip(weights, min_value=0.0, max_value=1.0)
154159

155160
return weights

0 commit comments

Comments
 (0)