r_precision.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import torch
  15. from torch import Tensor, tensor
  16. from torchmetrics.utilities.checks import _check_retrieval_functional_inputs
  17. def retrieval_r_precision(preds: Tensor, target: Tensor) -> Tensor:
  18. """Compute the r-precision metric for information retrieval.
  19. R-Precision is the fraction of relevant documents among all the top ``k`` retrieved documents where ``k`` is equal
  20. to the total number of relevant documents.
  21. ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``,
  22. ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``,
  23. otherwise an error is raised. If you want to measure Precision@K, ``top_k`` must be a positive integer.
  24. Args:
  25. preds: estimated probabilities of each document to be relevant.
  26. target: ground truth about each document being relevant or not.
  27. Returns:
  28. A single-value tensor with the r-precision of the predictions ``preds`` w.r.t. the labels ``target``.
  29. Example:
  30. >>> preds = tensor([0.2, 0.3, 0.5])
  31. >>> target = tensor([True, False, True])
  32. >>> retrieval_r_precision(preds, target)
  33. tensor(0.5000)
  34. """
  35. preds, target = _check_retrieval_functional_inputs(preds, target)
  36. relevant_number = target.sum()
  37. if not relevant_number:
  38. return tensor(0.0, device=preds.device)
  39. relevant = target[torch.argsort(preds, dim=-1, descending=True)][:relevant_number].sum().float()
  40. return relevant / relevant_number