[805160]: / cardiac_motion / model / losses.py

Download this file

60 lines (42 with data), 1.6 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
"""Loss functions"""
import torch
def diffusion_loss(dvf):
"""
Calculate diffusion loss as a regularisation on the displacement vector field (DVF)
Args:
dvf: (Tensor of shape (N, 2, H, W)) displacement vector field estimated
Returns:
diffusion_loss_2d: (Scalar) diffusion regularisation loss
"""
# spatial derivatives
dvf_dx = dvf[:, :, 1:, 1:] - dvf[:, :, :-1, 1:] # (N, 2, H-1, W-1)
dvf_dy = dvf[:, :, 1:, 1:] - dvf[:, :, 1:, :-1] # (N, 2, H-1, W-1)
return (dvf_dx.pow(2) + dvf_dy.pow(2)).mean()
def huber_loss_spatial(dvf):
"""
Calculate approximated spatial Huber loss
Args:
dvf: (Tensor of shape (N, 2, H, W)) displacement vector field estimated
Returns:
loss: (Scalar) Huber loss spatial
"""
eps = 1e-8 # numerical stability
# spatial derivatives
dvf_dx = dvf[:, :, 1:, 1:] - dvf[:, :, :-1, 1:] # (N, 2, H-1, W-1)
dvf_dy = dvf[:, :, 1:, 1:] - dvf[:, :, 1:, :-1] # (N, 2, H-1, W-1)
return ((dvf_dx.pow(2) + dvf_dy.pow(2)).sum(dim=1) + eps).sqrt().mean()
def huber_loss_temporal(dvf):
"""
Calculate approximated temporal Huber loss
Args:
dvf: (Tensor of shape (N, 2, H, W)) displacement vector field estimated
Returns:
loss: (Scalar) huber loss temporal
"""
eps = 1e-8 # numerical stability
# magnitude of the dvf
dvf_norm = torch.norm(dvf, dim=1) # (N, H, W)
# temporal derivatives, 1st order
dvf_norm_dt = dvf_norm[1:, :, :] - dvf_norm[:-1, :, :]
loss = (dvf_norm_dt.pow(2) + eps).sum().sqrt()
return loss