Repository: Project-MONAI/MONAI
File: monai/metrics/generalized_dice.py (Python)

Code before:
        # Do metric reduction and return
        f, _ = do_metric_reduction(data, self.reduction)

        return f


def compute_generalized_dice(
    y_pred: torch.Tensor,
    y: torch.Tensor,
    include_background: bool = True,
    weight_type: Weight | str = Weight.SQUARE,
    sum_over_labels: bool = False,
) -> torch.Tensor:
    """
    Computes the Generalized Dice Score and returns a tensor with its per image values.

    Args:
        y_pred: Binarized segmentation model output. It should be binarized, in one-hot format
            and in the NCHW[D] format, where N is the batch dimension, C is the channel dimension, and the
            remaining are the spatial dimensions.
        y: Binarized ground-truth. It should be binarized, in one-hot format and have the same shape as `y_pred`.
        include_background: Whether to include score computation on the first channel of the
            predicted output. Defaults to True.
        weight_type: {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to
            transform ground truth volume into a weight factor. Defaults to ``"square"``.
        sum_over_labels: Whether to sum the numerator and denominator across all labels before the final computation.

    Returns:
        torch.Tensor: Per batch and per class Generalized Dice Score, i.e., with the shape [batch_size, num_classes].

    Raises:
        ValueError: If `y_pred` or `y` are not PyTorch tensors, if `y_pred` and `y` have less than three dimensions,
            or `y_pred` and `y` don't have the same shape.
    """
    # Ensure tensors have at least 3 dimensions and have the same shape
    dims = y_pred.dim()
    if dims < 3:
        raise ValueError(f"y_pred should have at least 3 dimensions (batch, channel, spatial), got {dims}.")
    if y.shape != y_pred.shape:
        raise ValueError(f"y_pred - {y_pred.shape} - and y - {y.shape} - should have the same shapes.")

    # Ignore background, if needed
    if not include_background:
        y_pred, y = ignore_background(y_pred=y_pred, y=y)

    # Reducing only spatial dimensions (not batch nor channels), compute the intersection and non-weighted denominator
    reduce_axis = list(range(2, y_pred.dim()))
    intersection = torch.sum(y * y_pred, dim=reduce_axis)
    y_o = torch.sum(y, dim=reduce_axis)
    y_pred_o = torch.sum(y_pred, dim=reduce_axis)
    denominator = y_o + y_pred_o

Review comment (suggestion):
Do you thinks sum_over_classes would be better? Just a suggestion, open for this one.
```suggestion
        sum_over_labels: Whether to sum the numerator and denominator across all classes before the final computation.
```

Code after:
            include_background=self.include_background,
            weight_type=self.weight_type,
            sum_over_classes=self.sum_over_classes,
        )

    @deprecated_arg(
        "reduction",
        since="1.3.3",
        removed="1.7.0",
        msg_suffix="Reduction will be ignored. Set reduction during init. as gen.dice needs it during compute",
    )
    def aggregate(self, reduction: MetricReduction | str | None = None) -> torch.Tensor:
        """
        Execute reduction logic for the output of `compute_generalized_dice`.

        Returns:
            torch.Tensor: Aggregated metric value.

        Raises:
            ValueError: If the data to aggregate is not a PyTorch Tensor.
        """
        data = self.get_buffer()
        if not isinstance(data, torch.Tensor):
            raise ValueError("The data to aggregate must be a PyTorch Tensor.")

        # Do metric reduction and return
        f, _ = do_metric_reduction(data, self.reduction)

        return f


def compute_generalized_dice(
    y_pred: torch.Tensor,
    y: torch.Tensor,
    include_background: bool = True,
    weight_type: Weight | str = Weight.SQUARE,
    sum_over_classes: bool = False,
) -> torch.Tensor:
    """
    Computes the Generalized Dice Score and returns a tensor with its per image values.

    Args:
        y_pred (torch.Tensor): Binarized segmentation model output. It should be binarized, in one-hot format
            and in the NCHW[D] format, where N is the batch dimension, C is the channel dimension, and the
            remaining are the spatial dimensions.
        y (torch.Tensor): Binarized ground-truth. It should be binarized, in one-hot format and have the same shape as `y_pred`.
        include_background: Whether to include score computation on the first channel of the
            predicted output. Defaults to True.
        weight_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to
            transform ground truth volume into a weight factor. Defaults to ``"square"``.
        sum_over_labels (bool): Whether to sum the numerator and denominator across all labels before the final computation.