-
Notifications
You must be signed in to change notification settings - Fork 0
/
ordinal_loss.py
94 lines (64 loc) · 2.42 KB
/
ordinal_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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
import torch
import torch.nn.functional as F
from torchmetrics.functional import pairwise_manhattan_distance
def order_loss(features, y):
if features.shape[0]>1:
features = F.normalize(features, dim=1)
distance = triu_up(pairwise_manhattan_distance(features, features))
weights = triu_up(pairwise_manhattan_distance(y, y))
has_same_label = 0 in weights
if features.shape[0]>1:
weights_max, weights_min = torch.max(weights), torch.min(weights)
if weights_min == weights_max == 0:
weights_max = 1
weights = ((weights - weights_min)/weights_max)
distance = distance*weights
loss = - torch.mean(distance)
return loss
def euclidean_loss(features, y):
if features.shape[0]>1:
features = F.normalize(features, dim=1)
distance = triu_up(euclidean_distance(features, features))
weights = triu_up(euclidean_distance(y, y))
has_same_label = 0 in weights
if features.shape[0]>1:
weights_max, weights_min = torch.max(weights), torch.min(weights)
weights = ((weights - weights_min)/weights_max)
# if has_same_label:
# weights = torch.where(weights == 0, -1, weights)
distance = distance*weights
loss = - torch.mean(distance)
return loss
def order_loss_p(features, y, p=float(1/2)):
if features.shape[0]>1:
features = F.normalize(features, dim=1)
distance = triu_up(distance_p(features, features, p))
weights = triu_up(distance_p(y, y, p))
has_same_label = 0 in weights
if features.shape[0]>1:
weights_max, weights_min = torch.max(weights), torch.min(weights)
weights = ((weights - weights_min)/weights_max)
# if has_same_label:
# weights = torch.where(weights == 0, -1, weights)
distance = distance*weights
loss = - torch.mean(distance)
return loss
def distance_p(x, y, p):
x, y = x.type(torch.FloatTensor), y.type(torch.FloatTensor)
distance = torch.cdist(x, y, p=p)
return distance
def euclidean_distance(x, y):
x, y = x.type(torch.FloatTensor), y.type(torch.FloatTensor)
distance = torch.cdist(x, y, p=2.0)
return distance
def triu_up(dist):
a, b = dist.shape
assert a == b
indexes = torch.triu(torch.ones(a, b), diagonal=1).to(torch.bool)
return dist[indexes]
if __name__ == "__main__":
# x = torch.tensor([[1, 1], [2, 2], [3, 3], [4, 4]]).type(torch.FloatTensor)
# y = torch.tensor([[1], [2], [3], [4]]).type(torch.FloatTensor)
x = torch.tensor([[1, 1], [2, 2], [3, 3]]).type(torch.FloatTensor)
y = torch.tensor([[1], [1], [1]]).type(torch.FloatTensor)
print(order_loss(x, y))