Skip to content

Instantly share code, notes, and snippets.

@oscar-defelice
Last active June 3, 2020 07:40
Show Gist options
  • Save oscar-defelice/8bda457c145e01f3fac40b30aef835ce to your computer and use it in GitHub Desktop.
Save oscar-defelice/8bda457c145e01f3fac40b30aef835ce to your computer and use it in GitHub Desktop.
class TripletLossLayer(Layer):
"""
Layer object to minimise the triplet loss.
Here we implement the Bayesian Personal Ranking triplet loss.
"""
def __init__(self, **kwargs):
super(TripletLossLayer, self).__init__(**kwargs)
def bpr_triplet_loss(self, inputs):
"""
Bayesian Personal Ranking triplet loss.
We actually use log-loss for numerical purposes.
"""
anchor, positive, negative = inputs
p_dist = K.sum(anchor*positive, axis=-1, keepdims=True)
n_dist = K.sum(anchor*negative, axis=-1, keepdims=True)
return K.log(1.0 - K.sigmoid(p_dist - n_dist))
def call(self, inputs):
loss = self.bpr_triplet_loss(inputs)
self.add_loss(loss)
return loss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment