calinskiharabaszscore
Metric
CalinskiHarabaszScorefromtorchmetrics(torchmetrics.clustering.CalinskiHarabaszScore)
When to invoke this skill
The user has predictions + ground truth and asks to evaluate with CalinskiHarabaszScore, or
mentions torchmetrics.clustering.CalinskiHarabaszScore directly, or wants the standard torchmetrics implementation.
Reference signature
from torchmetrics.clustering import CalinskiHarabaszScore
# CalinskiHarabaszScore(**kwargs: Any) -> None
Library docstring
Compute Calinski Harabasz Score (also known as variance ratio criterion) for clustering algorithms.
.. math::
CHS(X, L) = \frac{B(X, L) \cdot (n_\text{samples} - n_\text{labels})}{W(X, L) \cdot (n_\text{labels} - 1)}
where :math:`B(X, L)` is the between-cluster dispersion, which is the squared distance between the cluster centers
and the dataset mean, weighted by the size of the clusters, :math:`n_\text{samples}` is the number of samples,
:math:`n_\text{labels}` is the number of labels, and :math:`W(X, L)` is the within-cluster dispersion e.g. the
sum of squared distances between each samples and its closest cluster center.
This clustering metric is an intrinsic measure, because it does not rely on ground truth labels for the evaluation.
Instead it examines how well the clusters are separated from each other. The score is higher when clusters are dense
and well separated, which relates to a standard concept of a cluster.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``data`` (:class:`~torch.Tensor`): float tensor with shape ``(N,d)`` with the embedded data. ``d`` is the
dimensionality of the embedding space.
- ``labels`` (:class:`~torch.Tensor`): single integer tensor with shape ``(N,)`` with cluster labels
As output of ``forward`` and ``compute`` the metric returns the following output:
- ``chs`` (:class:`~torch.Tensor`): A tensor with the Calinski Harabasz Score
Args:
kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
Example::
>>> from torch import randn, randint
>>> from torchmetrics.clustering import CalinskiHarabaszScore
>>> data = randn(20, 3)
>>> labels = randint(3, (20,))
>>> metric = CalinskiHarabaszScore()
>>> metric(data, labels)
tensor(2.2128)
Quick recipe
import torchmetrics.clustering as _m
score = _m.CalinskiHarabaszScore(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).