Search Tutorials
--Ads--Retrieval Metrics: Recall@k, Precision@k, MRR and nDCG
Implement the standard information-retrieval metrics in plain Python.
Retrieval metrics come from decades of information-retrieval research. They need a test set in which each question is labelled with the chunks (or documents) that are relevant to it. Given those labels, the metrics are simple to compute and need no LLM, so you can run them on every change. This lesson implements the five you will use most.
Setup: labels and results
For each question you have the set of relevant IDs (from your test set) and the ranked list of retrieved IDs (from your retriever).
relevant = {"leave-1", "leave-2"} # labelled as relevant
retrieved = ["leave-1", "exp-0", "leave-2", "it-3", "leave-0"] # ranked results, best first
Hit rate@k
Did at least one relevant item appear in the top k? It is the simplest and most intuitive metric for RAG, where one good chunk is often enough.
def hit_rate_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
return 1.0 if any(r in relevant for r in retrieved[:k]) else 0.0
Recall@k
What fraction of all relevant items appeared in the top k? Important when answers need several pieces of evidence.
def recall_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
if not relevant:
return 0.0
return len(set(retrieved[:k]) & relevant) / len(relevant)
Precision@k
What fraction of the top k are relevant? It tells you how much noise you send to the LLM.
def precision_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
return len([r for r in retrieved[:k] if r in relevant]) / k
MRR (mean reciprocal rank)
The reciprocal of the rank of the first relevant item (1 for rank 1, 0.5 for rank 2, 0.33 for rank 3, and 0 if none), averaged over all questions. It rewards putting a good result at the very top.
def reciprocal_rank(retrieved: list[str], relevant: set[str]) -> float:
for rank, r in enumerate(retrieved, start=1):
if r in relevant:
return 1.0 / rank
return 0.0
nDCG@k (normalised discounted cumulative gain)
nDCG handles graded relevance (for example 2 = answers the question, 1 = related, 0 = irrelevant) and rewards placing the most relevant items highest. Each result's grade is discounted by the logarithm of its rank, and the total is divided by the best possible total, giving a score between 0 and 1.
import math
def ndcg_at_k(retrieved: list[str], grades: dict[str, int], k: int) -> float:
dcg = sum(grades.get(r, 0) / math.log2(rank + 1) for rank, r in enumerate(retrieved[:k], start=1))
ideal = sorted(grades.values(), reverse=True)[:k]
idcg = sum(g / math.log2(rank + 1) for rank, g in enumerate(ideal, start=1))
return dcg / idcg if idcg else 0.0
Worked example
k = 3
print("hit@3 ", hit_rate_at_k(retrieved, relevant, k)) # 1.0 (leave-1 at rank 1)
print("recall@3 ", recall_at_k(retrieved, relevant, k)) # 1.0 (both relevant in top 3)
print("precision@3", precision_at_k(retrieved, relevant, k)) # 0.67 (2 of 3)
print("RR ", reciprocal_rank(retrieved, relevant)) # 1.0
print("nDCG@3 ", round(ndcg_at_k(retrieved, {"leave-1": 2, "leave-2": 1}, k), 3)) # 0.95
Evaluating a whole test set
import numpy as np
def retrieval_report(test_set: list[dict], retrieve, ks=(1, 3, 5, 10)) -> dict:
"""test_set items: {"question": ..., "relevant_ids": [...]}; retrieve(q, k) -> list of ids"""
max_k = max(ks)
rows = []
for case in test_set:
ids = retrieve(case["question"], max_k)
rel = set(case["relevant_ids"])
row = {"rr": reciprocal_rank(ids, rel)}
for k in ks:
row[f"hit@{k}"] = hit_rate_at_k(ids, rel, k)
row[f"recall@{k}"] = recall_at_k(ids, rel, k)
rows.append(row)
return {metric: round(float(np.mean([r[metric] for r in rows])), 3) for metric in rows[0]}
Labels by evidence instead of IDs
Chunk IDs change whenever you change chunking, which would make your labels useless. Label relevance with an evidence string instead (a short phrase that must appear in a relevant chunk), as in Evaluating Chunking Strategies. A retrieved chunk counts as relevant if it contains the evidence. This keeps one test set valid across all chunking experiments.
Which metric when?
| Metric | Use when |
|---|---|
| Hit rate@k | Most questions need one passage; the default headline metric |
| Recall@k | Answers need several passages; choosing k |
| Precision@k | Prompt cost or noise matters; tuning thresholds |
| MRR | Only the top one or two results are used; evaluating rerankers |
| nDCG@k | You have graded labels; comparing ranking quality in detail |
Key takeaways
- Retrieval metrics need relevance labels but no LLM, so they are fast and cheap to run.
- Hit rate and recall measure whether evidence was found; precision measures noise; MRR and nDCG measure ranking quality.
- Label relevance with evidence strings so the test set survives chunking changes.
- Report several k values; the curve shows how far down the evidence sits.