Contrastive loss differentiates images by similarity. The feature or latent layer is compared using a similarity metric and trained with the target for a similarity score. In the case of a positive pair, the target would be 0, as both inputs are the same. For negative pairs, the distance between the pair of latent is a maximum of 0 in the case of cosine distance or regularised Euclidean distance. The loss can be defined by a contrastive_loss, which is explained in the following code:
def contrastive_loss(model_1, model_2, label, margin=0.1): distance = tf.reduce_sum(tf.square(model_1 - model_2), 1) loss = label * tf.square( tf.maximum(0., margin - tf.sqrt(distance))) + (1 - label) * distance loss = 0.5 * tf.reduce_mean(loss) ...