---
title: Hausdorff Distance
description: >-
  Compute the Hausdorff Distance between two subsets of a metric space for
  semantic segmentation.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/segmentation/hausdorff_distance'
---
# Hausdorff Distance {#hausdorff-distance}

## Module Interface {#module-interface}

### `class torchmetrics.segmentation.HausdorffDistance(num_classes, include_background=False, distance_metric='euclidean', spacing=None, directed=False, input_format='one-hot', **kwargs)` {#torchmetrics.segmentation.HausdorffDistance}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/hausdorff_distance.py#L31-L159)

Compute the [Hausdorff Distance](https://en.wikipedia.org/wiki/Hausdorff_distance) between two subsets of a metric space for semantic segmentation.

```math
d_{\Pi}(X,Y) = \max{/sup_{x\in X} {d(x,Y)}, /sup_{y\in Y} {d(X,y)}}
```

where $`\X, \Y`$ are two subsets of a metric space with distance metric $`d`$. The Hausdorff distance is the maximum distance from a point in one set to the closest point in the other set. The Hausdorff distance is a measure of the degree of mismatch between two sets.

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 of `forward` and `compute` the metric returns the following output:

*   `hausdorff_distance` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): A scalar float tensor with the Hausdorff distance averaged over
    
    classes and samples
    

Parameters:

*   **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 background class in calculation
    
*   **distance\_metric** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'euclidean'`, `'chessboard'`, `'taxicab'`\]) – distance metric to calculate surface distance. Choose one of “euclidean”, “chessboard” or “taxicab”
    
*   **spacing** (`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – spacing between pixels along each spatial dimension. If not provided the spacing is assumed to be 1
    
*   **directed** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – whether to calculate directed or undirected Hausdorff distance
    
*   **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.
    

Example

```python
>>> from torch import randint
>>> from torchmetrics.segmentation import HausdorffDistance
>>> 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
>>> hausdorff_distance = HausdorffDistance(distance_metric="euclidean", num_classes=5)
>>> hausdorff_distance(preds, target)
tensor(1.9567)
```

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

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/segmentation/hausdorff_distance.py#L130-L159)

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
>>> from torch import randint
>>> from torchmetrics.segmentation import HausdorffDistance
>>> 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
>>> metric = HausdorffDistance(num_classes=5)
>>> metric.update(preds, target)
>>> fig_, ax_ = metric.plot()
```

[![../../\_images/hausdorff\_distance-1.png](/docs/torchmetrics/1.9.0/static/_images/hausdorff_distance-1.png)](/docs/torchmetrics/1.9.0/static/_images/hausdorff_distance-1.png)

## Functional Interface {#functional-interface}

### `torchmetrics.functional.segmentation.hausdorff_distance(preds, target, num_classes, include_background=False, distance_metric='euclidean', spacing=None, directed=False, input_format='one-hot')` {#torchmetrics.functional.segmentation.hausdorff_distance}

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

Calculate [Hausdorff Distance](https://en.wikipedia.org/wiki/Hausdorff_distance) for semantic segmentation.

Parameters:

*   **preds** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – predicted binarized segmentation map
    
*   **target** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – target binarized segmentation map
    
*   **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 background class in calculation
    
*   **distance\_metric** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'euclidean'`, `'chessboard'`, `'taxicab'`\]) – distance metric to calculate surface distance. Choose one of “euclidean”, “chessboard” or “taxicab”
    
*   **spacing** (`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – spacing between pixels along each spatial dimension. If not provided the spacing is assumed to be 1
    
*   **directed** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – whether to calculate directed or undirected Hausdorff distance
    
*   **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:

Hausdorff Distance for each class and batch element

Example

```python
>>> from torch import randint
>>> from torchmetrics.functional.segmentation import hausdorff_distance
>>> 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
>>> hausdorff_distance(preds, target, num_classes=5)
tensor([[2.0000, 1.4142, 2.0000, 2.0000],
        [1.4142, 2.0000, 2.0000, 2.0000],
        [2.0000, 2.0000, 1.4142, 2.0000],
        [2.0000, 2.8284, 2.0000, 2.2361]])
```

---

**Navigation**

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