-
Notifications
You must be signed in to change notification settings - Fork 9
/
loss.py
212 lines (153 loc) · 7.38 KB
/
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import torch
import torch.nn as nn
class MLDL_Loss(object):
def __init__(self, args, k=5, cuda=True):
self.args = args
self.NetworkStructure = args['NetworkStructure']
self.latent_index = 2 * len(args['NetworkStructure']) - 3
self.device = cuda
self.epoch = 0
def SetEpoch(self, epoch):
self.epoch = epoch
def Epsilonball(self, data):
"""
function used to calculate the distance between point pairs and determine the neighborhood with r-ball
Arguments:
data {tensor} -- the train data
Outputs:
d {tensor} -- the distance between point pairs
kNN_mask {tensor} a mask used to determine the neighborhood of every data point
"""
Epsilon = self.args['Epsilon']
x = data.to(self.device)
y = data.to(self.device)
m, n = x.size(0), y.size(0)
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()
dist = xx + yy
# dist.addmm_(1, -2, x, y.t())
dist = torch.addmm(dist, mat1=x, mat2=y.t(),beta=1, alpha=-2)
d = dist.clamp(min=1e-8).sqrt()
kNN_mask = (d < Epsilon).bool()
return d, kNN_mask
def KNNGraph(self, data):
"""
another function used to calculate the distance between point pairs and determine the neighborhood
Arguments:
data {tensor} -- the train data
Outputs:
d {tensor} -- the distance between point pairs
kNN_mask {tensor} a mask used to determine the neighborhood of every data point
"""
k = self.args['MAEK']
batch_size = data.shape[0]
x = data.to(self.device)
y = data.to(self.device)
m, n = x.size(0), y.size(0)
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()
dist = xx + yy
# dist.addmm_(1, -2, x, y.t())
dist = torch.addmm(dist, mat1=x, mat2=y.t(),beta=1, alpha=-2)
d = dist.clamp(min=1e-8).sqrt() # for numerical stabili
s_, indices = torch.sort(d, dim=1)
indices = indices[:, :k+1]
kNN_mask = torch.zeros((batch_size, batch_size,), device=self.device).scatter(1, indices, 1)
kNN_mask[torch.eye(kNN_mask.shape[0], dtype=int)] = 0
return d, kNN_mask.bool()
# Using the reconstruction loss as Loss_ae
def ReconstructionLoss(self, pred, target):
criterion = nn.MSELoss().cuda()
loss = criterion(pred, target)
return loss
def DistanceLoss(self, data, latent, dis_data, dis_latent, kNN_data, kNN_latent):
"""
function used to calculate loss_iso and loss_push-away
Arguments:
data {tensor} -- the data for input layer data
latent {tensor} -- the data for latent layer data
dis_data {tensor} -- the distance between point pairs for input layer data
dis_latent {tensor} -- the distance between point pairs for latent layer data
kNN_data {tensor} -- the mask to determine the neighborhood for input layer data
kNN_latent {tensor} -- the mask to determine the neighborhood for latent layer data
"""
if 'Spheres' in self.args['DATASET'] and self.args['Mode'] == 'ML-AE':
kNN_data = kNN_latent + kNN_data
norml_data = 1
norml_latent = 1
else:
norml_data = torch.sqrt(torch.tensor(float(data.shape[1])))
norml_latent = torch.sqrt(torch.tensor(float(latent.shape[1])))
# Calculate Loss_iso
D1_1 = (dis_data/norml_data)[kNN_data]
D1_2 = (dis_latent/norml_latent)[kNN_data]
Error1 = (D1_1 - D1_2) / 1
loss_iso = torch.norm(Error1)/torch.sum(kNN_data)
# Calculate Loss_push-away
D2_1 = (dis_latent/norml_latent)[kNN_data == False]
if 'MNIST' in self.args['DATASET']:
Error2 = (0 - torch.log(1+D2_1)) / 1
else:
Error2 = (0 - D2_1) / 1
loss_push_away = torch.norm(Error2[Error2 > -1 * self.args['RegularB']]) / torch.sum(kNN_data == False)
# The gradual changing of weight for Loss_push-away
if self.epoch > self.args['GradualChanging'][0]:
self.push_away = max(0.80 - (self.epoch - self.args['GradualChanging'][0]) / (self.args['GradualChanging'][1] - self.args['GradualChanging'][0]) * 0.80, 0)
else:
self.push_away = 0.80
loss_push_away = -1.0 * self.push_away * loss_push_away
return loss_iso, loss_push_away
# Calculating the Angle Matrix
def CossimiSlow(self, data):
eps = 1e-8
a_n, b_n = data.norm(dim=1)[:, None], data.norm(dim=1)[:, None]
a_norm = data / torch.max(a_n, eps * torch.ones_like(a_n))
b_norm = data / torch.max(b_n, eps * torch.ones_like(b_n))
out = torch.mm(a_norm, b_norm.transpose(0, 1))
return out
# Calculating the Loss_angle
def AngleLossSlow(self, data, latent, kNN_data, kNN_latent):
angle_loss = torch.zeros(data.shape[0], device=self.device)
for i in range(data.shape[0]):
center = data[i]
other = data[kNN_data[i]] - center
angle1 = self.CossimiSlow(other)
center = latent[i]
other = latent[kNN_data[i]] - center
angle2 = self.CossimiSlow(other)
angle_loss[i] = torch.norm(angle1 - angle2)/data.shape[0]
return torch.mean(angle_loss)
def MorphicLossItem(self, data, latent):
if 'MNIST' in self.args['DATASET'] or ('Spheres' in self.args['DATASET'] and self.args['Mode'] == 'ML-AE'):
dis_data, kNN_data = self.KNNGraph(data)
dis_latent, kNN_latent = self.KNNGraph(latent)
else:
dis_data, kNN_data = self.Epsilonball(data)
dis_latent, kNN_latent = self.Epsilonball(latent)
loss_iso, loss_push_away = self.DistanceLoss(data, latent, dis_data, dis_latent, kNN_data, kNN_latent)
if self.args['ratio'][2] < 0.01:
loss_ang = loss_iso / 100000
else:
loss_ang = self.AngleLossSlow(data, latent, kNN_data, kNN_latent)
return loss_iso, loss_ang, loss_push_away
def CalLosses(self, train_info):
"""
function used to calculate four losses
Arguments:
train_info {tensor} -- results for each intermediate layer in the network
Outputs:
loss_list {list} -- four losses: loss_ae, loss_iso, loss_angle, loss_push-away
"""
train_info[0] = train_info[0].view(train_info[0].shape[0], -1)
loss_ae = self.ReconstructionLoss(train_info[0], train_info[-1])
if 'Spheres' not in self.args['DATASET']:
loss_ae += self.ReconstructionLoss(train_info[2], train_info[-2])
loss_ae += self.ReconstructionLoss(train_info[4], train_info[-4])
loss_ae += self.ReconstructionLoss(train_info[6], train_info[-6])
loss_ae += self.ReconstructionLoss(train_info[8], train_info[-8])
loss_distance, loss_ang, loss_mutex = self.MorphicLossItem(train_info[0], train_info[self.latent_index])
loss_list = [loss_ae, loss_distance, loss_ang, loss_mutex]
# Weights for losses
for i in range(len(loss_list)):
loss_list[i] *= self.args['ratio'][i]
return loss_list