Skip to content

Instantly share code, notes, and snippets.

@amineHY
Last active April 24, 2019 12:07
Show Gist options
  • Save amineHY/ffeb2d68b20f4255b14cfe3ad09cadff to your computer and use it in GitHub Desktop.
Save amineHY/ffeb2d68b20f4255b14cfe3ad09cadff to your computer and use it in GitHub Desktop.
This function implement the computation of the triplet loss function for the face recognition application
def triplet_loss_function(im_anchor, im_positive, im_negative, alpha = 0.2):
"""
Implementation of the triplet loss function
Source: https://arxiv.org/pdf/1503.03832.pdf
Arguments:
y_pred -- python list containing three objects:
anchor -- the encodings for the anchor images, of shape (None, 128)
positive -- the encodings for the positive images, of shape (None, 128)
negative -- the encodings for the negative images, of shape (None, 128)
Returns:
loss -- real number, value of the loss
"""
# Compute the (encoding) distance between the anchor and the positive, then negative images
pos_dist = tf.reduce_sum(tf.square(tf.subtract(im_anchor, im_positive)), axis=-1)
neg_dist = tf.reduce_sum(tf.square(tf.subtract(im_anchor, im_negative)), axis=-1)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
return tf.reduce_sum(tf.maximum(basic_loss, 0.0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment