Created
November 5, 2020 14:38
-
-
Save kongzii/0a108b115179cc17d58c158a94465a3c to your computer and use it in GitHub Desktop.
Contrastive Loss function in PyTorch
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 criterion(x1, x2, label, margin: float = 1.0): | |
""" | |
Computes Contrastive Loss | |
""" | |
dist = torch.nn.functional.pairwise_distance(x1, x2) | |
loss = (1 - label) * torch.pow(dist, 2) \ | |
+ (label) * torch.pow(torch.clamp(margin - dist, min=0.0), 2) | |
loss = torch.mean(loss) | |
return loss |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment