---
title: Generalized Dice Score
description: Compute Generalized Dice Score.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/segmentation/generalized_dice'
---
# Generalized Dice Score {#generalized-dice-score}

## Module Interface {#module-interface}

### `class torchmetrics.segmentation.GeneralizedDiceScore(num_classes, include_background=True, per_class=False, weight_type='square', input_format='one-hot', **kwargs)` {#class-torchmetrics-segmentation-generalizeddicescore-num-classes-include-background-true-per-class-false-weight-type-square-input-format-one-hot-kwargs}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/generalized_dice.py#L34-L191)

Compute [Generalized Dice Score](https://arxiv.org/abs/1707.03237).

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

```math
\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`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): 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. The input type can be controlled with the `input_format` argument.
    
*   `target` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): 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. The input type can be controlled with the `input_format` argument.
    

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

*   `gds` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): 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`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – The number of classes in the segmentation problem.
    
*   **include\_background** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to include the background class in the computation
    
*   **per\_class** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to compute the metric for each class separately.
    
*   **weight\_type** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'square'`, `'simple'`, `'linear'`\]) – The type of weight to apply to each class. Can be one of `"square"`, `"simple"`, or `"linear"`.
    
*   **input\_format** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'one-hot'`, `'index'`, `'mixed'`\]) – What kind of input the function receives. Choose between `"one-hot"` for one-hot encoded tensors, `"index"` for index tensors or `"mixed"` for one one-hot encoded and one index tensor
    
*   **kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional keyword arguments, see [Advanced metric settings](/docs/torchmetrics/1.9.0/user-guide/overview.md#metric-kwargs) for more info.
    

Raises:

*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `num_classes` is not a positive integer
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `include_background` is not a boolean
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `per_class` is not a boolean
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `weight_type` is not one of `"square"`, `"simple"`, or `"linear"`
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `input_format` is not one of `"one-hot"`, `"index"` or `"mixed"`
    

Example

```python
>>> 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()` {#compute}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/generalized_dice.py#L147-L149)

Compute the final generalized dice score.

Return type:

[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")

#### `plot(val=None, ax=None)` {#plot-val-none-ax-none}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/generalized_dice.py#L151-L191)

Plot a single or multiple values from the metric.

Parameters:

*   **val** (`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either a single result from calling metric.forward or metric.compute or a list of these results. If no value is provided, will automatically call metric.compute and plot that result.
    
*   **ax** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)")\]) – An matplotlib axis object. If provided will add plot to that axis
    

Return type:

[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure "(in Matplotlib v3.11.2)"), `Union`\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)"), [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v2.5)")\]\]

Returns:

Figure and Axes object

Raises:

[**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If matplotlib is not installed

```python
>>> # 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()
```

[![../../\_images/generalized\_dice-1.png](/docs/torchmetrics/1.9.0/static/_images/generalized_dice-1.png)](/docs/torchmetrics/1.9.0/static/_images/generalized_dice-1.png)

```python
>>> # 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)
```

[![../../\_images/generalized\_dice-2.png](/docs/torchmetrics/1.9.0/static/_images/generalized_dice-2.png)](/docs/torchmetrics/1.9.0/static/_images/generalized_dice-2.png)

#### `update(preds, target)` {#update-preds-target}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/generalized_dice.py#L139-L145)

Update the state with new data.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

## Functional Interface {#functional-interface}

### `torchmetrics.functional.segmentation.generalized_dice_score(preds, target, num_classes, include_background=True, per_class=False, weight_type='square', input_format='one-hot')` {#torchmetrics-functional-segmentation-generalized-dice-score-preds-target-num-classes-include-background-true-per-class-false-weight-type-square-input-format-one-hot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/segmentation/generalized_dice.py#L96-L152)

Compute the Generalized Dice Score for semantic segmentation.

Parameters:

*   **preds** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – Predictions from model
    
*   **target** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – Ground truth values
    
*   **num\_classes** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Number of classes
    
*   **include\_background** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to include the background class in the computation
    
*   **per\_class** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to compute the score for each class separately, else average over all classes
    
*   **weight\_type** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'square'`, `'simple'`, `'linear'`\]) – Type of weight factor to apply to the classes. One of `"square"`, `"simple"`, or `"linear"`
    
*   **input\_format** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'one-hot'`, `'index'`, `'mixed'`\]) – What kind of input the function receives. Choose between `"one-hot"` for one-hot encoded tensors, `"index"` for index tensors or `"mixed"` for one one-hot encoded and one index tensor
    

Return type:

[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")

Returns:

The Generalized Dice Score

Example (with one-hot encoded tensors):

```python
>>> 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]])
```

Example (with index tensors):

```python
>>> from torch import randint
>>> from torchmetrics.functional.segmentation import generalized_dice_score
>>> preds = randint(0, 5, (4, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
>>> target = randint(0, 5, (4, 16, 16))  # 4 samples, 5 classes, 16x16 target
>>> generalized_dice_score(preds, target, num_classes=5, input_format="index")
tensor([0.1991, 0.1971, 0.2350, 0.2216])
>>> generalized_dice_score(preds, target, num_classes=5, per_class=True, input_format="index")
tensor([[0.1714, 0.2500, 0.1304, 0.2524, 0.2069],
        [0.1837, 0.2162, 0.0962, 0.2692, 0.1895],
        [0.3866, 0.1348, 0.2526, 0.2301, 0.2083],
        [0.1978, 0.2804, 0.1714, 0.1915, 0.2783]])
```

---

**Navigation**

- Parent: [Segmentation](/docs/torchmetrics/1.9.0/segmentation.md)
