Learning path: Build and Measure a RAG System · Step 11 of 12
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.
What you will learn
- Score a retriever on its own, with a golden set of graded labels and no model call
- Compute Recall@K, reciprocal rank and nDCG by hand and in Python
- Pick the metric that matches how the results are used
- Split the averages by slice to find the weak spot, then read the failing query
Before you start
- Building a Golden Dataset
- Hybrid Search: BM25 Plus Dense Embeddings
When a RAG answer is wrong, it's tempting to blame the model. But the model can only answer from what the retriever brings back. So in this article we measure the retriever on its own, with no model call at all, using three metrics: Recall@K, MRR and nDCG. If the score is bad, we know where to look before any model gets the blame.
Three questions for a librarian
You ask a librarian for books on one topic, and they bring a stack of five, best guess on top. Three questions:
- Of all the useful books, how many are in this stack? That's recall.
- How far down do you dig before the first useful one? That's MRR.
- Are the most useful ones near the top? That's nDCG.
One stack, three questions, and they won't always agree.
The project and its answer key
The project has 40 short help-desk articles for a made-up project-board product, and two retrievers:
- Keyword: TF-IDF word vectors and cosine similarity.
- Dense: the same TF-IDF squeezed to 16 dimensions with
TruncatedSVD. It's a small local stand-in for an embedding model, not a real one, so everything runs offline and gives the same result every time.
The answer key is a golden set of 24 queries with graded labels written by hand: 2 = answers the query, 1 = partly helps, missing = 0. Each query also has a slice: exact_code (8), paraphrase (10) or short (6). (How to build such a set: Building a Golden Dataset.)
{"id": "q06", "query": "E6120 nobody in the company can log in", "slice": "exact_code", "labels": {"d10": 2, "d34": 1}}
For this query, d10 (Error E6120: SSO certificate expired) answers it, and d34 (Set up single sign-on) partly helps. Both retrievers put d10 first. Which is better? You can't tell by looking, and you can't read every list every time something changes. We need a score.
The three metrics in code
import math
def recall_at_k(ranked, labels, k):
"""Share of relevant docs found in the top k."""
relevant = {d for d, g in labels.items() if g > 0}
found = relevant & set(ranked[:k])
return len(found) / len(relevant)
def reciprocal_rank(ranked, labels):
"""1 / rank of the first relevant doc, else 0."""
for i, doc in enumerate(ranked, start=1):
if labels.get(doc, 0) > 0:
return 1 / i
return 0.0
def dcg_at_k(ranked, labels, k):
"""Discounted gain: grade / log2(rank + 1)."""
total = 0.0
for i, doc in enumerate(ranked[:k], start=1):
total += labels.get(doc, 0) / math.log2(i + 1)
return total
def ndcg_at_k(ranked, labels, k):
"""DCG divided by the DCG of a perfect ranking."""
best = sorted(labels, key=labels.get, reverse=True)
ideal = dcg_at_k(best, labels, k)
if ideal == 0:
return 0.0
return dcg_at_k(ranked, labels, k) / ideal
Recall@K: did it show up?
recall_at_k collects the relevant docs (grade above 0, so d10 and d34), cuts the list at k = 5, and checks which are inside. The top 5 for q06:
| Rank | Keyword (grade) | Dense (grade) |
|---|---|---|
| 1 | d10 (2) | d10 (2) |
| 2 | d01 (0) | d04 (0) |
| 3 | d02 (0) | d34 (1) |
| 4 | d03 (0) | d21 (0) |
| 5 | d04 (0) | d02 (0) |
Keyword finds 1 of 2 relevant docs: recall 0.5. Dense finds both: 1.0. Recall tells you if the right documents showed up. It doesn't care about their order.
MRR: how soon is the first hit?
reciprocal_rank walks down the list, stops at the first relevant doc and returns 1 / its rank. A new query, API returns E5002, has one right article, d08. Keyword has it at rank 1: 1.0. Dense puts Create an API token first and d08 second: 1 / 2 = 0.5. Recall is 1.0 for both, so recall can't see this difference. MRR is the mean of this number over all queries, and it only looks at the first hit.
nDCG: compare with a perfect list
MRR ignores everything after the first hit, and treats a grade 1 like a grade 2. nDCG fixes both. First DCG: each grade is divided by log2(rank + 1), so rank 1 keeps everything and rank 3 keeps half.
Is 2.5 good? Sort the labels into the perfect list, which scores 2.63, and divide. Dense gets 0.95, keyword 0.76 (its d34 never made the top 5).
All 24 queries, no clear winner
evaluate.py asks each retriever for its top 10, scores every query with score_query (Recall@5, MRR over all 10, nDCG@5), and averages per retriever and per slice:
python -m retrieval_eval.evaluate
40 docs, 24 queries
Overall
Recall@5 MRR nDCG@5
Keyword 0.757 0.854 0.769
Dense 0.819 0.826 0.782
Slice: exact_code (8 queries)
Recall@5 MRR nDCG@5
Keyword 0.875 1.000 0.940
Dense 1.000 0.938 0.941
Slice: paraphrase (10 queries)
Recall@5 MRR nDCG@5
Keyword 0.517 0.650 0.517
Dense 0.567 0.633 0.546
Slice: short (6 queries)
Recall@5 MRR nDCG@5
Keyword 1.000 1.000 0.961
Dense 1.000 1.000 0.964
Recall@5 favours dense, MRR goes the other way, nDCG is almost tied. Be careful here: with 24 queries, one single query can move an average by about 0.04, and the MRR and nDCG gaps are both smaller than that. The honest answer on this data is: no clear winner. A bigger golden set is how you'd settle it.
The average hides the weak spot
Split by slice and the picture changes. On exact codes and short queries, both retrievers do well, about 0.94 and 0.96 nDCG. On paraphrases, where the user's words differ from the article's words, keyword drops to 0.52 and dense to 0.55.
Now read the worst query: stop being charged next month. Both retrievers score 0 on all three metrics, and both put Mute a board first. The articles it needed are Cancel your subscription and Upgrade or downgrade your plan. The user said "charged"; those articles use other words. The metric tells you where it failed; reading the query tells you why. This is the kind of query hybrid search and real embedding models are meant to help with, and now you have the numbers to check whether they do. (The same slicing idea for classifiers is in slice evaluation.)
Which metric when?
| How results are used | Metric | Why |
|---|---|---|
| A model reads the top 5 (RAG) | Recall@5 | You care that the right docs are in there |
| A person clicks the first result | MRR | Only the first hit matters |
| A results page where order and grades matter | nDCG@5 | Rewards strong docs near the top |
Common mistakes
- Blaming the model before scoring the retriever.
- Reporting one metric. Recall saw no difference on E5002; MRR did.
- Reading a gap smaller than one query's weight as a win.
- Looking only at the overall average. Split by slice, then read the worst queries.
- Treating grade 1 and grade 2 the same when they're not. That's what nDCG's grades are for.
Quick recap
- Recall@K: share of relevant docs in the top k. Ignores order.
- MRR: mean of 1 / rank of the first relevant doc. Ignores the rest.
- nDCG@K: graded gain discounted by rank, divided by the perfect list's gain. 0 to 1.
- Average, then split by slice, then read the failures.
Try it yourself
Change K from 5 to 3 in evaluate.py and run it again. The table headers still say 5 (they're hard-coded), so don't let that throw you. Which retriever loses the most?
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.