average_precision.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 List, Optional, Union
  15. import torch
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.classification.precision_recall_curve import (
  19. _binary_precision_recall_curve_arg_validation,
  20. _binary_precision_recall_curve_compute,
  21. _binary_precision_recall_curve_format,
  22. _binary_precision_recall_curve_tensor_validation,
  23. _binary_precision_recall_curve_update,
  24. _multiclass_precision_recall_curve_arg_validation,
  25. _multiclass_precision_recall_curve_compute,
  26. _multiclass_precision_recall_curve_format,
  27. _multiclass_precision_recall_curve_tensor_validation,
  28. _multiclass_precision_recall_curve_update,
  29. _multilabel_precision_recall_curve_arg_validation,
  30. _multilabel_precision_recall_curve_compute,
  31. _multilabel_precision_recall_curve_format,
  32. _multilabel_precision_recall_curve_tensor_validation,
  33. _multilabel_precision_recall_curve_update,
  34. )
  35. from torchmetrics.utilities.compute import _safe_divide
  36. from torchmetrics.utilities.data import _bincount
  37. from torchmetrics.utilities.enums import ClassificationTask
  38. from torchmetrics.utilities.prints import rank_zero_warn
  39. def _reduce_average_precision(
  40. precision: Union[Tensor, List[Tensor]],
  41. recall: Union[Tensor, List[Tensor]],
  42. average: Optional[Literal["macro", "weighted", "none"]] = "macro",
  43. weights: Optional[Tensor] = None,
  44. ) -> Tensor:
  45. """Reduce multiple average precision score into one number."""
  46. if isinstance(precision, Tensor) and isinstance(recall, Tensor):
  47. precision = torch.where(torch.isnan(precision), torch.zeros_like(precision), precision)
  48. recall = torch.where(torch.isnan(recall), torch.zeros_like(recall), recall)
  49. res = -torch.sum((recall[:, 1:] - recall[:, :-1]) * precision[:, :-1], 1)
  50. else:
  51. res = torch.stack([-torch.sum((r[1:] - r[:-1]) * p[:-1]) for p, r in zip(precision, recall)])
  52. if average is None or average == "none":
  53. return res
  54. if torch.isnan(res).any():
  55. rank_zero_warn(
  56. f"Average precision score for one or more classes was `nan`. Ignoring these classes in {average}-average",
  57. UserWarning,
  58. )
  59. idx = ~torch.isnan(res)
  60. if average == "macro":
  61. return res[idx].mean()
  62. if average == "weighted" and weights is not None:
  63. weights = _safe_divide(weights[idx], weights[idx].sum())
  64. return (res[idx] * weights).sum()
  65. raise ValueError("Received an incompatible combinations of inputs to make reduction.")
  66. def _binary_average_precision_compute(
  67. state: Union[Tensor, tuple[Tensor, Tensor]],
  68. thresholds: Optional[Tensor],
  69. ) -> Tensor:
  70. precision, recall, _ = _binary_precision_recall_curve_compute(state, thresholds)
  71. precision = torch.where(torch.isnan(precision), torch.zeros_like(precision), precision)
  72. recall = torch.where(torch.isnan(recall), torch.zeros_like(recall), recall)
  73. return -torch.sum((recall[1:] - recall[:-1]) * precision[:-1])
  74. def binary_average_precision(
  75. preds: Tensor,
  76. target: Tensor,
  77. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  78. ignore_index: Optional[int] = None,
  79. validate_args: bool = True,
  80. ) -> Tensor:
  81. r"""Compute the average precision (AP) score for binary tasks.
  82. The AP score summarizes a precision-recall curve as an weighted mean of precisions at each threshold, with the
  83. difference in recall from the previous threshold as weight:
  84. .. math::
  85. AP = \sum{n} (R_n - R_{n-1}) P_n
  86. where :math:`P_n, R_n` is the respective precision and recall at threshold index :math:`n`. This value is
  87. equivalent to the area under the precision-recall curve (AUPRC).
  88. Accepts the following input tensors:
  89. - ``preds`` (float tensor): ``(N, ...)``. Preds should be a tensor containing probabilities or logits for each
  90. observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  91. sigmoid per element.
  92. - ``target`` (int tensor): ``(N, ...)``. Target should be a tensor containing ground truth labels, and therefore
  93. only contain {0,1} values (except if `ignore_index` is specified). The value 1 always encodes the positive class.
  94. Additional dimension ``...`` will be flattened into the batch dimension.
  95. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  96. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  97. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  98. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  99. size :math:`\mathcal{O}(n_{thresholds})` (constant memory).
  100. Args:
  101. preds: Tensor with predictions
  102. target: Tensor with true labels
  103. thresholds:
  104. Can be one of:
  105. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  106. all the data. Most accurate but also most memory consuming approach.
  107. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  108. 0 to 1 as bins for the calculation.
  109. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  110. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  111. bins for the calculation.
  112. ignore_index:
  113. Specifies a target value that is ignored and does not contribute to the metric calculation
  114. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  115. Set to ``False`` for faster computations.
  116. Returns:
  117. A single scalar with the average precision score
  118. Example:
  119. >>> from torchmetrics.functional.classification import binary_average_precision
  120. >>> preds = torch.tensor([0, 0.5, 0.7, 0.8])
  121. >>> target = torch.tensor([0, 1, 1, 0])
  122. >>> binary_average_precision(preds, target, thresholds=None)
  123. tensor(0.5833)
  124. >>> binary_average_precision(preds, target, thresholds=5)
  125. tensor(0.6667)
  126. """
  127. if validate_args:
  128. _binary_precision_recall_curve_arg_validation(thresholds, ignore_index)
  129. _binary_precision_recall_curve_tensor_validation(preds, target, ignore_index)
  130. preds, target, thresholds = _binary_precision_recall_curve_format(preds, target, thresholds, ignore_index)
  131. state = _binary_precision_recall_curve_update(preds, target, thresholds)
  132. return _binary_average_precision_compute(state, thresholds)
  133. def _multiclass_average_precision_arg_validation(
  134. num_classes: int,
  135. average: Optional[Literal["macro", "weighted", "none"]] = "macro",
  136. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  137. ignore_index: Optional[int] = None,
  138. ) -> None:
  139. _multiclass_precision_recall_curve_arg_validation(num_classes, thresholds, ignore_index)
  140. allowed_average = ("macro", "weighted", "none", None)
  141. if average not in allowed_average:
  142. raise ValueError(f"Expected argument `average` to be one of {allowed_average} but got {average}")
  143. def _multiclass_average_precision_compute(
  144. state: Union[Tensor, tuple[Tensor, Tensor]],
  145. num_classes: int,
  146. average: Optional[Literal["macro", "weighted", "none"]] = "macro",
  147. thresholds: Optional[Tensor] = None,
  148. ) -> Tensor:
  149. precision, recall, _ = _multiclass_precision_recall_curve_compute(state, num_classes, thresholds)
  150. return _reduce_average_precision(
  151. precision,
  152. recall,
  153. average,
  154. weights=_bincount(state[1], minlength=num_classes).float() if thresholds is None else state[0][:, 1, :].sum(-1),
  155. )
  156. def multiclass_average_precision(
  157. preds: Tensor,
  158. target: Tensor,
  159. num_classes: int,
  160. average: Optional[Literal["macro", "weighted", "none"]] = "macro",
  161. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  162. ignore_index: Optional[int] = None,
  163. validate_args: bool = True,
  164. ) -> Tensor:
  165. r"""Compute the average precision (AP) score for multiclass tasks.
  166. The AP score summarizes a precision-recall curve as an weighted mean of precisions at each threshold, with the
  167. difference in recall from the previous threshold as weight:
  168. .. math::
  169. AP = \sum{n} (R_n - R_{n-1}) P_n
  170. where :math:`P_n, R_n` is the respective precision and recall at threshold index :math:`n`. This value is
  171. equivalent to the area under the precision-recall curve (AUPRC).
  172. Accepts the following input tensors:
  173. - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
  174. observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  175. softmax per sample.
  176. - ``target`` (int tensor): ``(N, ...)``. Target should be a tensor containing ground truth labels, and therefore
  177. only contain values in the [0, n_classes-1] range (except if `ignore_index` is specified).
  178. Additional dimension ``...`` will be flattened into the batch dimension.
  179. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  180. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  181. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  182. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  183. size :math:`\mathcal{O}(n_{thresholds} \times n_{classes})` (constant memory).
  184. Args:
  185. preds: Tensor with predictions
  186. target: Tensor with true labels
  187. num_classes: Integer specifying the number of classes
  188. average:
  189. Defines the reduction that is applied over classes. Should be one of the following:
  190. - ``macro``: Calculate score for each class and average them
  191. - ``weighted``: calculates score for each class and computes weighted average using their support
  192. - ``"none"`` or ``None``: calculates score for each class and applies no reduction
  193. thresholds:
  194. Can be one of:
  195. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  196. all the data. Most accurate but also most memory consuming approach.
  197. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  198. 0 to 1 as bins for the calculation.
  199. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  200. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  201. bins for the calculation.
  202. ignore_index:
  203. Specifies a target value that is ignored and does not contribute to the metric calculation
  204. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  205. Set to ``False`` for faster computations.
  206. Returns:
  207. If `average=None|"none"` then a 1d tensor of shape (n_classes, ) will be returned with AP score per class.
  208. If `average="macro"|"weighted"` then a single scalar is returned.
  209. Example:
  210. >>> from torchmetrics.functional.classification import multiclass_average_precision
  211. >>> preds = torch.tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
  212. ... [0.05, 0.75, 0.05, 0.05, 0.05],
  213. ... [0.05, 0.05, 0.75, 0.05, 0.05],
  214. ... [0.05, 0.05, 0.05, 0.75, 0.05]])
  215. >>> target = torch.tensor([0, 1, 3, 2])
  216. >>> multiclass_average_precision(preds, target, num_classes=5, average="macro", thresholds=None)
  217. tensor(0.6250)
  218. >>> multiclass_average_precision(preds, target, num_classes=5, average=None, thresholds=None)
  219. tensor([1.0000, 1.0000, 0.2500, 0.2500, nan])
  220. >>> multiclass_average_precision(preds, target, num_classes=5, average="macro", thresholds=5)
  221. tensor(0.5000)
  222. >>> multiclass_average_precision(preds, target, num_classes=5, average=None, thresholds=5)
  223. tensor([1.0000, 1.0000, 0.2500, 0.2500, -0.0000])
  224. """
  225. if validate_args:
  226. _multiclass_average_precision_arg_validation(num_classes, average, thresholds, ignore_index)
  227. _multiclass_precision_recall_curve_tensor_validation(preds, target, num_classes, ignore_index)
  228. preds, target, thresholds = _multiclass_precision_recall_curve_format(
  229. preds, target, num_classes, thresholds, ignore_index
  230. )
  231. state = _multiclass_precision_recall_curve_update(preds, target, num_classes, thresholds)
  232. return _multiclass_average_precision_compute(state, num_classes, average, thresholds)
  233. def _multilabel_average_precision_arg_validation(
  234. num_labels: int,
  235. average: Optional[Literal["micro", "macro", "weighted", "none"]],
  236. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  237. ignore_index: Optional[int] = None,
  238. ) -> None:
  239. _multilabel_precision_recall_curve_arg_validation(num_labels, thresholds, ignore_index)
  240. allowed_average = ("micro", "macro", "weighted", "none", None)
  241. if average not in allowed_average:
  242. raise ValueError(f"Expected argument `average` to be one of {allowed_average} but got {average}")
  243. def _multilabel_average_precision_compute(
  244. state: Union[Tensor, tuple[Tensor, Tensor]],
  245. num_labels: int,
  246. average: Optional[Literal["micro", "macro", "weighted", "none"]],
  247. thresholds: Optional[Tensor],
  248. ignore_index: Optional[int] = None,
  249. ) -> Tensor:
  250. if average == "micro":
  251. if isinstance(state, Tensor) and thresholds is not None:
  252. state = state.sum(1)
  253. else:
  254. preds, target = state[0].flatten(), state[1].flatten()
  255. if ignore_index is not None:
  256. idx = target == ignore_index
  257. preds = preds[~idx]
  258. target = target[~idx]
  259. state = (preds, target)
  260. return _binary_average_precision_compute(state, thresholds)
  261. precision, recall, _ = _multilabel_precision_recall_curve_compute(state, num_labels, thresholds, ignore_index)
  262. return _reduce_average_precision(
  263. precision,
  264. recall,
  265. average,
  266. weights=(state[1] == 1).sum(dim=0).float() if thresholds is None else state[0][:, 1, :].sum(-1),
  267. )
  268. def multilabel_average_precision(
  269. preds: Tensor,
  270. target: Tensor,
  271. num_labels: int,
  272. average: Optional[Literal["micro", "macro", "weighted", "none"]] = "macro",
  273. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  274. ignore_index: Optional[int] = None,
  275. validate_args: bool = True,
  276. ) -> Tensor:
  277. r"""Compute the average precision (AP) score for multilabel tasks.
  278. The AP score summarizes a precision-recall curve as an weighted mean of precisions at each threshold, with the
  279. difference in recall from the previous threshold as weight:
  280. .. math::
  281. AP = \sum{n} (R_n - R_{n-1}) P_n
  282. where :math:`P_n, R_n` is the respective precision and recall at threshold index :math:`n`. This value is
  283. equivalent to the area under the precision-recall curve (AUPRC).
  284. Accepts the following input tensors:
  285. - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
  286. observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
  287. sigmoid per element.
  288. - ``target`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
  289. only contain {0,1} values (except if `ignore_index` is specified).
  290. Additional dimension ``...`` will be flattened into the batch dimension.
  291. The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
  292. that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
  293. non-binned version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
  294. argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
  295. size :math:`\mathcal{O}(n_{thresholds} \times n_{labels})` (constant memory).
  296. Args:
  297. preds: Tensor with predictions
  298. target: Tensor with true labels
  299. num_labels: Integer specifying the number of labels
  300. average:
  301. Defines the reduction that is applied over labels. Should be one of the following:
  302. - ``micro``: Sum score over all labels
  303. - ``macro``: Calculate score for each label and average them
  304. - ``weighted``: calculates score for each label and computes weighted average using their support
  305. - ``"none"`` or ``None``: calculates score for each label and applies no reduction
  306. thresholds:
  307. Can be one of:
  308. - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
  309. all the data. Most accurate but also most memory consuming approach.
  310. - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
  311. 0 to 1 as bins for the calculation.
  312. - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
  313. - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
  314. bins for the calculation.
  315. ignore_index:
  316. Specifies a target value that is ignored and does not contribute to the metric calculation
  317. validate_args: bool indicating if input arguments and tensors should be validated for correctness.
  318. Set to ``False`` for faster computations.
  319. Returns:
  320. If `average=None|"none"` then a 1d tensor of shape (n_classes, ) will be returned with AP score per class.
  321. If `average="micro|macro"|"weighted"` then a single scalar is returned.
  322. Example:
  323. >>> from torchmetrics.functional.classification import multilabel_average_precision
  324. >>> preds = torch.tensor([[0.75, 0.05, 0.35],
  325. ... [0.45, 0.75, 0.05],
  326. ... [0.05, 0.55, 0.75],
  327. ... [0.05, 0.65, 0.05]])
  328. >>> target = torch.tensor([[1, 0, 1],
  329. ... [0, 0, 0],
  330. ... [0, 1, 1],
  331. ... [1, 1, 1]])
  332. >>> multilabel_average_precision(preds, target, num_labels=3, average="macro", thresholds=None)
  333. tensor(0.7500)
  334. >>> multilabel_average_precision(preds, target, num_labels=3, average=None, thresholds=None)
  335. tensor([0.7500, 0.5833, 0.9167])
  336. >>> multilabel_average_precision(preds, target, num_labels=3, average="macro", thresholds=5)
  337. tensor(0.7778)
  338. >>> multilabel_average_precision(preds, target, num_labels=3, average=None, thresholds=5)
  339. tensor([0.7500, 0.6667, 0.9167])
  340. """
  341. if validate_args:
  342. _multilabel_average_precision_arg_validation(num_labels, average, thresholds, ignore_index)
  343. _multilabel_precision_recall_curve_tensor_validation(preds, target, num_labels, ignore_index)
  344. preds, target, thresholds = _multilabel_precision_recall_curve_format(
  345. preds, target, num_labels, thresholds, ignore_index
  346. )
  347. state = _multilabel_precision_recall_curve_update(preds, target, num_labels, thresholds)
  348. return _multilabel_average_precision_compute(state, num_labels, average, thresholds, ignore_index)
  349. def average_precision(
  350. preds: Tensor,
  351. target: Tensor,
  352. task: Literal["binary", "multiclass", "multilabel"],
  353. thresholds: Optional[Union[int, list[float], Tensor]] = None,
  354. num_classes: Optional[int] = None,
  355. num_labels: Optional[int] = None,
  356. average: Optional[Literal["macro", "weighted", "none"]] = "macro",
  357. ignore_index: Optional[int] = None,
  358. validate_args: bool = True,
  359. ) -> Optional[Tensor]:
  360. r"""Compute the average precision (AP) score.
  361. The AP score summarizes a precision-recall curve as an weighted mean of precisions at each threshold, with the
  362. difference in recall from the previous threshold as weight:
  363. .. math::
  364. AP = \sum{n} (R_n - R_{n-1}) P_n
  365. where :math:`P_n, R_n` is the respective precision and recall at threshold index :math:`n`. This value is
  366. equivalent to the area under the precision-recall curve (AUPRC).
  367. This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
  368. ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
  369. :func:`~torchmetrics.functional.classification.binary_average_precision`,
  370. :func:`~torchmetrics.functional.classification.multiclass_average_precision` and
  371. :func:`~torchmetrics.functional.classification.multilabel_average_precision`
  372. for the specific details of each argument influence and examples.
  373. Legacy Example:
  374. >>> from torchmetrics.functional.classification import average_precision
  375. >>> pred = torch.tensor([0.0, 1.0, 2.0, 3.0])
  376. >>> target = torch.tensor([0, 1, 1, 1])
  377. >>> average_precision(pred, target, task="binary")
  378. tensor(1.)
  379. >>> pred = torch.tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
  380. ... [0.05, 0.75, 0.05, 0.05, 0.05],
  381. ... [0.05, 0.05, 0.75, 0.05, 0.05],
  382. ... [0.05, 0.05, 0.05, 0.75, 0.05]])
  383. >>> target = torch.tensor([0, 1, 3, 2])
  384. >>> average_precision(pred, target, task="multiclass", num_classes=5, average=None)
  385. tensor([1.0000, 1.0000, 0.2500, 0.2500, nan])
  386. """
  387. task = ClassificationTask.from_str(task)
  388. if task == ClassificationTask.BINARY:
  389. return binary_average_precision(preds, target, thresholds, ignore_index, validate_args)
  390. if task == ClassificationTask.MULTICLASS:
  391. if not isinstance(num_classes, int):
  392. raise ValueError(f"`num_classes` is expected to be `int` but `{type(num_classes)} was passed.`")
  393. return multiclass_average_precision(
  394. preds, target, num_classes, average, thresholds, ignore_index, validate_args
  395. )
  396. if task == ClassificationTask.MULTILABEL:
  397. if not isinstance(num_labels, int):
  398. raise ValueError(f"`num_labels` is expected to be `int` but `{type(num_labels)} was passed.`")
  399. return multilabel_average_precision(preds, target, num_labels, average, thresholds, ignore_index, validate_args)
  400. return None