# Generalized Dice Score¶

## Module Interface¶

class torchmetrics.segmentation.GeneralizedDiceScore(num_classes, include_background=True, per_class=False, weight_type='square', **kwargs)[source]

Compute Generalized Dice Score.

The metric can be used to evaluate the performance of image segmentation models. The Generalized Dice Score is defined as:

$\begin{split}GDS = \frac{2 \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} p_{ij}}{ \\sum_{i=1}^{N} w_i \\sum_{j} t_{ij} + \\sum_{i=1}^{N} w_i \\sum_{j} p_{ij}}\end{split}$

where $$N$$ is the number of classes, $$t_{ij}$$ is the target tensor, $$p_{ij}$$ is the prediction tensor, and $$w_i$$ is the weight for class $$i$$. The weight can be computed in three different ways:

• square: $$w_i = 1 / (\\sum_{j} t_{ij})^2$$

• simple: $$w_i = 1 / \\sum_{j} t_{ij}$$

• linear: $$w_i = 1$$

Note that the generalized dice loss can be computed as one minus the generalized dice score.

As input to forward and update the metric accepts the following input:

• preds (Tensor): An one-hot boolean tensor of shape (N, C, ...) with N being the number of samples and C the number of classes. Alternatively, an integer tensor of shape (N, ...) can be provided, where the integer values correspond to the class index. That format will be automatically converted to a one-hot tensor.

• target (Tensor): An one-hot boolean tensor of shape (N, C, ...) with N being the number of samples and C the number of classes. Alternatively, an integer tensor of shape (N, ...) can be provided, where the integer values correspond to the class index. That format will be automatically converted to a one-hot tensor.

As output to forward and compute the metric returns the following output:

• gds (Tensor): The generalized dice score. If per_class is set to True, the output will be a tensor of shape (C,) with the generalized dice score for each class. If per_class is set to False, the output will be a scalar tensor.

Parameters:
• num_classes (int) – The number of classes in the segmentation problem.

• include_background (bool) – Whether to include the background class in the computation

• per_class (bool) – Whether to compute the metric for each class separately.

• weight_type (Literal['square', 'simple', 'linear']) – The type of weight to apply to each class. Can be one of "square", "simple", or "linear".

• kwargs (Any) – Additional keyword arguments, see Advanced metric settings for more info.

Raises:
• ValueError – If num_classes is not a positive integer

• ValueError – If include_background is not a boolean

• ValueError – If per_class is not a boolean

• ValueError – If weight_type is not one of "square", "simple", or "linear"

Example

>>> from torch import randint
>>> from torchmetrics.segmentation import GeneralizedDiceScore
>>> gds = GeneralizedDiceScore(num_classes=3)
>>> preds = randint(0, 2, (10, 3, 128, 128))
>>> target = randint(0, 2, (10, 3, 128, 128))
>>> gds(preds, target)
tensor(0.4992)
>>> gds = GeneralizedDiceScore(num_classes=3, per_class=True)
>>> gds(preds, target)
tensor([0.5001, 0.4993, 0.4982])
>>> gds = GeneralizedDiceScore(num_classes=3, per_class=True, include_background=False)
>>> gds(preds, target)
tensor([0.4993, 0.4982])

compute()[source]

Compute the final generalized dice score.

Return type:

Tensor

plot(val=None, ax=None)[source]

Plot a single or multiple values from the metric.

Parameters:
Return type:
Returns:

Figure and Axes object

Raises:

ModuleNotFoundError – If matplotlib is not installed

>>> # Example plotting a single value
>>> import torch
>>> from torchmetrics.segmentation import GeneralizedDiceScore
>>> metric = GeneralizedDiceScore(num_classes=3)
>>> metric.update(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
>>> fig_, ax_ = metric.plot()

>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.segmentation import GeneralizedDiceScore
>>> metric = GeneralizedDiceScore(num_classes=3)
>>> values = [ ]
>>> for _ in range(10):
...     values.append(
...        metric(torch.randint(0, 2, (10, 3, 128, 128)), torch.randint(0, 2, (10, 3, 128, 128)))
...     )
>>> fig_, ax_ = metric.plot(values)

update(preds, target)[source]

Update the state with new data.

Return type:

None

## Functional Interface¶

torchmetrics.functional.segmentation.generalized_dice_score(preds, target, num_classes, include_background=True, per_class=False, weight_type='square')[source]

Compute the Generalized Dice Score for semantic segmentation.

Parameters:
• preds (Tensor) – Predictions from model

• target (Tensor) – Ground truth values

• num_classes (int) – Number of classes

• include_background (bool) – Whether to include the background class in the computation

• per_class (bool) – Whether to compute the IoU for each class separately, else average over all classes

• weight_type (Literal['square', 'simple', 'linear']) – Type of weight factor to apply to the classes. One of "square", "simple", or "linear"

Return type:

Tensor

Returns:

The Generalized Dice Score

Example

>>> from torch import randint
>>> from torchmetrics.functional.segmentation import generalized_dice_score
>>> preds = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
>>> target = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
>>> generalized_dice_score(preds, target, num_classes=5)
tensor([0.4830, 0.4935, 0.5044, 0.4880])
>>> generalized_dice_score(preds, target, num_classes=5, per_class=True)
tensor([[0.4724, 0.5185, 0.4710, 0.5062, 0.4500],
[0.4571, 0.4980, 0.5191, 0.4380, 0.5649],
[0.5428, 0.4904, 0.5358, 0.4830, 0.4724],
[0.4715, 0.4925, 0.4797, 0.5267, 0.4788]])