recall.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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_recall(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor:
  19. """Compute the recall metric for information retrieval.
  20. Recall is the fraction of relevant documents retrieved among all the 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 Recall@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. top_k: consider only the top k elements (default: `None`, which considers them all)
  28. Returns:
  29. A single-value tensor with the recall (at ``top_k``) of the predictions ``preds`` w.r.t. the labels ``target``.
  30. Raises:
  31. ValueError:
  32. If ``top_k`` parameter is not `None` or an integer larger than 0
  33. Example:
  34. >>> from torchmetrics.functional import retrieval_recall
  35. >>> preds = tensor([0.2, 0.3, 0.5])
  36. >>> target = tensor([True, False, True])
  37. >>> retrieval_recall(preds, target, top_k=2)
  38. tensor(0.5000)
  39. """
  40. preds, target = _check_retrieval_functional_inputs(preds, target)
  41. if top_k is None:
  42. top_k = preds.shape[-1]
  43. if not (isinstance(top_k, int) and top_k > 0):
  44. raise ValueError("`top_k` has to be a positive integer or None")
  45. if not target.sum():
  46. return tensor(0.0, device=preds.device)
  47. target_filtered = torch.where(preds > 0, target, torch.zeros_like(target))
  48. relevant = target_filtered[torch.argsort(preds, dim=-1, descending=True)][:top_k].sum().float()
  49. return relevant / target.sum()