This repository was archived by the owner on Dec 5, 2022. It is now read-only.
forked from euwern/proxynca_pp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloss.py
More file actions
83 lines (67 loc) · 2.58 KB
/
loss.py
File metadata and controls
83 lines (67 loc) · 2.58 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from similarity import pairwise_distance
import torch
import torch.nn.functional as F
import numpy as np
import torch.nn as nn
import copy
import math
def binarize_and_smooth_labels(T, nb_classes, smoothing_const = 0):
import sklearn.preprocessing
T = T.cpu().numpy()
T = sklearn.preprocessing.label_binarize(
T, classes = range(0, nb_classes)
)
T = T * (1 - smoothing_const)
T[T == 0] = smoothing_const / (nb_classes - 1)
T = torch.FloatTensor(T).cuda()
return T
class ProxyNCA_classic(torch.nn.Module):
def __init__(self, nb_classes, sz_embed, scale, **kwargs):
torch.nn.Module.__init__(self)
self.proxies = torch.nn.Parameter(torch.randn(nb_classes, sz_embed) / 8)
self.scale = scale
def forward(self, X, T):
P = self.proxies
#note: self.scale is equal to sqrt(1/T)
# in the paper T = 1/9, therefore, scale = sart(1/(1/9)) = sqrt(9) = 3
# we need to apply sqrt because the pairwise distance is calculated as norm^2
P = self.scale * F.normalize(P, p = 2, dim = -1)
X = self.scale * F.normalize(X, p = 2, dim = -1)
D = pairwise_distance(
torch.cat(
[X, P]
),
squared = True
)[:X.size()[0], X.size()[0]:]
T = binarize_and_smooth_labels(
T = T, nb_classes = len(P), smoothing_const = 0
)
loss1 = torch.sum(T * torch.exp(-D), -1)
loss2 = torch.sum((1-T) * torch.exp(-D), -1)
loss = -torch.log(loss1/loss2)
loss = loss.mean()
return loss
class ProxyNCA_prob(torch.nn.Module):
def __init__(self, nb_classes, sz_embed, scale, **kwargs):
torch.nn.Module.__init__(self)
self.proxies = torch.nn.Parameter(torch.randn(nb_classes, sz_embed) / 8)
self.scale = scale
def forward(self, X, T):
P = self.proxies
#note: self.scale is equal to sqrt(1/T)
# in the paper T = 1/9, therefore, scale = sart(1/(1/9)) = sqrt(9) = 3
# we need to apply sqrt because the pairwise distance is calculated as norm^2
P = self.scale * F.normalize(P, p = 2, dim = -1)
X = self.scale * F.normalize(X, p = 2, dim = -1)
D = pairwise_distance(
torch.cat(
[X, P]
),
squared = True
)[:X.size()[0], X.size()[0]:]
T = binarize_and_smooth_labels(
T = T, nb_classes = len(P), smoothing_const = 0
)
loss = torch.sum(- T * F.log_softmax(-D, -1), -1)
loss = loss.mean()
return loss