|
| 1 | +# Copyright The Lightning team. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from typing import Any, List, Optional, Sequence, Union |
| 15 | + |
| 16 | +from torch import Tensor |
| 17 | + |
| 18 | +from torchmetrics.functional.clustering.rand_score import rand_score |
| 19 | +from torchmetrics.metric import Metric |
| 20 | +from torchmetrics.utilities.data import dim_zero_cat |
| 21 | +from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE |
| 22 | +from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE |
| 23 | + |
| 24 | +if not _MATPLOTLIB_AVAILABLE: |
| 25 | + __doctest_skip__ = ["RandScore.plot"] |
| 26 | + |
| 27 | + |
| 28 | +class RandScore(Metric): |
| 29 | + r"""Compute `Rand Score`_ (alternatively known as Rand Index). |
| 30 | +
|
| 31 | + .. math:: |
| 32 | + RS(U, V) = \text{number of agreeing pairs} / \text{number of pairs} |
| 33 | +
|
| 34 | + The number of agreeing pairs is every :math:`(i, j)` pair of samples where :math:`i \in U` and :math:`j \in V` |
| 35 | + (the predicted and true clusterings, respectively) that are in the same cluster for both clusterings. |
| 36 | +
|
| 37 | + The metric is symmetric, therefore swapping :math:`U` and :math:`V` yields the same rand score. |
| 38 | +
|
| 39 | + As input to ``forward`` and ``update`` the metric accepts the following input: |
| 40 | +
|
| 41 | + - ``preds`` (:class:`~torch.Tensor`): single integer tensor with shape ``(N,)`` with predicted cluster labels |
| 42 | + - ``target`` (:class:`~torch.Tensor`): single integer tensor with shape ``(N,)`` with ground truth cluster labels |
| 43 | +
|
| 44 | + As output of ``forward`` and ``compute`` the metric returns the following output: |
| 45 | +
|
| 46 | + - ``rand_score`` (:class:`~torch.Tensor`): A tensor with the Rand Score |
| 47 | +
|
| 48 | + Args: |
| 49 | + kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info. |
| 50 | +
|
| 51 | + Example: |
| 52 | + >>> import torch |
| 53 | + >>> from torchmetrics.clustering import RandScore |
| 54 | + >>> preds = torch.tensor([2, 1, 0, 1, 0]) |
| 55 | + >>> target = torch.tensor([0, 2, 1, 1, 0]) |
| 56 | + >>> metric = RandScore() |
| 57 | + >>> metric(preds, target) |
| 58 | + tensor(0.6000) |
| 59 | +
|
| 60 | + """ |
| 61 | + |
| 62 | + is_differentiable = True |
| 63 | + higher_is_better = None |
| 64 | + full_state_update: bool = True |
| 65 | + plot_lower_bound: float = 0.0 |
| 66 | + preds: List[Tensor] |
| 67 | + target: List[Tensor] |
| 68 | + contingency: Tensor |
| 69 | + |
| 70 | + def __init__(self, **kwargs: Any) -> None: |
| 71 | + super().__init__(**kwargs) |
| 72 | + |
| 73 | + self.add_state("preds", default=[], dist_reduce_fx="cat") |
| 74 | + self.add_state("target", default=[], dist_reduce_fx="cat") |
| 75 | + |
| 76 | + def update(self, preds: Tensor, target: Tensor) -> None: |
| 77 | + """Update state with predictions and targets.""" |
| 78 | + self.preds.append(preds) |
| 79 | + self.target.append(target) |
| 80 | + |
| 81 | + def compute(self) -> Tensor: |
| 82 | + """Compute rand score over state.""" |
| 83 | + return rand_score(dim_zero_cat(self.preds), dim_zero_cat(self.target)) |
| 84 | + |
| 85 | + def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE: |
| 86 | + """Plot a single or multiple values from the metric. |
| 87 | +
|
| 88 | + Args: |
| 89 | + val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results. |
| 90 | + If no value is provided, will automatically call `metric.compute` and plot that result. |
| 91 | + ax: An matplotlib axis object. If provided will add plot to that axis |
| 92 | +
|
| 93 | + Returns: |
| 94 | + Figure and Axes object |
| 95 | +
|
| 96 | + Raises: |
| 97 | + ModuleNotFoundError: |
| 98 | + If `matplotlib` is not installed |
| 99 | +
|
| 100 | + .. plot:: |
| 101 | + :scale: 75 |
| 102 | +
|
| 103 | + >>> # Example plotting a single value |
| 104 | + >>> import torch |
| 105 | + >>> from torchmetrics.clustering import RandScore |
| 106 | + >>> metric = RandScore() |
| 107 | + >>> metric.update(torch.randint(0, 4, (10,)), torch.randint(0, 4, (10,))) |
| 108 | + >>> fig_, ax_ = metric.plot(metric.compute()) |
| 109 | +
|
| 110 | + .. plot:: |
| 111 | + :scale: 75 |
| 112 | +
|
| 113 | + >>> # Example plotting multiple values |
| 114 | + >>> import torch |
| 115 | + >>> from torchmetrics.clustering import RandScore |
| 116 | + >>> metric = RandScore() |
| 117 | + >>> for _ in range(10): |
| 118 | + ... metric.update(torch.randint(0, 4, (10,)), torch.randint(0, 4, (10,))) |
| 119 | + >>> fig_, ax_ = metric.plot(metric.compute()) |
| 120 | +
|
| 121 | + """ |
| 122 | + return self._plot(val, ax) |
0 commit comments