utils.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 Optional, Union
  15. import torch
  16. from torch import Tensor, tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.utilities.checks import _check_same_shape
  19. def is_nonnegative(x: Tensor, atol: float = 1e-5) -> Tensor:
  20. """Return True if all elements of tensor are nonnegative within certain tolerance.
  21. Args:
  22. x: tensor
  23. atol: absolute tolerance
  24. Returns:
  25. Boolean tensor indicating if all values are nonnegative
  26. """
  27. return torch.logical_or(x > 0.0, torch.abs(x) < atol).all()
  28. def _validate_average_method_arg(
  29. average_method: Literal["min", "geometric", "arithmetic", "max"] = "arithmetic",
  30. ) -> None:
  31. if average_method not in ("min", "geometric", "arithmetic", "max"):
  32. raise ValueError(
  33. "Expected argument `average_method` to be one of `min`, `geometric`, `arithmetic`, `max`,"
  34. f"but got {average_method}"
  35. )
  36. def calculate_entropy(x: Tensor) -> Tensor:
  37. """Calculate entropy for a tensor of labels.
  38. Final calculation of entropy is performed in log form to account for roundoff error.
  39. Args:
  40. x: labels
  41. Returns:
  42. entropy: entropy of tensor
  43. Example:
  44. >>> from torchmetrics.functional.clustering.utils import calculate_entropy
  45. >>> labels = torch.tensor([1, 3, 2, 2, 1])
  46. >>> calculate_entropy(labels)
  47. tensor(1.0549)
  48. """
  49. if len(x) == 0:
  50. return tensor(1.0, device=x.device)
  51. p = torch.bincount(torch.unique(x, return_inverse=True)[1])
  52. p = p[p > 0]
  53. if p.size() == 1:
  54. return tensor(0.0, device=x.device)
  55. n = p.sum()
  56. return -torch.sum((p / n) * (torch.log(p) - torch.log(n)))
  57. def calculate_generalized_mean(x: Tensor, p: Union[int, Literal["min", "geometric", "arithmetic", "max"]]) -> Tensor:
  58. """Return generalized (power) mean of a tensor.
  59. Args:
  60. x: tensor
  61. p: power
  62. Returns:
  63. generalized_mean: generalized mean
  64. Example (p="min"):
  65. >>> from torchmetrics.functional.clustering.utils import calculate_generalized_mean
  66. >>> x = torch.tensor([1, 3, 2, 2, 1])
  67. >>> calculate_generalized_mean(x, "min")
  68. tensor(1)
  69. Example (p="geometric"):
  70. >>> from torchmetrics.functional.clustering.utils import calculate_generalized_mean
  71. >>> x = torch.tensor([1, 3, 2, 2, 1])
  72. >>> calculate_generalized_mean(x, "geometric")
  73. tensor(1.6438)
  74. """
  75. if torch.is_complex(x) or not is_nonnegative(x):
  76. raise ValueError("`x` must contain positive real numbers")
  77. if isinstance(p, str):
  78. if p == "min":
  79. return x.min()
  80. if p == "geometric":
  81. return torch.exp(torch.mean(x.log()))
  82. if p == "arithmetic":
  83. return x.mean()
  84. if p == "max":
  85. return x.max()
  86. raise ValueError("'method' must be 'min', 'geometric', 'arirthmetic', or 'max'")
  87. return torch.mean(torch.pow(x, p)) ** (1.0 / p)
  88. def calculate_contingency_matrix(
  89. preds: Tensor, target: Tensor, eps: Optional[float] = None, sparse: bool = False
  90. ) -> Tensor:
  91. """Calculate contingency matrix.
  92. Args:
  93. preds: predicted labels
  94. target: ground truth labels
  95. eps: value added to contingency matrix
  96. sparse: If True, returns contingency matrix as a sparse matrix. Else, return as dense matrix.
  97. `eps` must be `None` if `sparse` is `True`.
  98. Returns:
  99. contingency: contingency matrix of shape (n_classes_target, n_classes_preds)
  100. Example:
  101. >>> import torch
  102. >>> from torchmetrics.functional.clustering.utils import calculate_contingency_matrix
  103. >>> preds = torch.tensor([2, 1, 0, 1, 0])
  104. >>> target = torch.tensor([0, 2, 1, 1, 0])
  105. >>> calculate_contingency_matrix(preds, target, eps=1e-16)
  106. tensor([[1.0000e+00, 1.0000e-16, 1.0000e+00],
  107. [1.0000e+00, 1.0000e+00, 1.0000e-16],
  108. [1.0000e-16, 1.0000e+00, 1.0000e-16]])
  109. """
  110. if eps is not None and sparse is True:
  111. raise ValueError("Cannot specify `eps` and return sparse tensor.")
  112. if preds.ndim != 1 or target.ndim != 1:
  113. raise ValueError(f"Expected 1d `preds` and `target` but got {preds.ndim} and {target.dim}.")
  114. preds_classes, preds_idx = torch.unique(preds, return_inverse=True)
  115. target_classes, target_idx = torch.unique(target, return_inverse=True)
  116. num_classes_preds = preds_classes.size(0)
  117. num_classes_target = target_classes.size(0)
  118. contingency = torch.sparse_coo_tensor(
  119. torch.stack((
  120. target_idx,
  121. preds_idx,
  122. )),
  123. torch.ones(target_idx.shape[0], dtype=preds_idx.dtype, device=preds_idx.device),
  124. (
  125. num_classes_target,
  126. num_classes_preds,
  127. ),
  128. )
  129. if not sparse:
  130. contingency = contingency.to_dense()
  131. if eps:
  132. contingency = contingency + eps
  133. return contingency
  134. def _is_real_discrete_label(x: Tensor) -> bool:
  135. """Check if tensor of labels is real and discrete."""
  136. if x.ndim != 1:
  137. raise ValueError(f"Expected arguments to be 1-d tensors but got {x.ndim}-d tensors.")
  138. return not (torch.is_floating_point(x) or torch.is_complex(x))
  139. def check_cluster_labels(preds: Tensor, target: Tensor) -> None:
  140. """Check shape of input tensors and if they are real, discrete tensors.
  141. Args:
  142. preds: predicted labels
  143. target: ground truth labels
  144. """
  145. _check_same_shape(preds, target)
  146. if not (_is_real_discrete_label(preds) and _is_real_discrete_label(target)):
  147. raise ValueError(f"Expected real, discrete values for x but received {preds.dtype} and {target.dtype}.")
  148. def _validate_intrinsic_cluster_data(data: Tensor, labels: Tensor) -> None:
  149. """Validate that the input data and labels have correct shape and type."""
  150. if data.ndim != 2:
  151. raise ValueError(f"Expected 2D data, got {data.ndim}D data instead")
  152. if not data.is_floating_point():
  153. raise ValueError(f"Expected floating point data, got {data.dtype} data instead")
  154. if labels.ndim != 1:
  155. raise ValueError(f"Expected 1D labels, got {labels.ndim}D labels instead")
  156. def _validate_intrinsic_labels_to_samples(num_labels: int, num_samples: int) -> None:
  157. """Validate that the number of labels are in the correct range."""
  158. if not 1 < num_labels < num_samples:
  159. raise ValueError(
  160. "Number of detected clusters must be greater than one and less than the number of samples."
  161. f"Got {num_labels} clusters and {num_samples} samples."
  162. )
  163. def calculate_pair_cluster_confusion_matrix(
  164. preds: Optional[Tensor] = None,
  165. target: Optional[Tensor] = None,
  166. contingency: Optional[Tensor] = None,
  167. ) -> Tensor:
  168. """Calculates the pair cluster confusion matrix.
  169. Can either be calculated from predicted cluster labels and target cluster labels or from a pre-computed
  170. contingency matrix. The pair cluster confusion matrix is a 2x2 matrix where that defines the similarity between
  171. two clustering by considering all pairs of samples and counting pairs that are assigned into same or different
  172. clusters in the predicted and target clusterings.
  173. Note that the matrix is not symmetric.
  174. Inspired by:
  175. https://scikit-learn.org/stable/modules/generated/sklearn.metrics.cluster.pair_confusion_matrix.html
  176. Args:
  177. preds: predicted cluster labels
  178. target: ground truth cluster labels
  179. contingency: contingency matrix
  180. Returns:
  181. A 2x2 tensor containing the pair cluster confusion matrix.
  182. Raises:
  183. ValueError:
  184. If neither `preds` and `target` nor `contingency` are provided.
  185. ValueError:
  186. If both `preds` and `target` and `contingency` are provided.
  187. Example:
  188. >>> import torch
  189. >>> from torchmetrics.functional.clustering.utils import calculate_pair_cluster_confusion_matrix
  190. >>> preds = torch.tensor([0, 0, 1, 1])
  191. >>> target = torch.tensor([1, 1, 0, 0])
  192. >>> calculate_pair_cluster_confusion_matrix(preds, target)
  193. tensor([[8, 0],
  194. [0, 4]])
  195. >>> preds = torch.tensor([0, 0, 1, 2])
  196. >>> target = torch.tensor([0, 0, 1, 1])
  197. >>> calculate_pair_cluster_confusion_matrix(preds, target)
  198. tensor([[8, 2],
  199. [0, 2]])
  200. """
  201. if preds is None and target is None and contingency is None:
  202. raise ValueError("Must provide either `preds` and `target` or `contingency`.")
  203. if preds is not None and target is not None and contingency is not None:
  204. raise ValueError("Must provide either `preds` and `target` or `contingency`, not both.")
  205. if preds is not None and target is not None:
  206. contingency = calculate_contingency_matrix(preds, target)
  207. if contingency is None:
  208. raise ValueError("Must provide `contingency` if `preds` and `target` are not provided.")
  209. num_samples = contingency.sum()
  210. sum_c = contingency.sum(dim=1)
  211. sum_k = contingency.sum(dim=0)
  212. sum_squared = (contingency**2).sum()
  213. pair_matrix = torch.zeros(2, 2, dtype=contingency.dtype, device=contingency.device)
  214. pair_matrix[1, 1] = sum_squared - num_samples
  215. pair_matrix[1, 0] = (contingency * sum_k).sum() - sum_squared
  216. pair_matrix[0, 1] = (contingency.T * sum_c).sum() - sum_squared
  217. pair_matrix[0, 0] = num_samples**2 - pair_matrix[0, 1] - pair_matrix[1, 0] - sum_squared
  218. return pair_matrix