---
title: Edit Distance
description: Calculates the Levenshtein edit distance between two sequences.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/text/edit'
---
# Edit Distance {#edit-distance}

## Module Interface {#module-interface}

### `class torchmetrics.text.EditDistance(substitution_cost=1, reduction='mean', **kwargs)` {#torchmetrics.text.EditDistance}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/text/edit.py#L30-L175)

Calculates the Levenshtein edit distance between two sequences.

The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform the predicted text into the reference text. The lower the distance, the more accurate the model is considered to be.

Implementation is similar to [nltk.edit\_distance](https://www.nltk.org/_modules/nltk/metrics/distance.html).

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

*   `preds` (`Sequence`): An iterable of hypothesis corpus
    
*   `target` (`Sequence`): An iterable of iterables of reference corpus
    

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

*   `eed` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): A tensor with the extended edit distance score. If reduction is set to `'none'` or `None`, this has shape `(N, )`, where `N` is the batch size. Otherwise, this is a scalar.
    

Parameters:

*   **substitution\_cost** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – The cost of substituting one character for another.
    
*   **reduction** ([`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)")\[`'mean'`, `'sum'`, `'none'`\]\]) –
    
    a method to reduce metric score over samples.
    
    *   `'mean'`: takes the mean over samples
        
    *   `'sum'`: takes the sum over samples
        
    *   `None` or `'none'`: return the score per sample
        
    
*   **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::

Basic example with two strings. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits:

```python
>>> from torchmetrics.text import EditDistance
>>> metric = EditDistance()
>>> metric(["rain"], ["shine"])
tensor(3.)
```

Example::

Basic example with two strings and substitution cost of 2. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits, where two of them are substitutions:

```python
>>> from torchmetrics.text import EditDistance
>>> metric = EditDistance(substitution_cost=2)
>>> metric(["rain"], ["shine"])
tensor(5.)
```

Example::

Multiple strings example:

```python
>>> from torchmetrics.text import EditDistance
>>> metric = EditDistance(reduction=None)
>>> metric(["rain", "lnaguaeg"], ["shine", "language"])
tensor([3, 4], dtype=torch.int32)
>>> metric = EditDistance(reduction="mean")
>>> metric(["rain", "lnaguaeg"], ["shine", "language"])
tensor(3.5000)
```

#### `plot(val=None, ax=None)` {#torchmetrics.text.EditDistance.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/text/edit.py#L133-L175)

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
>>> from torchmetrics.text import EditDistance
>>> metric = EditDistance()
>>> preds = ["this is the prediction", "there is an other sample"]
>>> target = ["this is the reference", "there is another one"]
>>> metric.update(preds, target)
>>> fig_, ax_ = metric.plot()
```

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

```python
>>> # Example plotting multiple values
>>> from torchmetrics.text import EditDistance
>>> metric = EditDistance()
>>> preds = ["this is the prediction", "there is an other sample"]
>>> target = ["this is the reference", "there is another one"]
>>> values = [ ]
>>> for _ in range(10):
...     values.append(metric(preds, target))
>>> fig_, ax_ = metric.plot(values)
```

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

## Functional Interface {#functional-interface}

### `torchmetrics.functional.text.edit_distance(preds, target, substitution_cost=1, reduction='mean')` {#torchmetrics.functional.text.edit_distance}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/text/edit.py#L65-L120)

Calculates the Levenshtein edit distance between two sequences.

The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform the predicted text into the reference text. The lower the distance, the more accurate the model is considered to be.

Implementation is similar to [nltk.edit\_distance](https://www.nltk.org/_modules/nltk/metrics/distance.html).

Parameters:

*   **preds** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]\]) – An iterable of predicted texts (strings).
    
*   **target** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]\]) – An iterable of reference texts (strings).
    
*   **substitution\_cost** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – The cost of substituting one character for another.
    
*   **reduction** ([`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)")\[`'sum'`, `'mean'`, `'none'`\]\]) –
    
    a method to reduce metric score over samples.
    
    *   `'mean'`: takes the mean over samples
        
    *   `'sum'`: takes the sum over samples
        
    *   `None` or `'none'`: return the score per sample
        
    

Raises:

*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `preds` and `target` do not have the same length.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `preds` or `target` contain non-string values.
    

Return type:

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

Example::

Basic example with two strings. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits:

```python
>>> from torchmetrics.functional.text import edit_distance
>>> edit_distance(["rain"], ["shine"])
tensor(3.)
```

Example::

Basic example with two strings and substitution cost of 2. Going from “rain” -> “sain” -> “shin” -> “shine” takes 3 edits, where two of them are substitutions:

```python
>>> from torchmetrics.functional.text import edit_distance
>>> edit_distance(["rain"], ["shine"], substitution_cost=2)
tensor(5.)
```

Example::

Multiple strings example:

```python
>>> from torchmetrics.functional.text import edit_distance
>>> edit_distance(["rain", "lnaguaeg"], ["shine", "language"], reduction=None)
tensor([3, 4], dtype=torch.int32)
>>> edit_distance(["rain", "lnaguaeg"], ["shine", "language"], reduction="mean")
tensor(3.5000)
```

---

**Navigation**

- Parent: [Text](/docs/torchmetrics/1.9.0/text.md)
