BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Embeddings and RAG18 of 19 in topic

803. Score a retriever with recall@k and MRR

EasyEmbeddings and RAG

Why it matters Most bad RAG answers come from retrieval misses, and these two numbers find them.

Before tuning a RAG prompt, check the retriever. Recall@k asks what share of the relevant chunks made the top k. Mean reciprocal rank (MRR) rewards putting the first relevant chunk near the top.

Write retrieval_metrics(results, relevant, k). results is a list of ranked id lists (one per query, best first) and relevant is a list of sets of relevant ids. Return a dict:
- "recall@k": mean over queries of |relevant in top k| / |relevant| (a query with no relevant ids counts as 0)
- "mrr": mean over queries of 1 / rank of the first relevant id (1-based), or 0 if none appears anywhere in the list

Functiondef retrieval_metrics(results, relevant, k)

Example 1

Input: retrieval_metrics([[3, 1, 2], [5, 6, 7]], [{1, 2}, {9}], 2)

Output: {'recall@k': 0.25, 'mrr': 0.25}

Example 2

Input: results = [['a', 'b'], ['c', 'd']], relevant = [{'a'}, {'d'}], k = 1

Output: {'recall@k': 0.5, 'mrr': 0.75}

Example 3

Input: results = [[1, 2, 3, 4]], relevant = [{4, 9}], k = 4

Output: {'recall@k': 0.5, 'mrr': 0.25}

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
Hint 1

Handle each query separately, then average.

Hint 2

Recall uses only the first k ids; MRR scans the whole list for the first relevant id.

Common mistakes
  • Dividing recall by k instead of by the number of relevant ids.
  • Using 0-based rank in MRR, which divides by zero.
Understand the idea

Recall@k ignores order inside the top k; MRR cares only about the first hit. Together they tell you whether the right chunk is found and how high it sits.

Worked example

query 1 returns [3, 1, 2] with relevant {1, 2}: top 2 has one of two, recall 0.5, first hit at rank 2 so RR 0.5. Query 2 has no hit: 0 and 0. Means: recall 0.25, MRR 0.25.

recall = hits in top k / relevant; RR = 1 / first relevant rank
Topics
Embeddings and RAG
Similar questions
  • RAG retrieval: pick the top-k help article chunks for a questionEasy
  • Merge several retrievers' rankings with reciprocal rank fusionEasy
  • Truncate Matryoshka embeddings and renormaliseEasy
  • Measure recall at k of an approximate indexEasy
All Embeddings and RAG problems
Report
803 / 903
Python 3solution.pyPython idle
1
2
3
4
def retrieval_metrics(results, relevant, k):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS