Differentiable Hamming Loss for TensorFlow

Viewed 762

The Hamming Loss counts the number of labels for which our prediction is wrong normalizing it.

Hamming loss

The standard implementation of the HammingLoss as a metric relies on counting the wrong predictions, with something along these lines: (on TF)

count_non_zero = tf.math.count_nonzero(actuals - predictions)
return tf.reduce_mean(count_non_zero / actuals.get_shape()[-1])

Implementing the Hamming Loss as an actual loss requires it to be differentiable, which is not this case due to the tf.math.count_nonzero. An alternative (and approximated) method would be counting the non-zero labels in this way, but unluckily the NN doesn't seem to improve.

def hamming_loss(y_true, y_pred):
  y_true = tf.convert_to_tensor(y_true, name="y_true")
  y_pred = tf.convert_to_tensor(y_pred, name="y_pred")

  diff = tf.cast(tf.math.abs(y_true - y_pred), dtype=tf.float32)

  #Counting non-zeros in a differentiable way
  epsilon = K.epsilon()
  nonzero = tf.reduce_mean(tf.math.abs( diff / (tf.math.abs(diff) + epsilon)))

  return tf.reduce_mean(nonzero / K.int_shape(y_pred)[-1])

Concluding, what's the correct implementation of the Hamming Loss for TensorFlow?

[.1] https://hal.archives-ouvertes.fr/hal-01044994/document

1 Answers

Your network doesn't converge since:

diff / (tf.math.abs(diff) + epsilon) 

yields a 0 , 1 vector which kills the gradients both on zeros and ones

Related