---
title: Total Variation (TV)
description: Compute Total Variation loss (TV).
canonical: 'https://lightning.ai/docs/torchmetrics/stable/image/total_variation'
---
# Total Variation (TV) {#total-variation-tv}

## Module Interface {#module-interface}

### `class torchmetrics.image.TotalVariation(reduction='sum', **kwargs)` {#torchmetrics.image.TotalVariation}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/image/tv.py#L31-L139)

Compute Total Variation loss ([TV](https://en.wikipedia.org/wiki/Total_variation_denoising)).

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

*   `img` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): A tensor of shape `(N, C, H, W)` consisting of images
    

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

*   `sdi` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): if `reduction!='none'` returns float scalar tensor with average TV value over sample else returns tensor of shape `(N,)` with TV values per sample
    

Parameters:

*   **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.
    

Raises:

[**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `reduction` is not one of `'sum'`, `'mean'`, `'none'` or `None`

Example

```python
>>> from torch import rand
>>> from torchmetrics.image import TotalVariation
>>> tv = TotalVariation()
>>> img = torch.rand(5, 3, 28, 28)
>>> tv(img)
tensor(7546.8018)
```

#### `plot(val=None, ax=None)` {#torchmetrics.image.TotalVariation.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/image/tv.py#L99-L139)

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.image import TotalVariation
>>> metric = TotalVariation()
>>> metric.update(torch.rand(5, 3, 28, 28))
>>> fig_, ax_ = metric.plot()
```

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

```python
>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.image import TotalVariation
>>> metric = TotalVariation()
>>> values = [ ]
>>> for _ in range(10):
...     values.append(metric(torch.rand(5, 3, 28, 28)))
>>> fig_, ax_ = metric.plot(values)
```

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

## Functional Interface {#functional-interface}

### `torchmetrics.functional.image.total_variation(img, reduction='sum')` {#torchmetrics.functional.image.total_variation}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/image/tv.py#L46-L77)

Compute total variation loss.

Parameters:

*   **img** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – A Tensor of shape (N, C, H, W) consisting of images
    
*   **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
        
    

Return type:

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

Returns:

A loss scalar value containing the total variation

Raises:

*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `reduction` is not one of `'sum'`, `'mean'`, `'none'` or `None`
    
*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If `img` is not 4D tensor
    

Example

```python
>>> from torch import rand
>>> from torchmetrics.functional.image import total_variation
>>> img = rand(5, 3, 28, 28)
>>> total_variation(img)
tensor(7546.8018)
```

---

**Navigation**

- Parent: [Image](/docs/torchmetrics/1.9.0/image.md)
