tf.keras.losses.Hinge

Computes the hinge loss between y_true and y_pred.

Used in the notebooks

Used in the tutorials

loss = maximum(1 - y_true * y_pred, 0)

y_true values are expected to be -1 or 1. If binary (0 or 1) labels are provided we will convert them to -1 or 1.

Standalone usage:

y_true = [[0., 1.], [0., 0.]]
y_pred = [[0.6, 0.4], [0.4, 0.6]]
# Using 'auto'/'sum_over_batch_size' reduction type.
h = tf.keras.losses.Hinge()
h(y_true, y_pred).numpy()
1.3
# Calling with 'sample_weight'.
h(y_true, y_pred, sample_weight=[1, 0]).numpy()
0.55
# Using 'sum' reduction type.
h = tf.keras.losses.Hinge(
    reduction=tf.keras.losses.Reduction.SUM)
h(y_true, y_pred).numpy()
2.6
# Using 'none' reduction type.
h = tf.keras.losses.Hinge(
    reduction=tf.keras.losses.Reduction.NONE)
h(y_true, y_pred).numpy()
array([1.1, 1.5], dtype=float32)

Usage with the compile() API:

model.compile(optimizer='sgd', loss=tf.keras.losses.Hinge())