Last active
June 3, 2020 07:40
-
-
Save oscar-defelice/8bda457c145e01f3fac40b30aef835ce to your computer and use it in GitHub Desktop.
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
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