average_precision.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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, tensor
  17. from torchmetrics.utilities.checks import _check_retrieval_functional_inputs
  18. def retrieval_average_precision(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor:
  19. """Compute average precision (for information retrieval), as explained in `IR Average precision`_.
  20. ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``,
  21. ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``,
  22. otherwise an error is raised.
  23. Args:
  24. preds: estimated probabilities of each document to be relevant.
  25. target: ground truth about each document being relevant or not.
  26. top_k: consider only the top k elements (default: ``None``, which considers them all)
  27. Return:
  28. a single-value tensor with the average precision (AP) of the predictions ``preds`` w.r.t. the labels ``target``.
  29. Raises:
  30. ValueError:
  31. If ``top_k`` is not ``None`` or an integer larger than 0.
  32. Example:
  33. >>> from torchmetrics.functional.retrieval import retrieval_average_precision
  34. >>> preds = tensor([0.2, 0.3, 0.5])
  35. >>> target = tensor([True, False, True])
  36. >>> retrieval_average_precision(preds, target)
  37. tensor(0.8333)
  38. """
  39. preds, target = _check_retrieval_functional_inputs(preds, target)
  40. top_k = top_k or preds.shape[-1]
  41. if not isinstance(top_k, int) and top_k <= 0:
  42. raise ValueError(f"Argument ``top_k`` has to be a positive integer or None, but got {top_k}.")
  43. target = torch.where(preds > 0, target, torch.zeros_like(target))
  44. target = target[preds.topk(min(top_k, preds.shape[-1]), sorted=True, dim=-1)[1]]
  45. if not target.sum():
  46. return tensor(0.0, device=preds.device)
  47. positions = torch.arange(1, len(target) + 1, device=target.device, dtype=torch.float32)[target > 0]
  48. return torch.div((torch.arange(len(positions), device=positions.device, dtype=torch.float32) + 1), positions).mean()