dunn_index.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 collections.abc import Sequence
  15. from typing import Any, List, Optional, Union
  16. from torch import Tensor
  17. from torchmetrics.functional.clustering.dunn_index import dunn_index
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.data import dim_zero_cat
  20. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  21. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  22. if not _MATPLOTLIB_AVAILABLE:
  23. __doctest_skip__ = ["DunnIndex.plot"]
  24. class DunnIndex(Metric):
  25. r"""Compute `Dunn Index`_.
  26. .. math::
  27. DI_m = \frac{\min_{1\leq i<j\leq m} \delta(C_i,C_j)}{\max_{1\leq k\leq m} \Delta_k}
  28. Where :math:`C_i` is a cluster of tensors, :math:`C_j` is a cluster of tensors,
  29. and :math:`\delta(C_i,C_j)` is the intercluster distance metric for :math:`m` clusters.
  30. This clustering metric is an intrinsic measure, because it does not rely on ground truth labels for the evaluation.
  31. Instead it examines how well the clusters are separated from each other. The score is higher when clusters are dense
  32. and well separated, which relates to a standard concept of a cluster.
  33. As input to ``forward`` and ``update`` the metric accepts the following input:
  34. - ``data`` (:class:`~torch.Tensor`): float tensor with shape ``(N,d)`` with the embedded data. ``d`` is the
  35. dimensionality of the embedding space.
  36. - ``labels`` (:class:`~torch.Tensor`): single integer tensor with shape ``(N,)`` with cluster labels
  37. As output of ``forward`` and ``compute`` the metric returns the following output:
  38. - ``dunn_index`` (:class:`~torch.Tensor`): A tensor with the Dunn Index
  39. Args:
  40. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  41. Example::
  42. >>> import torch
  43. >>> from torchmetrics.clustering import DunnIndex
  44. >>> data = torch.tensor([[0, 0], [0.5, 0], [1, 0], [0.5, 1]])
  45. >>> labels = torch.tensor([0, 0, 0, 1])
  46. >>> dunn_index = DunnIndex(p=2)
  47. >>> dunn_index(data, labels)
  48. tensor(2.)
  49. """
  50. is_differentiable: bool = True
  51. higher_is_better: bool = True
  52. full_state_update: bool = False
  53. plot_lower_bound: float = 0.0
  54. data: List[Tensor]
  55. labels: List[Tensor]
  56. def __init__(self, p: float = 2, **kwargs: Any) -> None:
  57. super().__init__(**kwargs)
  58. self.p = p
  59. self.add_state("data", default=[], dist_reduce_fx="cat")
  60. self.add_state("labels", default=[], dist_reduce_fx="cat")
  61. def update(self, data: Tensor, labels: Tensor) -> None:
  62. """Update state with predictions and targets."""
  63. self.data.append(data)
  64. self.labels.append(labels)
  65. def compute(self) -> Tensor:
  66. """Compute mutual information over state."""
  67. return dunn_index(dim_zero_cat(self.data), dim_zero_cat(self.labels), self.p)
  68. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  69. """Plot a single or multiple values from the metric.
  70. Args:
  71. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  72. If no value is provided, will automatically call `metric.compute` and plot that result.
  73. ax: An matplotlib axis object. If provided will add plot to that axis
  74. Returns:
  75. Figure and Axes object
  76. Raises:
  77. ModuleNotFoundError:
  78. If `matplotlib` is not installed
  79. .. plot::
  80. :scale: 75
  81. >>> # Example plotting a single value
  82. >>> import torch
  83. >>> from torchmetrics.clustering import DunnIndex
  84. >>> data = torch.tensor([[0, 0], [0.5, 0], [1, 0], [0.5, 1]])
  85. >>> labels = torch.tensor([0, 0, 0, 1])
  86. >>> metric = DunnIndex(p=2)
  87. >>> metric.update(data, labels)
  88. >>> fig_, ax_ = metric.plot(metric.compute())
  89. .. plot::
  90. :scale: 75
  91. >>> # Example plotting multiple values
  92. >>> import torch
  93. >>> from torchmetrics.clustering import DunnIndex
  94. >>> metric = DunnIndex(p=2)
  95. >>> values = [ ]
  96. >>> for _ in range(10):
  97. ... values.append(metric(torch.randn(50, 3), torch.randint(0, 2, (50,))))
  98. >>> fig_, ax_ = metric.plot(values)
  99. """
  100. return self._plot(val, ax)