ndcg.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 _tie_average_dcg(target: Tensor, preds: Tensor, discount_cumsum: Tensor) -> Tensor:
  19. """Translated version of sklearns `_tie_average_dcg` function.
  20. Args:
  21. target: ground truth about each document relevance.
  22. preds: estimated probabilities of each document to be relevant.
  23. discount_cumsum: cumulative sum of the discount.
  24. Returns:
  25. The cumulative gain of the tied elements.
  26. """
  27. _, inv, counts = torch.unique(-preds, return_inverse=True, return_counts=True)
  28. ranked = torch.zeros_like(counts, dtype=torch.float32)
  29. ranked.scatter_add_(0, inv, target.to(dtype=ranked.dtype))
  30. ranked = ranked / counts
  31. groups = counts.cumsum(dim=0) - 1
  32. discount_sums = torch.zeros_like(counts, dtype=torch.float32)
  33. discount_sums[0] = discount_cumsum[groups[0]]
  34. discount_sums[1:] = discount_cumsum[groups].diff()
  35. return (ranked * discount_sums).sum()
  36. def _dcg_sample_scores(target: Tensor, preds: Tensor, top_k: int, ignore_ties: bool) -> Tensor:
  37. """Translated version of sklearns `_dcg_sample_scores` function.
  38. Args:
  39. target: ground truth about each document relevance.
  40. preds: estimated probabilities of each document to be relevant.
  41. top_k: consider only the top k elements
  42. ignore_ties: If True, ties are ignored. If False, ties are averaged.
  43. Returns:
  44. The cumulative gain
  45. """
  46. discount = 1.0 / (torch.log2(torch.arange(target.shape[-1], device=target.device) + 2.0))
  47. discount[top_k:] = 0.0
  48. if ignore_ties:
  49. ranking = preds.argsort(descending=True)
  50. ranked = target[ranking]
  51. cumulative_gain = (discount * ranked).sum()
  52. else:
  53. discount_cumsum = discount.cumsum(dim=-1)
  54. cumulative_gain = _tie_average_dcg(target, preds, discount_cumsum)
  55. return cumulative_gain
  56. def retrieval_normalized_dcg(preds: Tensor, target: Tensor, top_k: Optional[int] = None) -> Tensor:
  57. """Compute `Normalized Discounted Cumulative Gain`_ (for information retrieval).
  58. ``preds`` and ``target`` should be of the same shape and live on the same device.
  59. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``,
  60. otherwise an error is raised.
  61. Args:
  62. preds: estimated probabilities of each document to be relevant.
  63. target: ground truth about each document relevance.
  64. top_k: consider only the top k elements (default: ``None``, which considers them all)
  65. Return:
  66. A single-value tensor with the nDCG of the predictions ``preds`` w.r.t. the labels ``target``.
  67. Raises:
  68. ValueError:
  69. If ``top_k`` parameter is not `None` or an integer larger than 0
  70. Example:
  71. >>> from torchmetrics.functional.retrieval import retrieval_normalized_dcg
  72. >>> preds = torch.tensor([.1, .2, .3, 4, 70])
  73. >>> target = torch.tensor([10, 0, 0, 1, 5])
  74. >>> retrieval_normalized_dcg(preds, target)
  75. tensor(0.6957)
  76. """
  77. preds, target = _check_retrieval_functional_inputs(preds, target, allow_non_binary_target=True)
  78. top_k = preds.shape[-1] if top_k is None else top_k
  79. if not (isinstance(top_k, int) and top_k > 0):
  80. raise ValueError("`top_k` has to be a positive integer or None")
  81. gain = _dcg_sample_scores(target, preds, top_k, ignore_ties=False)
  82. normalized_gain = _dcg_sample_scores(target, target, top_k, ignore_ties=True)
  83. # filter undefined scores
  84. all_irrelevant = normalized_gain == 0
  85. gain[all_irrelevant] = 0
  86. gain[~all_irrelevant] /= normalized_gain[~all_irrelevant]
  87. return gain.mean()