---
title: Mean Intersection over Union (mIoU)
description: Computes Mean Intersection over Union (mIoU) for semantic segmentation.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/segmentation/mean_iou'
---
# Mean Intersection over Union (mIoU) {#mean-intersection-over-union-miou}

## Module Interface {#module-interface}

### `class torchmetrics.segmentation.MeanIoU(num_classes=None, include_background=True, per_class=False, input_format='one-hot', **kwargs)` {#torchmetrics.segmentation.MeanIoU}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/mean_iou.py#L30-L226)

Computes Mean Intersection over Union (mIoU) for semantic segmentation.

The metric is defined by the overlap between the predicted segmentation and the ground truth, divided by the total area covered by the union of the two. The metric can be computed for each class separately or for all classes at once. The metric is optimal at a value of 1 and worst at a value of 0, -1 is returned if class is completely absent both from prediction and the ground truth labels.

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:

*   `miou` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): The mean Intersection over Union (mIoU) score. If `per_class` is set to `True`, the output will be a tensor of shape `(C,)` with the IoU score for each class. If `per_class` is set to `False`, the output will be a scalar tensor.
    

Parameters:

*   **num\_classes** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – The number of classes in the segmentation problem. Required when input\_format=”index”, optional when input\_format=”one-hot” or “mixed”.
    
*   **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 IoU for each class separately. If set to `False`, the metric will compute the mean IoU over all 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
    
*   **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 `None` or a positive integer
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `num_classes` is not provided when `input_format` is `"index"`
    
*   [**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 `input_format` is not one of `"one-hot"`, `"index"` or `"mixed"`
    

Example

```python
>>> import torch
>>> from torch import randint
>>> from torchmetrics.segmentation import MeanIoU
>>> miou = MeanIoU()
>>> preds = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(42))
>>> target = randint(0, 2, (10, 3, 128, 128), generator=torch.Generator().manual_seed(43))
>>> miou(preds, target)
tensor(0.3336)
>>> miou = MeanIoU(num_classes=3, per_class=True)
>>> miou(preds, target)
tensor([0.3361, 0.3340, 0.3308])
>>> miou = MeanIoU(per_class=True, include_background=False)
>>> miou(preds, target)
tensor([0.3340, 0.3308])
>>> miou = MeanIoU(num_classes=3, per_class=True, include_background=True, input_format="index")
>>> miou(preds, target)
tensor([ 0.3334,  0.3336, -1.0000])
```

#### `plot(val=None, ax=None)` {#torchmetrics.segmentation.MeanIoU.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/mean_iou.py#L188-L226)

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.audio import PerceptualEvaluationSpeechQuality
>>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
>>> metric.update(torch.rand(8000), torch.rand(8000))
>>> fig_, ax_ = metric.plot()
```

```python
>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
>>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
>>> values = [ ]
>>> for _ in range(10):
...     values.append(metric(torch.rand(8000), torch.rand(8000)))
>>> fig_, ax_ = metric.plot(values)
```

## Functional Interface {#functional-interface}

### `torchmetrics.functional.segmentation.mean_iou(preds, target, num_classes=None, include_background=True, per_class=False, input_format='one-hot')` {#torchmetrics.functional.segmentation.mean_iou}

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

Calculates the mean Intersection over Union (mIoU) for semantic segmentation.

Returns -1 if class is completely absent both from predictions and ground truth labels.

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** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – Number of classes (required when input\_format=”index”, optional when input\_format=”one-hot” or “mixed”)
    
*   **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 IoU for each class separately, else average over all 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
    

Return type:

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

Returns:

The mean IoU score

Example

```python
>>> import torch
>>> from torch import randint
>>> from torchmetrics.functional.segmentation import mean_iou
>>> # 4 samples, 5 classes, 16x16 prediction
>>> preds = randint(0, 2, (4, 5, 16, 16), generator=torch.Generator().manual_seed(42))
>>> # 4 samples, 5 classes, 16x16 target
>>> target = randint(0, 2, (4, 5, 16, 16), generator=torch.Generator().manual_seed(43))
>>> mean_iou(preds, target)
tensor([0.3323, 0.3336, 0.3397, 0.3435])
>>> mean_iou(preds, target, include_background=False, num_classes=5)
tensor([0.3250, 0.3258, 0.3307, 0.3398])
>>> mean_iou(preds, target, include_background=True, num_classes=5, per_class=True)
tensor([[0.3617, 0.3128, 0.3366, 0.3242, 0.3263],
        [0.3646, 0.2893, 0.3297, 0.3073, 0.3770],
        [0.3756, 0.3168, 0.3505, 0.3400, 0.3155],
        [0.3579, 0.3317, 0.3797, 0.3523, 0.2957]])
>>> # re-initialize tensors for ``input_format="index"``
>>> preds = randint(0, 2, (4, 16, 16), generator=torch.Generator().manual_seed(42))
>>> target = randint(0, 2, (4, 16, 16), generator=torch.Generator().manual_seed(43))
>>> mean_iou(preds, target, num_classes=5, input_format = "index")
tensor([0.3617, 0.3128, 0.3047, 0.3499])
>>> mean_iou(preds, target, num_classes=5, per_class=True, input_format="index")
tensor([[ 0.3617,  0.3617, -1.0000, -1.0000, -1.0000],
        [ 0.3128,  0.3128, -1.0000, -1.0000, -1.0000],
        [ 0.2727,  0.3366, -1.0000, -1.0000, -1.0000],
        [ 0.3756,  0.3242, -1.0000, -1.0000, -1.0000]])
```

---

**Navigation**

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