hit_rate.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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
  17. from torchmetrics.utilities.checks import _check_retrieval_functional_inputs
  18. def retrieval_hit_rate(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor:
  19. """Compute the hit rate for information retrieval.
  20. The hit rate is 1.0 if there is at least one relevant document among all the top `k` retrieved 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 HitRate@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 hit rate (at ``top_k``) of the predictions ``preds`` w.r.t. the labels
  30. ``target``.
  31. Raises:
  32. ValueError:
  33. If ``top_k`` parameter is not `None` or an integer larger than 0
  34. Example:
  35. >>> from torch import tensor
  36. >>> preds = tensor([0.2, 0.3, 0.5])
  37. >>> target = tensor([True, False, True])
  38. >>> retrieval_hit_rate(preds, target, top_k=2)
  39. tensor(1.)
  40. """
  41. preds, target = _check_retrieval_functional_inputs(preds, target)
  42. if top_k is None:
  43. top_k = 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. relevant = target[torch.argsort(preds, dim=-1, descending=True)][:top_k].sum()
  47. return (relevant > 0).float()