fall_out.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. import torch
  16. from torch import Tensor, tensor
  17. from torchmetrics.utilities.checks import _check_retrieval_functional_inputs
  18. def retrieval_fall_out(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor:
  19. """Compute the Fall-out for information retrieval, as explained in `IR Fall-out`_.
  20. Fall-out is the fraction of non-relevant documents retrieved among all the non-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 Fall-out@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 fall-out (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_fall_out
  35. >>> preds = tensor([0.2, 0.3, 0.5])
  36. >>> target = tensor([True, False, True])
  37. >>> retrieval_fall_out(preds, target, top_k=2)
  38. tensor(1.)
  39. """
  40. preds, target = _check_retrieval_functional_inputs(preds, target)
  41. top_k = preds.shape[-1] if top_k is None else top_k
  42. if not (isinstance(top_k, int) and top_k > 0):
  43. raise ValueError("`top_k` has to be a positive integer or None")
  44. target = 1 - target # we want to compute the probability of getting a non-relevant doc among all non-relevant docs
  45. if not target.sum():
  46. return tensor(0.0, device=preds.device)
  47. relevant = target[torch.argsort(preds, dim=-1, descending=True)][:top_k].sum().float()
  48. return relevant / target.sum()