clusteraccuracy
Metric
ClusterAccuracyfromtorchmetrics(torchmetrics.clustering.ClusterAccuracy)
When to invoke this skill
The user has predictions + ground truth and asks to evaluate with ClusterAccuracy, or
mentions torchmetrics.clustering.ClusterAccuracy directly, or wants the standard torchmetrics implementation.
Reference signature
from torchmetrics.clustering import ClusterAccuracy
# ClusterAccuracy(num_classes: int, **kwargs: Any) -> None
Library docstring
Compute `Cluster Accuracy`_ 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 :math:`g` is a function that maps predicted clusters :math:`p` to target clusters :math:`t`, :math:`N` is the
number of samples, :math:`p_n` is the predicted cluster for sample :math:`n`, :math:`t_n` is the target cluster for
sample :math:`n`, and :math:`\mathbb{1}` is the indicator function. The function :math:`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`` (:class:`~torch.Tensor`): single integer tensor with shape ``(N,)`` with predicted cluster labels
- ``target`` (:class:`~torch.Tensor`): 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`` (:class:`~torch.Tensor`): A tensor with the Cluster Accuracy score
Args:
num_classes: number of classes
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Raises:
RuntimeError:
If ``torch_linear_assignment`` is not installed. To install, run ``pip install torchmetrics[clustering]``.
ValueError
If ``num_classes`` is not a positive integer
Example::
>>> 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.)
Quick recipe
import torchmetrics.clustering as _m
score = _m.ClusterAccuracy(y_true, y_pred)
Don'ts
- Don't reimplement when the library version handles edge cases (NaN, ties, empty inputs) better than a hand-rolled formula.
- Always check the library version's argument order — sklearn is
(y_true, y_pred)while torchmetrics is(preds, target).