def test_smooth( self, value: float, smooth_nr: float, smooth_dr: float, expected: float, ): """ Test values in extreme cases where numerator/denominator are all zero. :param value: value for input. :param smooth_nr: constant for numerator. :param smooth_dr: constant for denominator. :param expected: target value. """ shape = (1, 10) y_true = tf.ones(shape=shape) * value y_pred = tf.ones(shape=shape) * value got = label.JaccardIndex(smooth_nr=smooth_nr, smooth_dr=smooth_dr).call( y_true, y_pred, ) expected = tf.constant(expected) assert is_equal_tf(got[0], expected)
def test_get_config(self): got = label.JaccardIndex().get_config() expected = dict( binary=False, scales=None, kernel="gaussian", reduction=tf.keras.losses.Reduction.SUM, name="JaccardIndex", ) assert got == expected
def test_call(self, y_true, y_pred, binary, scales, expected): expected = np.array([expected] * self.shape[0]) # call returns (batch, ) got = label.JaccardIndex(binary=binary, scales=scales).call(y_true=y_true, y_pred=y_pred) assert is_equal_tf(got, expected) got = label.JaccardLoss(binary=binary, scales=scales).call(y_true=y_true, y_pred=y_pred) assert is_equal_tf(got, -expected)
def test_get_config(self): got = label.JaccardIndex().get_config() expected = dict( binary=False, background_weight=0.0, smooth_nr=1e-5, smooth_dr=1e-5, reduction=tf.keras.losses.Reduction.AUTO, name="JaccardIndex", ) assert got == expected
def test_exact_value(self, binary: bool, background_weight: float, shape: Tuple): """ Test Jaccard index by comparing at ground truth values. :param binary: if project labels to binary values. :param background_weight: the weight of background class. :param shape: shape of input. """ # init shape = (1, ) + shape # add batch axis foreground_weight = 1 - background_weight tf.random.set_seed(0) y_true = tf.random.uniform(shape=shape) y_pred = tf.random.uniform(shape=shape) # obtained value got = label.JaccardIndex( binary=binary, background_weight=background_weight, ).call(y_true=y_true, y_pred=y_pred) # expected value flatten = tf.keras.layers.Flatten() y_true = flatten(y_true) y_pred = flatten(y_pred) if binary: y_true = tf.cast(y_true >= 0.5, dtype=y_true.dtype) y_pred = tf.cast(y_pred >= 0.5, dtype=y_pred.dtype) num = foreground_weight * tf.reduce_sum( y_true * y_pred, axis=1) + background_weight * tf.reduce_sum( (1 - y_true) * (1 - y_pred), axis=1) denom = foreground_weight * tf.reduce_sum( y_true + y_pred, axis=1) + background_weight * tf.reduce_sum( (1 - y_true) + (1 - y_pred), axis=1) denom = denom - num expected = (num + EPS) / (denom + EPS) assert is_equal_tf(got, expected)