---
title: Theil's U
description: >-
  Compute Theil’s U statistic measuring the association between two categorical
  (nominal) data series.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/nominal/theils_u'
---
# Theil's U {#theil-s-u}

## Module Interface {#module-interface}

### `class torchmetrics.nominal.TheilsU(num_classes, nan_strategy='replace', nan_replace_value=0.0, **kwargs)` {#torchmetrics.nominal.TheilsU}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/nominal/theils_u.py#L31-L143)

Compute [Theil’s U](#theil-s-u) statistic measuring the association between two categorical (nominal) data series.

```math
U(X|Y) = \frac{H(X) - H(X|Y)}{H(X)}
```

where $`H(X)`$ is entropy of variable $`X`$ while $`H(X|Y)`$ is the conditional entropy of $`X`$ given $`Y`$. It is also know as the Uncertainty Coefficient. Theils’s U is an asymmetric coefficient, i.e. $`TheilsU(preds, target) \neq TheilsU(target, preds)`$, so the order of the inputs matters. The output values lies in \[0, 1\], where a 0 means y has no information about x while value 1 means y has complete information about x.

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)")): Either 1D or 2D tensor of categorical (nominal) data from the first data series (called X in the above definition) with shape `(batch_size,)` or `(batch_size, num_classes)`, respectively.
    
*   `target` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): Either 1D or 2D tensor of categorical (nominal) data from the second data series (called Y in the above definition) with shape `(batch_size,)` or `(batch_size, num_classes)`, respectively.
    

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

*   `theils_u` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): Scalar tensor containing the Theil’s U statistic.
    

Parameters:

*   **num\_classes** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – Integer specifying the number of classes
    
*   **nan\_strategy** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'replace'`, `'drop'`\]) – Indication of whether to replace or drop `NaN` values
    
*   **nan\_replace\_value** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – Value to replace `NaN``s when ``nan_strategy = 'replace'`
    
*   **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.nominal import TheilsU
>>> preds = randint(10, (10,))
>>> target = randint(10, (10,))
>>> metric = TheilsU(num_classes=10)
>>> metric(preds, target)
tensor(0.8530)
```

#### `plot(val=None, ax=None)` {#torchmetrics.nominal.TheilsU.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/nominal/theils_u.py#L105-L143)

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.nominal import TheilsU
>>> metric = TheilsU(num_classes=10)
>>> metric.update(torch.randint(10, (10,)), torch.randint(10, (10,)))
>>> fig_, ax_ = metric.plot()
```

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

```python
>>> # Example plotting multiple values
>>> import torch
>>> from torchmetrics.nominal import TheilsU
>>> metric = TheilsU(num_classes=10)
>>> values = [ ]
>>> for _ in range(10):
...     values.append(metric(torch.randint(10, (10,)), torch.randint(10, (10,))))
>>> fig_, ax_ = metric.plot(values)
```

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

## Functional Interface {#functional-interface}

### `torchmetrics.functional.nominal.theils_u(preds, target, nan_strategy='replace', nan_replace_value=0.0)` {#torchmetrics.functional.nominal.theils_u}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/nominal/theils_u.py#L108-L151)

Compute [Theils Uncertainty coefficient](https://en.wikipedia.org/wiki/Uncertainty_coefficient) statistic measuring the association between two nominal data series.

```math
U(X|Y) = \frac{H(X) - H(X|Y)}{H(X)}
```

where $`H(X)`$ is entropy of variable $`X`$ while $`H(X|Y)`$ is the conditional entropy of $`X`$ given $`Y`$.

Theils’s U is an asymmetric coefficient, i.e. $`TheilsU(preds, target) \neq TheilsU(target, preds)`$.

The output values lies in \[0, 1\]. 0 means y has no information about x while value 1 means y has complete information about x.

Parameters:

*   **preds** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – 1D or 2D tensor of categorical (nominal) data - 1D shape: (batch\_size,) - 2D shape: (batch\_size, num\_classes)
    
*   **target** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – 1D or 2D tensor of categorical (nominal) data - 1D shape: (batch\_size,) - 2D shape: (batch\_size, num\_classes)
    
*   **nan\_strategy** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'replace'`, `'drop'`\]) – Indication of whether to replace or drop `NaN` values
    
*   **nan\_replace\_value** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – Value to replace `NaN``s when ``nan_strategy = 'replace'`
    

Return type:

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

Returns:

Tensor containing Theil’s U statistic

Example

```python
>>> from torch import randint
>>> from torchmetrics.functional.nominal import theils_u
>>> preds = randint(10, (10,))
>>> target = randint(10, (10,))
>>> theils_u(preds, target)
tensor(0.8530)
```

### theils_u_matrix {#theils-u-matrix}

### `torchmetrics.functional.nominal.theils_u_matrix(matrix, nan_strategy='replace', nan_replace_value=0.0)` {#torchmetrics.functional.nominal.theils_u_matrix}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/nominal/theils_u.py#L154-L195)

Compute [Theil’s U](#theil-s-u) statistic between a set of multiple variables.

This can serve as a convenient tool to compute Theil’s U statistic for analyses of correlation between categorical variables in your dataset.

Parameters:

*   **matrix** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – A tensor of categorical (nominal) data, where: - rows represent a number of data points - columns represent a number of categorical (nominal) features
    
*   **nan\_strategy** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'replace'`, `'drop'`\]) – Indication of whether to replace or drop `NaN` values
    
*   **nan\_replace\_value** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – Value to replace `NaN``s when ``nan_strategy = 'replace'`
    

Return type:

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

Returns:

Theil’s U statistic for a dataset of categorical variables

Example

```python
>>> from torch import randint
>>> from torchmetrics.functional.nominal import theils_u_matrix
>>> matrix = randint(0, 4, (200, 5))
>>> theils_u_matrix(matrix)
tensor([[1.0000, 0.0202, 0.0142, 0.0196, 0.0353],
        [0.0202, 1.0000, 0.0070, 0.0136, 0.0065],
        [0.0143, 0.0070, 1.0000, 0.0125, 0.0206],
        [0.0198, 0.0137, 0.0125, 1.0000, 0.0312],
        [0.0352, 0.0065, 0.0204, 0.0308, 1.0000]])
```

---

**Navigation**

- Parent: [Nominal](/docs/torchmetrics/1.9.0/nominal.md)
