Skip to content

Instantly share code, notes, and snippets.

@TheLoneNut
Created February 15, 2018 15:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheLoneNut/af657c294a2f41e253683bb1514bf674 to your computer and use it in GitHub Desktop.
Save TheLoneNut/af657c294a2f41e253683bb1514bf674 to your computer and use it in GitHub Desktop.
def triplet_loss(y_true, y_pred, alpha = 0.2):
    """
    Implementation of the triplet loss function
    Arguments:
    y_true -- true labels, required when you define a loss in Keras, not used in this function.
    y_pred -- python list containing three objects:
            anchor:   the encodings for the anchor data
            positive: the encodings for the positive data (similar to anchor)
            negative: the encodings for the negative data (different from anchor)
    Returns:
    loss -- real number, value of the loss
    """
    anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
    # distance between the anchor and the positive
    pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,positive)))
    # distance between the anchor and the negative
    neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,negative)))
    # compute loss
    basic_loss = pos_dist-neg_dist+alpha
    loss = tf.maximum(basic_loss,0.0)
    return loss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment