Skip to content

loss

xvr.model.loss

DiceMetric

DiceMetric()
Source code in src/xvr/model/loss.py
63
64
def __init__(self):
    super().__init__()

forward

forward(y_pred, y_true)

Compute 2D Dice coefficient between to multi-channel labelmaps. Assumes the first channel in each image is background.

Equivalent to monai.metrics.DiceMetric(include_background=False, reduction="none")

Source code in src/xvr/model/loss.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def forward(self, y_pred, y_true):
    """
    Compute 2D Dice coefficient between to multi-channel labelmaps.
    Assumes the first channel in each image is background.

    Equivalent to monai.metrics.DiceMetric(include_background=False, reduction="none")
    """

    # Flatten spatial dimensions
    y_pred = y_pred.view(y_pred.shape[0], y_pred.shape[1], -1)  # (B, C, H*W)
    y_true = y_true.view(y_true.shape[0], y_true.shape[1], -1)  # (B, C, H*W)

    # Compute intersection and union
    intersection = (y_pred * y_true).sum(dim=2)  # (B, C)
    pred_sum = y_pred.sum(dim=2)  # (B, C)
    true_sum = y_true.sum(dim=2)  # (B, C)

    # Compute Dice coefficient
    dice = (2.0 * intersection) / (pred_sum + true_sum)

    # Exclude background (assume background is channel 0)
    dice = dice[:, 1:]

    return dice