Sub topic 13
Measuring retrieval quality: recall@k, MRR, and nDCG
This chapter assumes you can build a basic semantic search (embed documents, embed a query, rank by cosine similarity) and read short Python functions. Tuning chunk size, models, or indexes without a measurement is guesswork, so you need a small labeled test set and a few metrics.
Build a labeled query set
An evaluation set is a list of queries. Each query is paired with the document ids a person judged relevant. Start with 30 to 100 queries taken from real user questions. Write down the relevant ids before you look at what your system returns, or you will bias the labels toward its current behavior.
Evaluate the ranked list of ids that your search returns for each query. Then average each metric over all queries.
Recall@k
Recall@k is the share of the relevant documents that appear in the top k results. If a query has two relevant documents and one is in the top 3, recall@3 is 0.5.
Use recall@k when a later stage, such as a reranker or a language model, reads the top k results. If the right document is not in that list, no later stage can recover it.
Mean reciprocal rank
Reciprocal rank is 1 divided by the position of the first relevant result. A hit at rank 1 scores 1.0, rank 2 scores 0.5, and rank 4 scores 0.25. If nothing relevant is returned, the score is 0. Mean reciprocal rank (MRR) averages this over all queries.
MRR suits cases where the user needs one good answer near the top. It ignores every relevant document after the first.
nDCG
Normalized discounted cumulative gain (nDCG) handles graded relevance, such as 0 (irrelevant), 1 (partly relevant), and 2 (exact answer). It rewards putting highly relevant documents early. Each result's grade is divided by log2(rank + 1), so lower positions count less. The sum is then divided by the best possible sum for that query, which gives a score between 0 and 1.
import math
def recall_at_k(retrieved, relevant, k):
if not relevant:
return 0.0
return len(set(retrieved[:k]) & set(relevant)) / len(relevant)
def reciprocal_rank(retrieved, relevant):
for rank, doc_id in enumerate(retrieved, start=1):
if doc_id in relevant:
return 1.0 / rank
return 0.0
def ndcg_at_k(retrieved, grades, k):
"""grades: dict mapping doc id to a relevance grade (missing means 0)."""
dcg = sum(grades.get(d, 0) / math.log2(i + 1)
for i, d in enumerate(retrieved[:k], start=1))
ideal = sorted(grades.values(), reverse=True)[:k]
idcg = sum(g / math.log2(i + 1) for i, g in enumerate(ideal, start=1))
return dcg / idcg if idcg > 0 else 0.0
queries = [
{"retrieved": ["d4", "d1", "d9", "d2"], "grades": {"d1": 2, "d2": 1}},
{"retrieved": ["d7", "d3", "d5", "d8"], "grades": {"d3": 2}},
]
for name, fn in [
("recall@3", lambda q: recall_at_k(q["retrieved"], set(q["grades"]), 3)),
("rr", lambda q: reciprocal_rank(q["retrieved"], set(q["grades"]))),
("ndcg@3", lambda q: ndcg_at_k(q["retrieved"], q["grades"], 3)),
]:
mean = sum(fn(q) for q in queries) / len(queries)
print(f"{name}: {mean:.3f}")Choosing a metric
| Metric | Question it answers | Relevance labels |
|---|---|---|
| recall@k | Did the relevant documents make it into the top k? | Binary |
| MRR | How early is the first relevant result? | Binary |
| nDCG@k | Is the whole ranking in a good order? | Graded |
Common errors
- Changing the test set between runs, which makes scores incomparable.
- Reporting one average only. Look at the queries with score 0, since they show what to fix.
- Chunked documents: map each retrieved chunk back to its source document id, and remove duplicates before scoring.
- Incomplete labels. An unlabeled but useful result counts as a miss, so scores are a lower bound.
Exercise
A query has relevant documents {"a", "b", "c"}. Your search returns ["x", "b", "y", "a", "z"]. What are recall@3, recall@5, and the reciprocal rank?
Show answer
Recall@3: only "b" is in the top 3, so 1/3 ≈ 0.333. Recall@5: "b" and "a" are found, so 2/3 ≈ 0.667. Reciprocal rank: the first relevant result, "b", is at rank 2, so 0.5.
Exercise
Why is nDCG a better fit than MRR when some documents answer the query fully and others only partly?
Show answer
MRR uses binary labels and looks only at the first relevant result. nDCG uses graded labels and scores the whole ranking, so it rewards placing the fully relevant document above the partly relevant ones.