Skip to content

Instantly share code, notes, and snippets.

@wenfahu
Last active August 25, 2018 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wenfahu/741d0c89c61e8d23738d1e234d22209e to your computer and use it in GitHub Desktop.
Save wenfahu/741d0c89c61e8d23738d1e234d22209e to your computer and use it in GitHub Desktop.
hard margin smooth hinge triplet loss
def triplet_loss(anchor, positive, negative, alpha):
"""Calculate the triplet loss according to the FaceNet paper
Args:
anchor: the embeddings for the anchor images.
positive: the embeddings for the positive images.
negative: the embeddings for the negative images.
Returns:
the triplet loss according to the FaceNet paper as a float tensor.
"""
with tf.variable_scope('triplet_loss'):
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), 1)
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), 1)
diff = tf.subtract(pos_dist, neg_dist)
loss = tf.relu(tf.add(diff, alpha))
quad = tf.minimum(loss, 2*alpha)
loss = tf.square(quad) + 4 * alpha *(loss - quad)
loss = tf.reduce_mean(loss )
return loss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment