Sub topic 5
Rank-aware metrics: MRR, MAP, and nDCG
This chapter assumes you can read Python, know precision and recall from classification, and have already met precision@k, recall@k, and hit rate. It also assumes you have an evaluation set where each question has labelled relevant documents.
Why set-based metrics are not enough
Precision@k and recall@k treat the top k results as an unordered set. A retriever that returns the one relevant chunk at rank 1 and a retriever that returns it at rank k get the same score. In a RAG system that difference matters for three reasons.
- Prompts are often truncated. If you pass only the top 3 chunks to the generator, a relevant chunk at rank 4 is lost.
- Language models can pay less attention to material in the middle of a long context, so position can affect the answer.
- A reranker's whole job is to change the order. A set-based metric at a fixed k cannot show that it helped.
Rank-aware metrics reward putting relevant documents early. This chapter covers reciprocal rank and MRR, average precision and MAP, and nDCG.
Reciprocal rank and MRR
Reciprocal rank (RR) for one question is 1 divided by the rank of the first relevant document. It is 0 if no relevant document is retrieved. Mean reciprocal rank (MRR) is the average of RR over all questions.
| First relevant rank | Reciprocal rank |
|---|---|
| 1 | 1.0 |
| 2 | 0.5 |
| 3 | 0.333 |
| 10 | 0.1 |
| not retrieved | 0 |
MRR fits questions that need one good passage, such as a factual lookup. It ignores everything after the first relevant hit. If a question has three relevant documents, MRR does not care whether the other two are at rank 2 or rank 50.
The scale is also steep at the top. Moving the first hit from rank 2 to rank 1 adds 0.5. Moving it from rank 10 to rank 5 adds 0.1. This is useful if the top slot matters most, and misleading if you pass 10 chunks to the generator and position within them hardly matters.
Average precision and MAP
Average precision (AP) looks at every relevant document, not just the first. For each relevant document found in the ranking, compute precision at that rank. Then sum these values and divide by the total number of relevant documents for the question. Mean average precision (MAP) is the mean of AP over questions.
Take the ranking d7, d2, d9, d1 with relevant set {d2, d1, d5}.
d2is at rank 2. Precision@2 is 1/2 = 0.5.d1is at rank 4. Precision@4 is 2/4 = 0.5.d5is never retrieved. It contributes 0.
AP = (0.5 + 0.5 + 0) / 3 = 0.333.
Dividing by the total number of relevant documents, not the number found, is what makes AP penalise missed documents. A common bug is dividing by the number found, which inflates the score for retrievers that return few relevant items.
def average_precision(retrieved_ids, relevant_ids, k=None):
if not relevant_ids:
return None # undefined: no labelled relevant documents
ranking = retrieved_ids if k is None else retrieved_ids[:k]
hits = 0
total = 0.0
for rank, d in enumerate(ranking, start=1):
if d in relevant_ids:
hits += 1
total += hits / rank
return total / len(relevant_ids)
retrieved = ["d7", "d2", "d9", "d1"]
relevant = {"d2", "d1", "d5"}
print(round(average_precision(retrieved, relevant), 3)) # 0.333MAP uses binary relevance (relevant or not). It suits questions with several relevant passages where you want all of them near the top, such as questions that need evidence from multiple chunks.
nDCG: graded relevance and position discount
Often relevance is not yes or no. A chunk that contains the full answer is better than one that gives partial background. nDCG (normalised discounted cumulative gain) handles this with graded labels such as 0, 1, 2, 3.
The metric has three steps.
- Gain. Each retrieved document contributes its grade.
- Discount. The gain at rank i (starting from 1) is divided by log2(i + 1). Rank 1 is divided by 1, rank 2 by about 1.58, rank 4 by about 2.32. Lower positions count for less.
- Normalise. Divide the DCG (the discounted sum) by the DCG of the ideal ordering, which sorts all labelled documents by grade. The result is between 0 and 1.
The code below reuses the functions from the spine and adds the reciprocal rank check on the same ranking.
import math
def reciprocal_rank(retrieved_ids, relevant_ids):
for rank, d in enumerate(retrieved_ids, start=1):
if d in relevant_ids:
return 1.0 / rank
return 0.0
def dcg(gains):
return sum(g / math.log2(i + 2) for i, g in enumerate(gains))
def ndcg_at_k(retrieved_ids, graded_relevance, k):
# graded_relevance maps document id -> gain (for example 0, 1, 2, 3)
gains = [graded_relevance.get(d, 0) for d in retrieved_ids[:k]]
ideal = sorted(graded_relevance.values(), reverse=True)[:k]
ideal_dcg = dcg(ideal)
return dcg(gains) / ideal_dcg if ideal_dcg > 0 else 0.0
retrieved = ["d7", "d2", "d9", "d1"]
grades = {"d2": 3, "d1": 2, "d5": 1}
print(reciprocal_rank(retrieved, set(grades))) # 0.5
print(round(ndcg_at_k(retrieved, grades, 4), 3)) # 0.572Work through the numbers. The actual gains are [0, 3, 0, 2]. DCG = 0 + 3/1.585 + 0 + 2/2.322 = 1.893 + 0.861 = 2.754. The ideal gains are [3, 2, 1]. Ideal DCG = 3/1 + 2/1.585 + 1/2 = 3 + 1.262 + 0.5 = 4.762. So nDCG@4 = 2.754 / 4.762 = 0.578.
Check the printed value against this hand calculation when you run it. The exact output depends on floating point, and you should see a value close to 0.578.
The code uses log2(i + 2) because enumerate starts at 0. Index 0 is rank 1, and rank 1 needs log2(2) = 1.
Gain variants and gotchas
- Some libraries use the exponential gain
2^grade - 1instead of the raw grade. This stresses highly relevant documents more. Scores from two libraries are not comparable unless both use the same form. - The ideal ranking must come from all labelled documents for the question, not only those your system retrieved. If you build the ideal list from retrieved items, nDCG is inflated.
- Unlabelled documents are scored as grade 0. If your labels are incomplete, a good retriever that finds an unlabelled relevant chunk is punished. See the chapter on building evaluation sets for how to reduce this.
- A question with no relevant documents has an ideal DCG of 0. The code returns 0.0, but you should usually exclude such questions or report them separately, because 0.0 would drag the mean down for a reason unrelated to retrieval quality.
Choosing a metric
The diagram shows a simple decision path.
| Metric | Label type | Looks at | Weak spot |
|---|---|---|---|
| MRR | Binary | First relevant hit only | Ignores later relevant documents |
| MAP | Binary | Every relevant hit | Needs complete labels, binary only |
| nDCG@k | Graded or binary | Top k, with position discount | Gain form and cutoff must be reported |
In practice, report one rank-aware metric together with recall@k. Recall@k tells you whether the generator could have seen the evidence at all. The rank-aware metric tells you how early it appeared. Two retrievers can have equal recall@10 and very different nDCG@10, and the second number predicts what happens when the prompt is cut to a few chunks.
Common errors
- Averaging over different question sets. Compute each metric over the same questions for every system you compare.
- Mixing cutoffs. nDCG@5 and nDCG@10 are different numbers. Always write the k.
- Treating duplicates as separate documents. If the retriever returns two chunks of the same source and your labels are at document level, decide whether to deduplicate before scoring. State the rule.
- Label level mismatch. If labels are at passage level and results are chunks, map chunk IDs to labels consistently, or relevant chunks will count as misses.
- Reading small differences as real. A change of 0.01 in MRR on 50 questions is usually noise. A later chapter covers confidence intervals.
Exercise
A retriever returns ["a", "b", "c", "d", "e"]. The relevant set is {"b", "e"}. Compute the reciprocal rank and the average precision.
Show answer
The first relevant document is b at rank 2, so the reciprocal rank is 1/2 = 0.5. For average precision, b is at rank 2 with precision 1/2 = 0.5, and e is at rank 5 with precision 2/5 = 0.4. The total number of relevant documents is 2, so AP = (0.5 + 0.4) / 2 = 0.45.
Exercise
Why should the ideal DCG in nDCG be computed from all labelled documents for the question, and not from the documents the system retrieved?
Show answer
The ideal DCG is the best score any ranking could reach for that question. If you build it only from retrieved documents, a system that misses the best labelled documents gets a smaller ideal value. Its nDCG then looks higher than it should, so missing relevant documents would not be penalised.