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

## Module Interface {#module-interface}

### `class torchmetrics.segmentation.DiceScore(num_classes, include_background=True, average='macro', aggregation_level='samplewise', input_format='one-hot', **kwargs)` {#class-torchmetrics-segmentation-dicescore-num-classes-include-background-true-average-macro-aggregation-level-samplewise-input-format-one-hot-kwargs}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/dice.py#L35-L200)

Compute [Dice Score](#dice-score).

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

```math
DS = \frac{2 \sum_{i=1}^{N} t_i p_i}{\sum_{i=1}^{N} t_i + \sum_{i=1}^{N} p_i}
```

where $`N`$ is the number of classes, $`t_i`$ is the target tensor, and $`p_i`$ is the prediction tensor. In general the Dice Score can be interpreted as the overlap between the prediction and target tensors divided by the total number of elements in the tensors.

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 dice score. If `average` is set to `None` or `"none"` the output will be a tensor of shape `(C,)` with the dice score for each class. If `average` is set to `"micro"`, `"macro"`, or `"weighted"` the output will be a scalar tensor. The score is an average over all samples.
    

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.
    
*   **average** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'micro'`, `'macro'`, `'weighted'`, `'none'`\]\]) – The method to average the dice score. Options are `"micro"`, `"macro"`, `"weighted"`, `"none"` or `None`. This determines how to average the dice score across different classes.
    
*   **aggregation\_level** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'samplewise'`, `'global'`\]\]) – The level at which to aggregate the dice score. Options are `"samplewise"` or `"global"`. For `"samplewise"` the dice score is computed for each sample and then averaged. For `"global"` the dice score is computed globally over all samples.
    
*   **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 `average` is not one of `"micro"`, `"macro"`, `"weighted"`, `"none"` or `None`
    
*   [**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 DiceScore
>>> 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
>>> dice_score = DiceScore(num_classes=5, average="micro")
>>> dice_score(preds, target)
tensor(0.4941)
>>> dice_score = DiceScore(num_classes=5, average="none")
>>> dice_score(preds, target)
tensor([0.4860, 0.4999, 0.5014, 0.4885, 0.4915])
```

#### `compute()` {#compute}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/dice.py#L150-L158)

Computes the 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/dice.py#L160-L200)

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 DiceScore
>>> metric = DiceScore(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/dice-1.png](/docs/torchmetrics/1.9.0/static/_images/dice-1.png)](/docs/torchmetrics/1.9.0/static/_images/dice-1.png)

```python
>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.segmentation import DiceScore
>>> metric = DiceScore(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/dice-2.png](/docs/torchmetrics/1.9.0/static/_images/dice-2.png)](/docs/torchmetrics/1.9.0/static/_images/dice-2.png)

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

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/dice.py#L141-L148)

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.dice_score(preds, target, num_classes, include_background=True, average='macro', input_format='one-hot', aggregation_level='samplewise')` {#torchmetrics-functional-segmentation-dice-score-preds-target-num-classes-include-background-true-average-macro-input-format-one-hot-aggregation-level-samplewise}

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

Compute the 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
    
*   **average** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'micro'`, `'macro'`, `'weighted'`, `'none'`\]\]) – The method to average the dice score. Options are `"micro"`, `"macro"`, `"weighted"`, `"none"` or `None`. This determines how to average the dice score across different classes.
    
*   **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
    
*   **aggregation\_level** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'samplewise'`, `'global'`\]\]) – The level at which to aggregate the dice score. Options are `"samplewise"` or `"global"`. For `"samplewise"` the dice score is computed for each sample and then averaged. For `"global"` the dice score is computed globally over all samples.
    

Return type:

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

Returns:

The Dice score.

Example (with one-hot encoded tensors):

```python
>>> from torch import randint
>>> from torchmetrics.functional.segmentation import dice_score
>>> _ = torch.manual_seed(42)
>>> 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
>>> # dice score micro averaged over all classes
>>> dice_score(preds, target, num_classes=5, average="micro")
tensor([0.4842, 0.4968, 0.5053, 0.4902])
>>> # dice score per sample and class
>>> dice_score(preds, target, num_classes=5, average="none")
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]])
>>> # global dice score over all samples with macro averaging
>>> dice_score(preds, target, num_classes=5, average="macro", aggregation_level="global")
tensor([0.4942])
```

Example (with index tensors):

```python
>>> from torch import randint
>>> from torchmetrics.functional.segmentation import dice_score
>>> _ = torch.manual_seed(42)
>>> 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
>>> # dice score micro averaged over all classes
>>> dice_score(preds, target, num_classes=5, average="micro", input_format="index")
tensor([0.2031, 0.1914, 0.2266, 0.1641])
>>> # dice score per sample and class
>>> dice_score(preds, target, num_classes=5, average="none", input_format="index")
tensor([[0.1731, 0.1667, 0.2400, 0.2424, 0.1947],
        [0.2245, 0.2247, 0.2321, 0.1132, 0.1682],
        [0.2500, 0.2476, 0.1887, 0.1818, 0.2718],
        [0.1308, 0.1800, 0.1980, 0.1607, 0.1522]])
>>> # global dice score over all samples with macro averaging
>>> dice_score(preds, target, num_classes=5, average="macro", aggregation_level="global", input_format="index")
tensor([0.1965])
```

---

**Navigation**

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