-
Notifications
You must be signed in to change notification settings - Fork 51
/
losses.py
284 lines (226 loc) · 10.8 KB
/
losses.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
__copyright__ = \
"""
Copyright ©right © (c) 2019 The Board of Trustees of Purdue University and the Purdue Research Foundation.
All rights reserved.
This software is covered by US patents and copyright.
This source code is to be used for academic research purposes only, and no commercial use is allowed.
For any questions, please contact Edward J. Delp ([email protected]) at Purdue University.
Last Modified: 10/02/2019
"""
__license__ = "CC BY-NC-SA 4.0"
__authors__ = "Javier Ribera, David Guera, Yuhao Chen, Edward J. Delp"
__version__ = "1.6.0"
import math
import torch
from sklearn.utils.extmath import cartesian
import numpy as np
from torch.nn import functional as F
import os
import time
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.neighbors.kde import KernelDensity
import skimage.io
from matplotlib import pyplot as plt
from torch import nn
torch.set_default_dtype(torch.float32)
def _assert_no_grad(variables):
for var in variables:
assert not var.requires_grad, \
"nn criterions don't compute the gradient w.r.t. targets - please " \
"mark these variables as volatile or not requiring gradients"
def cdist(x, y):
"""
Compute distance between each pair of the two collections of inputs.
:param x: Nxd Tensor
:param y: Mxd Tensor
:res: NxM matrix where dist[i,j] is the norm between x[i,:] and y[j,:],
i.e. dist[i,j] = ||x[i,:]-y[j,:]||
"""
differences = x.unsqueeze(1) - y.unsqueeze(0)
distances = torch.sum(differences**2, -1).sqrt()
return distances
def averaged_hausdorff_distance(set1, set2, max_ahd=np.inf):
"""
Compute the Averaged Hausdorff Distance function
between two unordered sets of points (the function is symmetric).
Batches are not supported, so squeeze your inputs first!
:param set1: Array/list where each row/element is an N-dimensional point.
:param set2: Array/list where each row/element is an N-dimensional point.
:param max_ahd: Maximum AHD possible to return if any set is empty. Default: inf.
:return: The Averaged Hausdorff Distance between set1 and set2.
"""
if len(set1) == 0 or len(set2) == 0:
return max_ahd
set1 = np.array(set1)
set2 = np.array(set2)
assert set1.ndim == 2, 'got %s' % set1.ndim
assert set2.ndim == 2, 'got %s' % set2.ndim
assert set1.shape[1] == set2.shape[1], \
'The points in both sets must have the same number of dimensions, got %s and %s.'\
% (set2.shape[1], set2.shape[1])
d2_matrix = pairwise_distances(set1, set2, metric='euclidean')
res = np.average(np.min(d2_matrix, axis=0)) + \
np.average(np.min(d2_matrix, axis=1))
return res
class AveragedHausdorffLoss(nn.Module):
def __init__(self):
super(nn.Module, self).__init__()
def forward(self, set1, set2):
"""
Compute the Averaged Hausdorff Distance function
between two unordered sets of points (the function is symmetric).
Batches are not supported, so squeeze your inputs first!
:param set1: Tensor where each row is an N-dimensional point.
:param set2: Tensor where each row is an N-dimensional point.
:return: The Averaged Hausdorff Distance between set1 and set2.
"""
assert set1.ndimension() == 2, 'got %s' % set1.ndimension()
assert set2.ndimension() == 2, 'got %s' % set2.ndimension()
assert set1.size()[1] == set2.size()[1], \
'The points in both sets must have the same number of dimensions, got %s and %s.'\
% (set2.size()[1], set2.size()[1])
d2_matrix = cdist(set1, set2)
# Modified Chamfer Loss
term_1 = torch.mean(torch.min(d2_matrix, 1)[0])
term_2 = torch.mean(torch.min(d2_matrix, 0)[0])
res = term_1 + term_2
return res
class WeightedHausdorffDistance(nn.Module):
def __init__(self,
resized_height, resized_width,
p=-9,
return_2_terms=False,
device=torch.device('cpu')):
"""
:param resized_height: Number of rows in the image.
:param resized_width: Number of columns in the image.
:param p: Exponent in the generalized mean. -inf makes it the minimum.
:param return_2_terms: Whether to return the 2 terms
of the WHD instead of their sum.
Default: False.
:param device: Device where all Tensors will reside.
"""
super(nn.Module, self).__init__()
# Prepare all possible (row, col) locations in the image
self.height, self.width = resized_height, resized_width
self.resized_size = torch.tensor([resized_height,
resized_width],
dtype=torch.get_default_dtype(),
device=device)
self.max_dist = math.sqrt(resized_height**2 + resized_width**2)
self.n_pixels = resized_height * resized_width
self.all_img_locations = torch.from_numpy(cartesian([np.arange(resized_height),
np.arange(resized_width)]))
# Convert to appropiate type
self.all_img_locations = self.all_img_locations.to(device=device,
dtype=torch.get_default_dtype())
self.return_2_terms = return_2_terms
self.p = p
def forward(self, prob_map, gt, orig_sizes):
"""
Compute the Weighted Hausdorff Distance function
between the estimated probability map and ground truth points.
The output is the WHD averaged through all the batch.
:param prob_map: (B x H x W) Tensor of the probability map of the estimation.
B is batch size, H is height and W is width.
Values must be between 0 and 1.
:param gt: List of Tensors of the Ground Truth points.
Must be of size B as in prob_map.
Each element in the list must be a 2D Tensor,
where each row is the (y, x), i.e, (row, col) of a GT point.
:param orig_sizes: Bx2 Tensor containing the size
of the original images.
B is batch size.
The size must be in (height, width) format.
:param orig_widths: List of the original widths for each image
in the batch.
:return: Single-scalar Tensor with the Weighted Hausdorff Distance.
If self.return_2_terms=True, then return a tuple containing
the two terms of the Weighted Hausdorff Distance.
"""
_assert_no_grad(gt)
assert prob_map.dim() == 3, 'The probability map must be (B x H x W)'
assert prob_map.size()[1:3] == (self.height, self.width), \
'You must configure the WeightedHausdorffDistance with the height and width of the ' \
'probability map that you are using, got a probability map of size %s'\
% str(prob_map.size())
batch_size = prob_map.shape[0]
assert batch_size == len(gt)
terms_1 = []
terms_2 = []
for b in range(batch_size):
# One by one
prob_map_b = prob_map[b, :, :]
gt_b = gt[b]
orig_size_b = orig_sizes[b, :]
norm_factor = (orig_size_b/self.resized_size).unsqueeze(0)
n_gt_pts = gt_b.size()[0]
# Corner case: no GT points
if gt_b.ndimension() == 1 and (gt_b < 0).all().item() == 0:
terms_1.append(torch.tensor([0],
dtype=torch.get_default_dtype()))
terms_2.append(torch.tensor([self.max_dist],
dtype=torch.get_default_dtype()))
continue
# Pairwise distances between all possible locations and the GTed locations
n_gt_pts = gt_b.size()[0]
normalized_x = norm_factor.repeat(self.n_pixels, 1) *\
self.all_img_locations
normalized_y = norm_factor.repeat(len(gt_b), 1)*gt_b
d_matrix = cdist(normalized_x, normalized_y)
# Reshape probability map as a long column vector,
# and prepare it for multiplication
p = prob_map_b.view(prob_map_b.nelement())
n_est_pts = p.sum()
p_replicated = p.view(-1, 1).repeat(1, n_gt_pts)
# Weighted Hausdorff Distance
term_1 = (1 / (n_est_pts + 1e-6)) * \
torch.sum(p * torch.min(d_matrix, 1)[0])
weighted_d_matrix = (1 - p_replicated)*self.max_dist + p_replicated*d_matrix
minn = generaliz_mean(weighted_d_matrix,
p=self.p,
dim=0, keepdim=False)
term_2 = torch.mean(minn)
# terms_1[b] = term_1
# terms_2[b] = term_2
terms_1.append(term_1)
terms_2.append(term_2)
terms_1 = torch.stack(terms_1)
terms_2 = torch.stack(terms_2)
if self.return_2_terms:
res = terms_1.mean(), terms_2.mean()
else:
res = terms_1.mean() + terms_2.mean()
return res
def generaliz_mean(tensor, dim, p=-9, keepdim=False):
# """
# Computes the softmin along some axes.
# Softmin is the same as -softmax(-x), i.e,
# softmin(x) = -log(sum_i(exp(-x_i)))
# The smoothness of the operator is controlled with k:
# softmin(x) = -log(sum_i(exp(-k*x_i)))/k
# :param input: Tensor of any dimension.
# :param dim: (int or tuple of ints) The dimension or dimensions to reduce.
# :param keepdim: (bool) Whether the output tensor has dim retained or not.
# :param k: (float>0) How similar softmin is to min (the lower the more smooth).
# """
# return -torch.log(torch.sum(torch.exp(-k*input), dim, keepdim))/k
"""
The generalized mean. It corresponds to the minimum when p = -inf.
https://en.wikipedia.org/wiki/Generalized_mean
:param tensor: Tensor of any dimension.
:param dim: (int or tuple of ints) The dimension or dimensions to reduce.
:param keepdim: (bool) Whether the output tensor has dim retained or not.
:param p: (float<0).
"""
assert p < 0
res= torch.mean((tensor + 1e-6)**p, dim, keepdim=keepdim)**(1./p)
return res
"""
Copyright ©right © (c) 2019 The Board of Trustees of Purdue University and the Purdue Research Foundation.
All rights reserved.
This software is covered by US patents and copyright.
This source code is to be used for academic research purposes only, and no commercial use is allowed.
For any questions, please contact Edward J. Delp ([email protected]) at Purdue University.
Last Modified: 10/02/2019
"""