micro_sam.v2.loss.semantic_loss

 1import torch
 2import torch.nn as nn
 3
 4from micro_sam.v1.training.semantic_sam_trainer import CustomDiceLoss
 5
 6
 7class CustomCombinedLoss(nn.Module):
 8    """Weighted dice and cross entropy loss for semantic segmentation.
 9
10    The loss is 'dice_weight * dice + (1 - dice_weight) * cross_entropy'. The dice term is the multi-class
11    dice of `micro_sam.v1.training.semantic_sam_trainer.CustomDiceLoss`.
12
13    The predictions must be the raw class logits. The dice term applies a softmax and the cross entropy term
14    applies a log softmax, so a model with a final activation would activate its predictions twice.
15
16    Args:
17        num_classes: The number of semantic classes, the background class included.
18        dice_weight: The weight of the dice loss. One selects dice only. Zero selects cross entropy only.
19    """
20    def __init__(self, num_classes: int, dice_weight: float = 0.5):
21        super().__init__()
22        if not 0.0 <= dice_weight <= 1.0:
23            raise ValueError(f"The dice weight is '{dice_weight}'. It must lie between zero and one.")
24
25        self.dice_weight = dice_weight
26        self.dice_loss = CustomDiceLoss(num_classes=num_classes)
27        self.ce_loss = nn.CrossEntropyLoss()
28
29        self.init_kwargs = {"num_classes": num_classes, "dice_weight": dice_weight}
30
31    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
32        """Compute the combined loss between the class logits and the semantic map.
33
34        Args:
35            pred: The class logits of shape (B, num_classes, Z, Y, X).
36            target: The semantic map of shape (B, 1, Z, Y, X), holding the class ids.
37
38        Returns:
39            The combined loss.
40        """
41        target = target.to(pred.device, non_blocking=True)
42        dice_loss = self.dice_loss(pred, target)
43        ce_loss = self.ce_loss(pred, target.squeeze(1).long())
44        return self.dice_weight * dice_loss + (1 - self.dice_weight) * ce_loss
class CustomCombinedLoss(torch.nn.modules.module.Module):
 8class CustomCombinedLoss(nn.Module):
 9    """Weighted dice and cross entropy loss for semantic segmentation.
10
11    The loss is 'dice_weight * dice + (1 - dice_weight) * cross_entropy'. The dice term is the multi-class
12    dice of `micro_sam.v1.training.semantic_sam_trainer.CustomDiceLoss`.
13
14    The predictions must be the raw class logits. The dice term applies a softmax and the cross entropy term
15    applies a log softmax, so a model with a final activation would activate its predictions twice.
16
17    Args:
18        num_classes: The number of semantic classes, the background class included.
19        dice_weight: The weight of the dice loss. One selects dice only. Zero selects cross entropy only.
20    """
21    def __init__(self, num_classes: int, dice_weight: float = 0.5):
22        super().__init__()
23        if not 0.0 <= dice_weight <= 1.0:
24            raise ValueError(f"The dice weight is '{dice_weight}'. It must lie between zero and one.")
25
26        self.dice_weight = dice_weight
27        self.dice_loss = CustomDiceLoss(num_classes=num_classes)
28        self.ce_loss = nn.CrossEntropyLoss()
29
30        self.init_kwargs = {"num_classes": num_classes, "dice_weight": dice_weight}
31
32    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
33        """Compute the combined loss between the class logits and the semantic map.
34
35        Args:
36            pred: The class logits of shape (B, num_classes, Z, Y, X).
37            target: The semantic map of shape (B, 1, Z, Y, X), holding the class ids.
38
39        Returns:
40            The combined loss.
41        """
42        target = target.to(pred.device, non_blocking=True)
43        dice_loss = self.dice_loss(pred, target)
44        ce_loss = self.ce_loss(pred, target.squeeze(1).long())
45        return self.dice_weight * dice_loss + (1 - self.dice_weight) * ce_loss

Weighted dice and cross entropy loss for semantic segmentation.

The loss is 'dice_weight * dice + (1 - dice_weight) * cross_entropy'. The dice term is the multi-class dice of micro_sam.v1.training.semantic_sam_trainer.CustomDiceLoss.

The predictions must be the raw class logits. The dice term applies a softmax and the cross entropy term applies a log softmax, so a model with a final activation would activate its predictions twice.

Arguments:
  • num_classes: The number of semantic classes, the background class included.
  • dice_weight: The weight of the dice loss. One selects dice only. Zero selects cross entropy only.
CustomCombinedLoss(num_classes: int, dice_weight: float = 0.5)
21    def __init__(self, num_classes: int, dice_weight: float = 0.5):
22        super().__init__()
23        if not 0.0 <= dice_weight <= 1.0:
24            raise ValueError(f"The dice weight is '{dice_weight}'. It must lie between zero and one.")
25
26        self.dice_weight = dice_weight
27        self.dice_loss = CustomDiceLoss(num_classes=num_classes)
28        self.ce_loss = nn.CrossEntropyLoss()
29
30        self.init_kwargs = {"num_classes": num_classes, "dice_weight": dice_weight}

Initialize internal Module state, shared by both nn.Module and ScriptModule.

dice_weight
dice_loss
ce_loss
init_kwargs
def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
32    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
33        """Compute the combined loss between the class logits and the semantic map.
34
35        Args:
36            pred: The class logits of shape (B, num_classes, Z, Y, X).
37            target: The semantic map of shape (B, 1, Z, Y, X), holding the class ids.
38
39        Returns:
40            The combined loss.
41        """
42        target = target.to(pred.device, non_blocking=True)
43        dice_loss = self.dice_loss(pred, target)
44        ce_loss = self.ce_loss(pred, target.squeeze(1).long())
45        return self.dice_weight * dice_loss + (1 - self.dice_weight) * ce_loss

Compute the combined loss between the class logits and the semantic map.

Arguments:
  • pred: The class logits of shape (B, num_classes, Z, Y, X).
  • target: The semantic map of shape (B, 1, Z, Y, X), holding the class ids.
Returns:

The combined loss.