ranking.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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
  15. import torch
  16. from torch import Tensor
  17. from torchmetrics.functional.classification.confusion_matrix import (
  18. _multilabel_confusion_matrix_arg_validation,
  19. _multilabel_confusion_matrix_format,
  20. _multilabel_confusion_matrix_tensor_validation,
  21. )
  22. from torchmetrics.utilities.data import _cumsum
  23. def _rank_data(x: Tensor) -> Tensor:
  24. """Rank data based on values."""
  25. # torch.unique does not support input that requires grad
  26. with torch.no_grad():
  27. _, inverse, counts = torch.unique(x, sorted=True, return_inverse=True, return_counts=True)
  28. ranks = _cumsum(counts, dim=0)
  29. return ranks[inverse]
  30. def _ranking_reduce(score: Tensor, num_elements: int) -> Tensor:
  31. return score / num_elements
  32. def _multilabel_ranking_tensor_validation(
  33. preds: Tensor, target: Tensor, num_labels: int, ignore_index: Optional[int] = None
  34. ) -> None:
  35. _multilabel_confusion_matrix_tensor_validation(preds, target, num_labels, ignore_index)
  36. if not preds.is_floating_point():
  37. raise ValueError(f"Expected preds tensor to be floating point, but received input with dtype {preds.dtype}")
  38. def _multilabel_coverage_error_update(preds: Tensor, target: Tensor) -> tuple[Tensor, int]:
  39. """Accumulate state for coverage error."""
  40. offset = torch.zeros_like(preds)
  41. offset[target == 0] = preds.min().abs() + 10 # Any number >1 works
  42. preds_mod = preds + offset
  43. preds_min = preds_mod.min(dim=1)[0]
  44. coverage = (preds >= preds_min[:, None]).sum(dim=1).to(torch.float32)
  45. return coverage.sum(), coverage.numel()
  46. def multilabel_coverage_error(
  47. preds: Tensor,
  48. target: Tensor,
  49. num_labels: int,
  50. ignore_index: Optional[int] = None,
  51. validate_args: bool = True,
  52. ) -> Tensor:
  53. """Compute multilabel coverage error [1].
  54. The score measure how far we need to go through the ranked scores to cover all true labels. The best value is equal
  55. to the average number of labels in the target tensor per sample.
  56. Accepts the following input tensors:
  57. - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
  58. observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  59. sigmoid per element.
  60. - ``target`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
  61. only contain {0,1} values (except if `ignore_index` is specified).
  62. Additional dimension ``...`` will be flattened into the batch dimension.
  63. Args:
  64. preds: Tensor with predictions
  65. target: Tensor with true labels
  66. num_labels: Integer specifying the number of labels
  67. ignore_index:
  68. Specifies a target value that is ignored and does not contribute to the metric calculation
  69. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  70. Set to ``False`` for faster computations.
  71. Example:
  72. >>> from torch import rand, randint
  73. >>> from torchmetrics.functional.classification import multilabel_coverage_error
  74. >>> preds = rand(10, 5)
  75. >>> target = randint(2, (10, 5))
  76. >>> multilabel_coverage_error(preds, target, num_labels=5)
  77. tensor(3.9000)
  78. References:
  79. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and
  80. knowledge discovery handbook (pp. 667-685). Springer US.
  81. """
  82. if validate_args:
  83. _multilabel_confusion_matrix_arg_validation(num_labels, threshold=0.0, ignore_index=ignore_index)
  84. _multilabel_ranking_tensor_validation(preds, target, num_labels, ignore_index)
  85. preds, target = _multilabel_confusion_matrix_format(
  86. preds, target, num_labels, threshold=0.0, ignore_index=ignore_index, should_threshold=False
  87. )
  88. coverage, total = _multilabel_coverage_error_update(preds, target)
  89. return _ranking_reduce(coverage, total)
  90. def _multilabel_ranking_average_precision_update(preds: Tensor, target: Tensor) -> tuple[Tensor, int]:
  91. """Accumulate state for label ranking average precision."""
  92. # Invert so that the highest score receives rank 1
  93. neg_preds = -preds
  94. score = torch.tensor(0.0, device=neg_preds.device)
  95. num_preds, num_labels = neg_preds.shape
  96. for i in range(num_preds):
  97. relevant = target[i] == 1
  98. ranking = _rank_data(neg_preds[i][relevant]).float()
  99. if len(ranking) > 0 and len(ranking) < num_labels:
  100. rank = _rank_data(neg_preds[i])[relevant].float()
  101. score_idx = (ranking / rank).mean()
  102. else:
  103. score_idx = torch.ones_like(score)
  104. score += score_idx
  105. return score, num_preds
  106. def multilabel_ranking_average_precision(
  107. preds: Tensor,
  108. target: Tensor,
  109. num_labels: int,
  110. ignore_index: Optional[int] = None,
  111. validate_args: bool = True,
  112. ) -> Tensor:
  113. """Compute label ranking average precision score for multilabel data [1].
  114. The score is the average over each ground truth label assigned to each sample of the ratio of true vs. total labels
  115. with lower score. Best score is 1.
  116. Accepts the following input tensors:
  117. - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
  118. observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  119. sigmoid per element.
  120. - ``target`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
  121. only contain {0,1} values (except if `ignore_index` is specified).
  122. Additional dimension ``...`` will be flattened into the batch dimension.
  123. Args:
  124. preds: Tensor with predictions
  125. target: Tensor with true labels
  126. num_labels: Integer specifying the number of labels
  127. ignore_index:
  128. Specifies a target value that is ignored and does not contribute to the metric calculation
  129. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  130. Set to ``False`` for faster computations.
  131. Example:
  132. >>> from torch import rand, randint
  133. >>> from torchmetrics.functional.classification import multilabel_ranking_average_precision
  134. >>> preds = rand(10, 5)
  135. >>> target = randint(2, (10, 5))
  136. >>> multilabel_ranking_average_precision(preds, target, num_labels=5)
  137. tensor(0.7744)
  138. References:
  139. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and
  140. knowledge discovery handbook (pp. 667-685). Springer US.
  141. """
  142. if validate_args:
  143. _multilabel_confusion_matrix_arg_validation(num_labels, threshold=0.0, ignore_index=ignore_index)
  144. _multilabel_ranking_tensor_validation(preds, target, num_labels, ignore_index)
  145. preds, target = _multilabel_confusion_matrix_format(
  146. preds, target, num_labels, threshold=0.0, ignore_index=ignore_index, should_threshold=False
  147. )
  148. score, num_elements = _multilabel_ranking_average_precision_update(preds, target)
  149. return _ranking_reduce(score, num_elements)
  150. def _multilabel_ranking_loss_update(preds: Tensor, target: Tensor) -> tuple[Tensor, int]:
  151. """Accumulate state for label ranking loss.
  152. Args:
  153. preds: tensor with predictions
  154. target: tensor with ground truth labels
  155. sample_weight: optional tensor with weight for each sample
  156. """
  157. num_preds, num_labels = preds.shape
  158. relevant = target == 1
  159. num_relevant = relevant.sum(dim=1)
  160. # Ignore instances where number of true labels is 0 or n_labels
  161. mask = (num_relevant > 0) & (num_relevant < num_labels)
  162. preds = preds[mask]
  163. relevant = relevant[mask]
  164. num_relevant = num_relevant[mask]
  165. # Nothing is relevant
  166. if len(preds) == 0:
  167. return torch.tensor(0.0, device=preds.device), 1
  168. inverse = preds.argsort(dim=1).argsort(dim=1)
  169. per_label_loss = ((num_labels - inverse) * relevant).to(torch.float32)
  170. correction = 0.5 * num_relevant * (num_relevant + 1)
  171. denom = num_relevant * (num_labels - num_relevant)
  172. loss = (per_label_loss.sum(dim=1) - correction) / denom
  173. return loss.sum(), num_preds
  174. def multilabel_ranking_loss(
  175. preds: Tensor,
  176. target: Tensor,
  177. num_labels: int,
  178. ignore_index: Optional[int] = None,
  179. validate_args: bool = True,
  180. ) -> Tensor:
  181. """Compute the label ranking loss for multilabel data [1].
  182. The score is corresponds to the average number of label pairs that are incorrectly ordered given some predictions
  183. weighted by the size of the label set and the number of labels not in the label set. The best score is 0.
  184. Accepts the following input tensors:
  185. - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
  186. observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  187. sigmoid per element.
  188. - ``target`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
  189. only contain {0,1} values (except if `ignore_index` is specified).
  190. Additional dimension ``...`` will be flattened into the batch dimension.
  191. Args:
  192. preds: Tensor with predictions
  193. target: Tensor with true labels
  194. num_labels: Integer specifying the number of labels
  195. ignore_index:
  196. Specifies a target value that is ignored and does not contribute to the metric calculation
  197. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  198. Set to ``False`` for faster computations.
  199. Example:
  200. >>> from torch import rand, randint
  201. >>> from torchmetrics.functional.classification import multilabel_ranking_loss
  202. >>> preds = rand(10, 5)
  203. >>> target = randint(2, (10, 5))
  204. >>> multilabel_ranking_loss(preds, target, num_labels=5)
  205. tensor(0.4167)
  206. References:
  207. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). Mining multi-label data. In Data mining and
  208. knowledge discovery handbook (pp. 667-685). Springer US.
  209. """
  210. if validate_args:
  211. _multilabel_confusion_matrix_arg_validation(num_labels, threshold=0.0, ignore_index=ignore_index)
  212. _multilabel_ranking_tensor_validation(preds, target, num_labels, ignore_index)
  213. preds, target = _multilabel_confusion_matrix_format(
  214. preds, target, num_labels, threshold=0.0, ignore_index=ignore_index, should_threshold=False
  215. )
  216. loss, num_elements = _multilabel_ranking_loss_update(preds, target)
  217. return _ranking_reduce(loss, num_elements)