auroc.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. from torch import Tensor, tensor
  16. from torchmetrics.functional.classification.auroc import binary_auroc
  17. from torchmetrics.utilities.checks import _check_retrieval_functional_inputs
  18. def retrieval_auroc(
  19. preds: Tensor, target: Tensor, top_k: Optional[int] = None, max_fpr: Optional[float] = None
  20. ) -> Tensor:
  21. """Compute area under the receiver operating characteristic curve (AUROC) for information retrieval.
  22. ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``,
  23. ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``,
  24. otherwise an error is raised.
  25. Args:
  26. preds: estimated probabilities of each document to be relevant.
  27. target: ground truth about each document being relevant or not.
  28. top_k: consider only the top k elements (default: ``None``, which considers them all)
  29. max_fpr: If not ``None``, calculates standardized partial AUC over the range ``[0, max_fpr]``.
  30. Return:
  31. a single-value tensor with the auroc value of the predictions ``preds`` w.r.t. the labels ``target``.
  32. Raises:
  33. ValueError:
  34. If ``top_k`` is not ``None`` or an integer larger than 0.
  35. Example:
  36. >>> from torchmetrics.functional.retrieval import retrieval_auroc
  37. >>> preds = tensor([0.2, 0.3, 0.5])
  38. >>> target = tensor([True, False, True])
  39. >>> retrieval_auroc(preds, target)
  40. tensor(0.5000)
  41. """
  42. preds, target = _check_retrieval_functional_inputs(preds, target)
  43. top_k = top_k or preds.shape[-1]
  44. if not (isinstance(top_k, int) and top_k > 0):
  45. raise ValueError("`top_k` has to be a positive integer or None")
  46. top_k_idx = preds.topk(min(top_k, preds.shape[-1]), sorted=True, dim=-1)[1]
  47. target = target[top_k_idx]
  48. if (0 not in target) or (1 not in target):
  49. return tensor(0.0, device=preds.device, dtype=preds.dtype)
  50. preds = preds[top_k_idx]
  51. return binary_auroc(preds, target.int(), max_fpr=max_fpr)