Last active
May 25, 2020 14:35
-
-
Save pranjalg2308/6bfd49feec0cb5f50ade5fe3d89fec53 to your computer and use it in GitHub Desktop.
Implementation for Cosine similarity for triplet loss in keras
This file contains hidden or 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
# Cosine Similarity | |
def triplet_loss(alpha, emb_dim): | |
def loss(y_true, y_pred): | |
anc, pos, neg = y_pred[:,:emb_size], y_pred[:,emb_size:2*emb_size], y_pred[:,2*emb_size:] | |
distance1 = tf.keras.losses.cosine_similarity(anc, pos) | |
distance2 = tf.keras.losses.cosine_similarity(anc, neg) | |
return tf.keras.backend.clip(distance1 - distance2 + alpha, 0., None) | |
return loss |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment