24 """For each anchor, find the hardest positive and negative sample.
26 dist_mat: pair wise distance between samples, shape [N, M]
27 is_pos: positive index with shape [N, M]
28 is_neg: negative index with shape [N, M]
30 dist_ap: pytorch Variable, distance(anchor, positive); shape [N]
31 dist_an: pytorch Variable, distance(anchor, negative); shape [N]
32 p_inds: pytorch LongTensor, with shape [N];
33 indices of selected hard positive samples; 0 <= p_inds[i] <= N - 1
34 n_inds: pytorch LongTensor, with shape [N];
35 indices of selected hard negative samples; 0 <= n_inds[i] <= N - 1
36 NOTE: Only consider the case in which all labels have same num of samples,
37 thus we can cope with all anchors in parallel.
40 assert len(dist_mat.size()) == 2
57 dist_ap, relative_p_inds = torch.max(
58 dist_mat[is_pos].reshape(N,-1), 1, keepdim=
True)
62 dist_an, relative_n_inds = torch.min(
63 dist_mat[is_neg].reshape(N,-1), 1, keepdim=
True)
67 dist_ap = dist_ap.squeeze(1)
68 dist_an = dist_an.squeeze(1)
70 return dist_ap, dist_an
74 """For each anchor, find the weighted positive and negative sample.
76 dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N]
80 dist_ap: pytorch Variable, distance(anchor, positive); shape [N]
81 dist_an: pytorch Variable, distance(anchor, negative); shape [N]
83 assert len(dist_mat.size()) == 2
85 is_pos = is_pos.float()
86 is_neg = is_neg.float()
87 dist_ap = dist_mat * is_pos
88 dist_an = dist_mat * is_neg
93 dist_ap = torch.sum(dist_ap * weights_ap, dim=1)
94 dist_an = torch.sum(dist_an * weights_an, dim=1)
96 return dist_ap, dist_an
99def triplet_loss(embedding, targets, margin, norm_feat, hard_mining):
100 r"""Modified from Tong Xiao's open-reid (https://github.com/Cysu/open-reid).
101 Related Triplet Loss theory can be found in paper 'In Defense of the Triplet
102 Loss for Person Re-Identification'."""
104 if norm_feat: embedding = normalize(embedding, axis=-1)
107 if comm.get_world_size() > 1:
108 all_embedding = torch.cat(GatherLayer.apply(embedding), dim=0)
109 all_targets = concat_all_gather(targets)
111 all_embedding = embedding
112 all_targets = targets
114 dist_mat = euclidean_dist(embedding, all_embedding)
116 N, M = dist_mat.size()
117 is_pos = targets.view(N, 1).expand(N, M).eq(all_targets.view(M, 1).expand(M, N).t())
118 is_neg = targets.view(N, 1).expand(N, M).ne(all_targets.view(M, 1).expand(M, N).t())
125 y = dist_an.new().resize_as_(dist_an).fill_(1)
128 loss = F.margin_ranking_loss(dist_an, dist_ap, y, margin=margin)
130 loss = F.soft_margin_loss(dist_an - dist_ap, y)
132 if loss == float(
'Inf'): loss = F.margin_ranking_loss(dist_an, dist_ap, y, margin=0.3)