-
Notifications
You must be signed in to change notification settings - Fork 373
/
triplet_loss.py
36 lines (28 loc) · 1 KB
/
triplet_loss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import torch
import torch.nn as nn
class TripletLoss(nn.Module):
'''
Compute normal triplet loss or soft margin triplet loss given triplets
'''
def __init__(self, margin=None):
super(TripletLoss, self).__init__()
self.margin = margin
if self.margin is None: # if no margin assigned, use soft-margin
self.Loss = nn.SoftMarginLoss()
else:
self.Loss = nn.TripletMarginLoss(margin=margin, p=2)
def forward(self, anchor, pos, neg):
if self.margin is None:
num_samples = anchor.shape[0]
y = torch.ones((num_samples, 1)).view(-1)
if anchor.is_cuda: y = y.cuda()
ap_dist = torch.norm(anchor-pos, 2, dim=1).view(-1)
an_dist = torch.norm(anchor-neg, 2, dim=1).view(-1)
loss = self.Loss(an_dist - ap_dist, y)
else:
loss = self.Loss(anchor, pos, neg)
return loss
if __name__ == '__main__':
pass