-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.py
193 lines (164 loc) · 8.42 KB
/
metrics.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
"""
This script defines the evaluation metrics and the loss functions
"""
import torch
import numpy as np
from kornia.losses import ssim as ssim_
class NerfLoss(torch.nn.Module):
def __init__(self):
super().__init__()
self.loss = torch.nn.MSELoss(reduction='mean')
def forward(self, inputs, targets):
loss_dict = {}
loss_dict['coarse_color'] = self.loss(inputs['rgb_coarse'], targets)
if 'rgb_fine' in inputs:
loss_dict['fine_color'] = self.loss(inputs['rgb_fine'], targets)
loss = sum(l for l in loss_dict.values())
return loss, loss_dict
def uncertainty_aware_loss(loss_dict, inputs, gt_rgb, typ, beta_min=0.05):
beta = torch.sum(inputs[f'weights_{typ}'].unsqueeze(-1) * inputs['beta_coarse'], -2) + beta_min
loss_dict[f'{typ}_color'] = ((inputs[f'rgb_{typ}'] - gt_rgb) ** 2 / (2 * beta ** 2)).mean()
loss_dict[f'{typ}_logbeta'] = (3 + torch.log(beta).mean()) / 2 # +3 to make c_b positive since beta_min = 0.05
return loss_dict
def solar_correction(loss_dict, inputs, typ, lambda_sc=0.05):
# computes the solar correction terms defined in Shadow NeRF and adds them to the dictionary of losses
sun_sc = inputs[f'sun_sc_{typ}'].squeeze()
term2 = torch.sum(torch.square(inputs[f'transparency_sc_{typ}'].detach() - sun_sc), -1)
term3 = 1 - torch.sum(inputs[f'weights_sc_{typ}'].detach() * sun_sc, -1)
loss_dict[f'{typ}_sc_term2'] = lambda_sc/3. * torch.mean(term2)
loss_dict[f'{typ}_sc_term3'] = lambda_sc/3. * torch.mean(term3)
return loss_dict
class SNerfLoss(torch.nn.Module):
def __init__(self, lambda_sc=0.05):
super().__init__()
self.lambda_sc = lambda_sc
self.loss = torch.nn.MSELoss(reduction='mean')
def forward(self, inputs, targets):
loss_dict = {}
typ = 'coarse'
loss_dict[f'{typ}_color'] = self.loss(inputs[f'rgb_{typ}'], targets)
if self.lambda_sc > 0:
loss_dict = solar_correction(loss_dict, inputs, typ, self.lambda_sc)
if 'rgb_fine' in inputs:
typ = 'fine'
loss_dict[f'{typ}_color'] = self.loss(inputs[f'rgb_{typ}'], targets)
if self.lambda_sc > 0:
loss_dict = solar_correction(loss_dict, inputs, typ, self.lambda_sc)
loss = sum(l for l in loss_dict.values())
return loss, loss_dict
class SatNerfLoss(torch.nn.Module):
def __init__(self, lambda_sc=0.0):
super().__init__()
self.lambda_sc = lambda_sc
def forward(self, inputs, targets):
loss_dict = {}
typ = 'coarse'
loss_dict = uncertainty_aware_loss(loss_dict, inputs, targets, typ)
if self.lambda_sc > 0:
loss_dict = solar_correction(loss_dict, inputs, typ, self.lambda_sc)
if 'rgb_fine' in inputs:
typ = 'fine'
loss_dict = uncertainty_aware_loss(loss_dict, inputs, targets, typ)
if self.lambda_sc > 0:
loss_dict = solar_correction(loss_dict, inputs, typ, self.lambda_sc)
loss = sum(l for l in loss_dict.values())
return loss, loss_dict
class DepthLoss(torch.nn.Module):
def __init__(self, lambda_ds=1.0, GNLL=False, usealldepth=True, margin=0, stdscale=1):
super().__init__()
self.lambda_ds = lambda_ds/3.
self.GNLL = GNLL
self.usealldepth = usealldepth
self.margin=margin
self.stdscale=stdscale
if self.GNLL == True:
self.loss = torch.nn.GaussianNLLLoss()
else:
self.loss = torch.nn.MSELoss(reduce=False)
def forward(self, inputs, targets, weights=1., target_valid_depth=None, target_std=None):
def is_not_in_expected_distribution(pred_depth, pred_std, target_depth, target_std):
depth_greater_than_expected = ((pred_depth - target_depth).abs() - target_std) > 0.
std_greater_than_expected = target_std < pred_std
return torch.logical_or(depth_greater_than_expected, std_greater_than_expected)
def ComputeSubsetDepthLoss(inputs, typ, target_depth, target_weight, target_valid_depth, target_std):
if target_valid_depth == None:
print('target_valid_depth is None! Use all the target_depth by default! target_depth.shape[0]', target_depth.shape[0])
target_valid_depth = torch.ones(target_depth.shape[0])
z_vals = inputs[f'z_vals_{typ}'][np.where(target_valid_depth.cpu()>0)]
pred_depth = inputs[f'depth_{typ}'][np.where(target_valid_depth.cpu()>0)]
pred_weight = inputs[f'weights_{typ}'][np.where(target_valid_depth.cpu()>0)]
if pred_depth.shape[0] == 0:
print('ZERO target_valid_depth in this depth loss computation! target_weight.device: ', target_weight.device)
return torch.zeros((1,), device=target_weight.device, requires_grad=True)
pred_std = (((z_vals - pred_depth.unsqueeze(-1)).pow(2) * pred_weight).sum(-1)).sqrt()
target_weight = target_weight[np.where(target_valid_depth.cpu()>0)]
target_depth = target_depth[np.where(target_valid_depth.cpu()>0)]
target_std = target_std[np.where(target_valid_depth.cpu()>0)]
#target_std = self.stdscale*(torch.ones_like(target_weight) - target_weight) + torch.ones_like(target_weight)*self.margin
apply_depth_loss = torch.ones(target_depth.shape[0])
if self.usealldepth == False:
apply_depth_loss = is_not_in_expected_distribution(pred_depth, pred_std, target_depth, target_std)
pred_depth = pred_depth[apply_depth_loss]
if pred_depth.shape[0] == 0:
print('ZERO apply_depth_loss in this depth loss computation!')
return torch.zeros((1,), device=target_weight.device, requires_grad=True)
pred_std = pred_std[apply_depth_loss]
target_depth = target_depth[apply_depth_loss]
numerator = float(pred_depth.shape[0])
denominator = float(target_valid_depth.shape[0])
if self.GNLL == True:
loss = numerator/denominator*self.loss(pred_depth, target_depth, pred_std)
return loss
else:
loss = numerator/denominator*target_weight[apply_depth_loss]*self.loss(pred_depth, target_depth)
return loss
loss_dict = {}
typ = 'coarse'
if self.usealldepth == False:
loss_dict[f'{typ}_ds'] = ComputeSubsetDepthLoss(inputs, typ, targets, weights, target_valid_depth, target_std)
else:
loss_dict[f'{typ}_ds'] = self.loss(inputs['depth_coarse'], targets)
if 'depth_fine' in inputs:
typ = 'fine'
if self.usealldepth == False:
loss_dict[f'{typ}_ds'] = ComputeSubsetDepthLoss(inputs, typ, targets, weights, target_valid_depth, target_std)
else:
loss_dict[f'{typ}_ds'] = self.loss(inputs['depth_fine'], targets)
if self.usealldepth == False:
# no need to apply weights here because it is already done in function ComputeSubsetDepthLoss
for k in loss_dict.keys():
loss_dict[k] = self.lambda_ds * torch.mean(loss_dict[k])
else:
# apply weights
for k in loss_dict.keys():
loss_dict[k] = self.lambda_ds * torch.mean(weights * loss_dict[k])
loss = sum(l for l in loss_dict.values())
return loss, loss_dict
def load_loss(args):
if args.model == "nerf":
loss_function = NerfLoss()
elif args.model == "s-nerf":
loss_function = SNerfLoss(lambda_sc=args.sc_lambda)
elif args.model == "sat-nerf" or args.model == "sps-nerf":
if args.beta == True:
loss_function = SatNerfLoss(lambda_sc=args.sc_lambda)
else:
loss_function = SNerfLoss(lambda_sc=args.sc_lambda)
else:
raise ValueError(f'model {args.model} is not valid')
return loss_function
def mse(image_pred, image_gt, valid_mask=None, reduction='mean'):
value = (image_pred-image_gt)**2
if valid_mask is not None:
value = value[valid_mask]
if reduction == 'mean':
return torch.mean(value)
return value
def psnr(image_pred, image_gt, valid_mask=None, reduction='mean'):
return -10*torch.log10(mse(image_pred, image_gt, valid_mask, reduction))
def ssim(image_pred, image_gt):
"""
image_pred and image_gt: (1, 3, H, W)
important: kornia==0.5.3
"""
return torch.mean(ssim_(image_pred, image_gt, 3))