---
title: Cluster Accuracy
description: Compute Cluster Accuracy between predicted and target clusters.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/clustering/cluster_accuracy'
---
# Cluster Accuracy {#cluster-accuracy}

## Module Interface {#module-interface}

### `class torchmetrics.clustering.ClusterAccuracy(num_classes, **kwargs)` {#torchmetrics.clustering.ClusterAccuracy}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/clustering/cluster_accuracy.py#L35-L148)

Compute [Cluster Accuracy](https://arxiv.org/abs/2206.07579) between predicted and target clusters.

```math
\text{Cluster Accuracy} = \max_g \frac{1}{N} \sum_{n=1}^N \mathbb{1}_{g(p_n) = t_n}
```

Where $`g`$ is a function that maps predicted clusters $`p`$ to target clusters $`t`$, $`N`$ is the number of samples, $`p_n`$ is the predicted cluster for sample $`n`$, $`t_n`$ is the target cluster for sample $`n`$, and $`\mathbb{1}`$ is the indicator function. The function $`g`$ is determined by solving the linear sum assignment problem.

This clustering metric is an extrinsic measure, because it requires ground truth clustering labels, which may not be available in practice since clustering in generally is used for unsupervised learning.

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)")): single integer tensor with shape `(N,)` with predicted cluster labels
    
*   `target` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): single integer tensor with shape `(N,)` with ground truth cluster labels
    

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

*   `acc_score` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): A tensor with the Cluster Accuracy score
    

Parameters:

*   **num\_classes** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – number of classes
    
*   **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:

*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If `torch_linear_assignment` is not installed. To install, run `pip install torchmetrics[clustering]`.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `num_classes` is not a positive integer
    

Example::

```python
>>> import torch
>>> from torchmetrics.clustering import ClusterAccuracy
>>> preds = torch.tensor([0, 0, 1, 1])
>>> target = torch.tensor([1, 1, 0, 0])
>>> metric = ClusterAccuracy(num_classes=2)
>>> metric(preds, target)
tensor(1.)
```

#### `plot(val=None, ax=None)` {#torchmetrics.clustering.ClusterAccuracy.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/clustering/cluster_accuracy.py#L109-L148)

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/typing.html#typing.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.clustering import ClusterAccuracy
>>> metric = ClusterAccuracy(num_classes=4)
>>> metric.update(torch.randint(0, 4, (10,)), torch.randint(0, 4, (10,)))
>>> fig_, ax_ = metric.plot(metric.compute())
```

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

## Functional Interface {#functional-interface}

### `torchmetrics.functional.clustering.cluster_accuracy(preds, target, num_classes)` {#torchmetrics.functional.clustering.cluster_accuracy}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/clustering/cluster_accuracy.py#L38-L67)

Computes the clustering accuracy between the predicted and target clusters.

Parameters:

*   **preds** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – predicted cluster labels
    
*   **target** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – ground truth cluster labels
    
*   **num\_classes** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – number of classes
    

Return type:

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

Returns:

Scalar tensor with clustering accuracy between 0.0 and 1.0

Raises:

[**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If torch\_linear\_assignment is not installed

Example

```python
>>> from torchmetrics.functional.clustering import cluster_accuracy
>>> preds = torch.tensor([0, 0, 1, 1])
>>> target = torch.tensor([1, 1, 0, 0])
>>> cluster_accuracy(preds, target, 2)
tensor(1.000)
```

---

**Navigation**

- Parent: [Clustering](/docs/torchmetrics/1.9.0/clustering.md)
