Contrastive loss

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) ...

Get Python: Advanced Guide to Artificial Intelligence now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.