synapse_net.training.loss
1import torch 2import torch.nn as nn 3 4 5class MaskedDiceLossPerSample(nn.Module): 6 """Dice loss with a per-voxel loss mask, which is averaged over the samples of the batch. 7 8 The target holds the actual targets, followed by a mask (or weight) for each of them, as produced by 9 `synapse_net.training.transform.AugmentedMitoStateMaskTransform`. The dice is computed per sample, 10 so that every patch counts equally regardless of how much foreground it contains. 11 12 Args: 13 eps: The epsilon value used to avoid division by zero. 14 """ 15 16 def __init__(self, eps: float = 1e-7): 17 super().__init__() 18 self.eps = eps 19 # Enables torch-em to rebuild the loss when loading a checkpoint. 20 self.init_kwargs = {"eps": eps} 21 22 def forward(self, prediction: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor: 23 """Compute the masked dice loss. 24 25 Args: 26 prediction: The predictions of the network. 27 target: The targets, with the loss mask in the second half of the channels. 28 29 Returns: 30 The loss value. 31 """ 32 n_channels = prediction.size(1) 33 if target.size(1) != 2 * n_channels: 34 raise ValueError(f"Expected a target with {2 * n_channels} channels, got {target.size(1)}.") 35 # With the square root a weight enters the numerator and the denominator of the dice linearly. 36 mask = torch.sqrt(target[:, n_channels:]) 37 pred, tgt = prediction * mask, target[:, :n_channels] * mask 38 39 spatial_dims = tuple(range(2, pred.dim())) 40 numerator = (pred * tgt).sum(spatial_dims) 41 denominator = (pred * pred).sum(spatial_dims) + (tgt * tgt).sum(spatial_dims) 42 dice = (2.0 * numerator / denominator.clamp(min=self.eps)).mean(dim=0) 43 return (1.0 - dice).sum()
class
MaskedDiceLossPerSample(torch.nn.modules.module.Module):
6class MaskedDiceLossPerSample(nn.Module): 7 """Dice loss with a per-voxel loss mask, which is averaged over the samples of the batch. 8 9 The target holds the actual targets, followed by a mask (or weight) for each of them, as produced by 10 `synapse_net.training.transform.AugmentedMitoStateMaskTransform`. The dice is computed per sample, 11 so that every patch counts equally regardless of how much foreground it contains. 12 13 Args: 14 eps: The epsilon value used to avoid division by zero. 15 """ 16 17 def __init__(self, eps: float = 1e-7): 18 super().__init__() 19 self.eps = eps 20 # Enables torch-em to rebuild the loss when loading a checkpoint. 21 self.init_kwargs = {"eps": eps} 22 23 def forward(self, prediction: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor: 24 """Compute the masked dice loss. 25 26 Args: 27 prediction: The predictions of the network. 28 target: The targets, with the loss mask in the second half of the channels. 29 30 Returns: 31 The loss value. 32 """ 33 n_channels = prediction.size(1) 34 if target.size(1) != 2 * n_channels: 35 raise ValueError(f"Expected a target with {2 * n_channels} channels, got {target.size(1)}.") 36 # With the square root a weight enters the numerator and the denominator of the dice linearly. 37 mask = torch.sqrt(target[:, n_channels:]) 38 pred, tgt = prediction * mask, target[:, :n_channels] * mask 39 40 spatial_dims = tuple(range(2, pred.dim())) 41 numerator = (pred * tgt).sum(spatial_dims) 42 denominator = (pred * pred).sum(spatial_dims) + (tgt * tgt).sum(spatial_dims) 43 dice = (2.0 * numerator / denominator.clamp(min=self.eps)).mean(dim=0) 44 return (1.0 - dice).sum()
Dice loss with a per-voxel loss mask, which is averaged over the samples of the batch.
The target holds the actual targets, followed by a mask (or weight) for each of them, as produced by
synapse_net.training.transform.AugmentedMitoStateMaskTransform. The dice is computed per sample,
so that every patch counts equally regardless of how much foreground it contains.
Arguments:
- eps: The epsilon value used to avoid division by zero.
MaskedDiceLossPerSample(eps: float = 1e-07)
17 def __init__(self, eps: float = 1e-7): 18 super().__init__() 19 self.eps = eps 20 # Enables torch-em to rebuild the loss when loading a checkpoint. 21 self.init_kwargs = {"eps": eps}
Initialize internal Module state, shared by both nn.Module and ScriptModule.
def
forward( self, prediction: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor:
23 def forward(self, prediction: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor: 24 """Compute the masked dice loss. 25 26 Args: 27 prediction: The predictions of the network. 28 target: The targets, with the loss mask in the second half of the channels. 29 30 Returns: 31 The loss value. 32 """ 33 n_channels = prediction.size(1) 34 if target.size(1) != 2 * n_channels: 35 raise ValueError(f"Expected a target with {2 * n_channels} channels, got {target.size(1)}.") 36 # With the square root a weight enters the numerator and the denominator of the dice linearly. 37 mask = torch.sqrt(target[:, n_channels:]) 38 pred, tgt = prediction * mask, target[:, :n_channels] * mask 39 40 spatial_dims = tuple(range(2, pred.dim())) 41 numerator = (pred * tgt).sum(spatial_dims) 42 denominator = (pred * pred).sum(spatial_dims) + (tgt * tgt).sum(spatial_dims) 43 dice = (2.0 * numerator / denominator.clamp(min=self.eps)).mean(dim=0) 44 return (1.0 - dice).sum()
Compute the masked dice loss.
Arguments:
- prediction: The predictions of the network.
- target: The targets, with the loss mask in the second half of the channels.
Returns:
The loss value.