Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 2

Precision@k and Recall@k by Hand and in Code

Compute precision@k and recall@k by hand for one labelled query, reproduce the numbers with a short Python function, handle short result lists, queries with no relevant document and repeated ids, and average over queries with macro and micro means.

Contentsand lesson path

What you will learn

  • Define precision@k and recall@k from labeled data.

Prerequisites: RAG Foundations

01. Why it matters

Lesson 1 showed that judging answers alone hides retrieval failures. To find them, compare what the retriever returned with labels: for each query, the documents that hold the evidence an answer needs. Precision@k and recall@k turn that comparison into numbers.

In this worked example you compute both by hand for one query, reproduce them in Python, test the code on three awkward inputs and average over several queries. Lessons 4 and 5 reuse the function unchanged.

02. The problem and the two definitions

Take the help centre from lesson 1, articles d01 to d14. A user types money taken from my card two times. Two articles hold evidence for an answer: d01, the refund policy for duplicate payments, and d13, the same problem for purchases in the Android app. They form the query's relevant set. The retriever returned the five articles below; the ranking and scores are made up.

The worked example: one query, its labels and the top 5 results
Query:     money taken from my card two times
Relevant:  d01, d13   (from the labels)

rank  id   similarity  start of the article
1     d02  0.82        Change the card used for your subscription under Settings ...
2     d01  0.79        Refunds for duplicate payments: if your card was billed twice ...
3     d07  0.55        Export reports to CSV or Excel from any dashboard ...
4     d13  0.52        Charged twice after upgrading in the Android app? ...
5     d03  0.47        Download past invoices as PDF files from the Billing page.

The k is the cut-off: only the top k results count, usually because only they reach the prompt. A hit is a result in the top k that is in the relevant set.

  • Precision@k = hits in the top k / k: the share of the k slots that holds evidence. Low precision fills the prompt with passages the model must ignore.
  • Recall@k = hits in the top k / number of relevant documents: the share of the evidence that reached the top k. Low recall means evidence is missing from the prompt, so the answer may be incomplete or unsupported.

Only the denominator differs. That is why recall needs labels that list every relevant document, including those the retriever never returned.

03. Step 1: compute by hand

Work at k = 3, as if the prompt receives the top three passages.

  1. Cut the ranking at 3: d02, d01, d07.
  2. Mark the hits: only d01 is relevant, so one hit.
  3. Precision@3 = 1 / 3 ≈ 0.333.
  4. Recall@3 = 1 / 2 = 0.500: two articles are relevant and one made the cut.

Now move the cut-off. At k = 5, d13 is in too: precision@5 = 2 / 5 = 0.400 and recall@5 = 2 / 2 = 1.000. At k = 1 only d02 counts, so both metrics are 0. Recall can only stay level or rise as k grows, because a longer cut can only add hits. Precision can move either way: one more irrelevant result at rank 6 would take it from 0.400 back to 0.333.

Notice what the similarity column did not do. d02 has the highest score and is not relevant: it shares the payment vocabulary of the query but says nothing about double charges. Metrics count labels, never scores; a similarity score only says how close two vectors are. The reverse holds too: even with precision and recall at 1, the answer is not guaranteed to be grounded, because the model can still misread or ignore a relevant passage. Retrieval metrics show whether the evidence arrived, not what the model did with it.

04. Step 2: the same numbers in Python

The function below repeats the hand calculation: slice the top k, count the hits, divide twice. It needs Python 3.10 or later and only the standard library (tested with 3.10.12 and 3.12.16). Save it as precision_recall.py in a new folder and run it.

Python · precision_recall.py
"""Precision@k and recall@k for one query, with binary relevance labels."""


def precision_recall_at_k(retrieved: list[str], relevant: set[str], k: int):
    if k <= 0 or not relevant:
        raise ValueError('k must be positive and relevant set non-empty')
    top_k = retrieved[:k]
    hits = sum(doc_id in relevant for doc_id in top_k)
    return hits / k, hits / len(relevant)


if __name__ == "__main__":
    ranked = ["d02", "d01", "d07", "d13", "d03"]  # as the retriever ranked them
    relevant = {"d01", "d13"}  # labels for "money taken from my card two times"
    for k in (1, 3, 5):
        precision, recall = precision_recall_at_k(ranked, relevant, k)
        print(f"k={k}  precision@{k} {precision:.3f}  recall@{k} {recall:.3f}")
Expected output (python precision_recall.py)
k=1  precision@1 0.000  recall@1 0.000
k=3  precision@3 0.333  recall@3 0.500
k=5  precision@5 0.400  recall@5 1.000

The numbers match the hand calculation. Three details matter:

  • retrieved[:k] does not fail when the list is shorter than k; it returns what is there.
  • doc_id in relevant is True or False, and sum() counts True as 1.
  • For k <= 0 or an empty relevant set, the function raises a ValueError instead of returning a number. Step 3 shows why.

Both metrics treat the top k as a set: a hit at rank 1 scores the same as one at rank 3. Lesson 5 adds metrics that reward putting the evidence first, and explains why context precision and context recall in Ragas, an open-source RAG evaluation library, differ from these two.

05. Step 3: three awkward inputs

Real rankings are messier. Try the function on three inputs that often cause wrong numbers.

Python · edge_cases.py (in the same folder)
"""Three awkward inputs, and what precision_recall_at_k() does with them."""

from precision_recall import precision_recall_at_k

relevant = {"d01", "d13"}

# 1. Fewer results than k: the empty slots count as misses.
print("short list:", precision_recall_at_k(["d01"], relevant, 3))

# 2. No relevant document: recall would be 0 / 0, so the function refuses.
try:
    precision_recall_at_k(["d04", "d05", "d06"], set(), 3)
except ValueError as error:
    print("no labels: ValueError:", error)

# 3. The same article twice (two chunks of d01): counted as two hits.
from_chunks = ["d01", "d01", "d02"]
print("duplicates:", precision_recall_at_k(from_chunks, relevant, 3))


def unique_in_order(doc_ids: list[str]) -> list[str]:
    """Keep each id once, at its first (best) rank; a dict keeps insertion order."""
    return list(dict.fromkeys(doc_ids))


top = unique_in_order(from_chunks[:3])  # cut at k first: the prompt had 3 slots
print("deduplicated:", top, precision_recall_at_k(top, relevant, 3))
Expected output (python edge_cases.py)
short list: (0.3333333333333333, 0.5)
no labels: ValueError: k must be positive and relevant set non-empty
duplicates: (0.6666666666666666, 1.0)
deduplicated: ['d01', 'd02'] (0.3333333333333333, 0.5)
  • Fewer results than k. Keyword search may return only the articles that share a word with the query, and a score threshold can stop a retriever early. Precision still divides by k, so the empty slots count as misses: 1/3, not 1/1. That is the usual convention, and the fair one: returning less should not earn higher precision. trec_eval, the evaluation tool of the Text REtrieval Conference (TREC), documents that it fills missing ranks with non-relevant documents. Recall is unaffected.
  • No relevant document. Recall would be 0 / 0, and precision would be 0 for every retriever. Scoring the query as 0 drags every mean down; scoring it as 1 pushes every mean up. So the function refuses. Keep such queries apart, as lesson 3 does, and test something else for them, such as whether the assistant says it cannot answer.
  • The same id twice. Map retrieved chunks to their articles and two chunks of d01 become d01, d01. Both count as hits, so recall@3 shows 1.0 although d13 was never found. Recall above 1 is the visible form of this bug; a perfect-looking recall is the dangerous one.

The fix removes repeats and keeps each article at its best rank. dict.fromkeys() does that in one line, because dictionaries keep insertion order (guaranteed since Python 3.7). When k is the number of prompt slots, cut at k first: the repeated chunk used a slot without adding an article, so it counts as a miss. When you score a ranking of documents, remove repeats first and then cut, and say which you did. trec_eval refuses such input: it stops with an error when a run lists one document twice for a query.

06. Step 4: average over queries

One query tells you little, so you report a mean over a labelled set. The macro mean averages the per-query values, so every query counts the same. The micro mean pools the counts first, all hits over all relevant documents (or over all slots, for precision), so a query with many relevant documents counts for more. The script below scores four queries at k = 3 and sets a fifth aside; the rankings are again made up.

Python · mean_at_k.py (in the same folder)
"""Mean precision@k and recall@k over a few labelled queries: macro and micro."""

from precision_recall import precision_recall_at_k

K = 3
# query -> (top results, best first; labelled relevant articles)
runs = {
    "money taken from my card two times": (["d02", "d01", "d07"], {"d01", "d13"}),
    "pdf invoice download": (["d03", "d07", "d02"], {"d03"}),
    "API returns 413 on exports": (["d09", "d07", "d08"], {"d08", "d09"}),
    "does the app work on iOS 15": (["d10", "d06", "d12"], {"d11"}),
    "how do I change my email address": (["d02", "d04", "d06"], set()),
}

scored = {}  # query -> (precision, recall, number of relevant articles)
set_aside = []
print(f"P@{K}    R@{K}    query")
for query, (ranked, relevant) in runs.items():
    if not relevant:  # recall would be 0 / 0: report the query, do not score it
        set_aside.append(query)
        continue
    precision, recall = precision_recall_at_k(ranked, relevant, K)
    scored[query] = (precision, recall, len(relevant))
    print(f"{precision:.3f}  {recall:.3f}  {query}")

n = len(scored)
macro_p = sum(p for p, _, _ in scored.values()) / n
macro_r = sum(r for _, r, _ in scored.values()) / n
# micro recall pools the hits: each query weighs as much as its number of labels
total_relevant = sum(m for _, _, m in scored.values())
micro_r = sum(r * m for _, r, m in scored.values()) / total_relevant
print(f"macro precision@{K} {macro_p:.3f}  macro recall@{K} {macro_r:.3f}")
print(f"micro recall@{K} {micro_r:.3f} over {total_relevant} relevant articles")
print("set aside, no relevant article:", set_aside)
Expected output (python mean_at_k.py)
P@3    R@3    query
0.333  0.500  money taken from my card two times
0.333  1.000  pdf invoice download
0.667  1.000  API returns 413 on exports
0.000  0.000  does the app work on iOS 15
macro precision@3 0.333  macro recall@3 0.625
micro recall@3 0.667 over 6 relevant articles
set aside, no relevant article: ['how do I change my email address']

Reading the output:

  • Every query keeps its own line. The iOS query found nothing, which the means alone would hide.
  • Macro and micro precision@3 are both 0.333: 4 hits in 12 slots. With the same k for every query the two always agree, so only recall needs a choice.
  • Macro recall@3 is 0.625; micro recall@3 is 4 of 6 relevant articles, 0.667, a mean weighted by each query's number of relevant articles.
  • The email question is reported, not scored. Scored as 0, it would lower macro recall to 0.500.

Report the macro mean as the headline: it describes a typical question, and it is what trec_eval and BEIR, a benchmark of 18 retrieval datasets, report. Micro recall is a useful second view when label counts vary a lot. And when a query has more relevant documents than k, its recall@k cannot reach 1; BEIR uses a capped recall for such datasets, dividing by the smaller of k and the number of relevant documents. Name it if you use it, because it runs higher than plain recall@k.

07. Common mistakes

08. Check your understanding

Practice check · 3 questions

Short lists, repeats and averages

Apply the conventions from steps 3 and 4.

Q1. A teammate's retriever drops every result below a similarity threshold, so it often returns fewer than k articles. Their script divides precision@5 by the number of articles returned. What goes wrong?
Q2. After a switch from whole articles to chunks, one query with two relevant articles scores recall@3 = 1.5. What is the most likely cause?
Q3. At k = 10, query A has one relevant article and finds it. Query B has nine relevant articles and finds three of them. What are the macro and micro recall@10 over the two queries?
Practice only: not graded, not saved, not evidence.

09. Apply it

Continue the practice project with your 10 questions from lesson 1:

  1. Write each question's relevant document ids as a set, and set aside questions that no document answers.
  2. Save the ranked ids your retriever returns for each question and score them with precision_recall_at_k() at the k your prompt uses. If chunks repeat a document, cut at k first, then remove the repeats.
  3. Print one line per query, the macro precision@k and recall@k and the micro recall@k. For each query with recall below 1, note the missed document; the project asks you to analyse at least two.
  4. Score again at the next k you might use, and list the queries that change.

Lesson 3 turns this file into a validated, versioned query set.

10. Review prompt

Without looking back:

  1. Write both formulas and the question each one answers.
  2. Compute both at k = 2 for the ranking d02, d01, d07, d13, d03 with the relevant set {d01, d13}.
  3. How does the function treat a short result list, a query with no relevant document and a repeated id, and why?
  4. When do macro and micro recall differ, and which is the headline number?
  5. Why is a similarity score not a relevance label?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 12 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check