Last active
August 25, 2018 05:53
-
-
Save wenfahu/741d0c89c61e8d23738d1e234d22209e to your computer and use it in GitHub Desktop.
hard margin smooth hinge triplet loss
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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