Sub topic 4
Precision@k, recall@k, and hit rate
This chapter covers the set-based metrics for a retriever. They treat the top k results as an unordered set and ask how many of them are relevant. The next chapter adds rank-aware metrics.
Prerequisites
This chapter assumes you know:
- How a RAG pipeline works: chunking, embedding, vector search, and prompting an LLM.
- Precision and recall from classification.
- How to read basic Python.
- That you have an evaluation set of questions, each labelled with the document or chunk IDs that answer it (built in the previous chapter).
What "set-based" means
A retriever returns a ranked list of chunks. A generator usually receives only the top k of them, where k is the number of chunks you put into the prompt. Set-based metrics look at that top-k list as a set. They ignore the order inside it. A relevant chunk at position 1 counts the same as one at position k.
Three metrics cover most needs:
| Metric | Question it answers | Range |
|---|---|---|
| precision@k | How much of what I retrieved is relevant? | 0 to 1 |
| recall@k | How much of what is relevant did I retrieve? | 0 to 1, or undefined |
| hit rate@k | For what share of questions did I retrieve at least one relevant chunk? | 0 to 1 |
Precision and recall are computed per question. Hit rate is defined per question as 0 or 1, and its average over questions is the number you report.
Precision@k
Precision@k is the number of relevant items in the top k, divided by the number of items returned.
precision@k = (relevant items in top k) / (items in top k)A low precision means the prompt contains noise. Noise costs tokens, and it can distract the generator or lead it to cite an irrelevant passage.
Precision@k has a ceiling that depends on the question. If a question has only two relevant chunks and k is 5, the best possible precision@5 is 2/5 = 0.4. A system that is perfect on that question still scores 0.4. Do not read a precision@5 of 0.4 as poor without checking how many relevant chunks exist.
Recall@k
Recall@k is the number of relevant items in the top k, divided by the total number of relevant items for the question.
recall@k = (relevant items in top k) / (all relevant items)A low recall means information the generator needed never reached the prompt. No amount of prompt tuning fixes that.
Recall has an edge case. If a question has no labelled relevant documents, the denominator is zero and recall is undefined. Return None and exclude that question from the average. Do not return 0 or 1, because either one distorts the mean. Questions with no relevant documents are still useful, for example to test whether the system should decline to answer, but they need a separate evaluation.
Recall also has a ceiling. If a question has 8 relevant chunks and k is 5, the best possible recall@5 is 5/8 = 0.625.
Worked example
The code below implements both metrics on one question.
def precision_at_k(retrieved_ids, relevant_ids, k):
top_k = retrieved_ids[:k]
if not top_k:
return 0.0
hits = sum(1 for d in top_k if d in relevant_ids)
return hits / len(top_k)
def recall_at_k(retrieved_ids, relevant_ids, k):
if not relevant_ids:
return None # undefined: the question has no labelled relevant documents
hits = sum(1 for d in retrieved_ids[:k] if d in relevant_ids)
return hits / len(relevant_ids)
retrieved = ["d7", "d2", "d9", "d1"]
relevant = {"d2", "d1", "d5"}
print(precision_at_k(retrieved, relevant, 3)) # 1/3
print(recall_at_k(retrieved, relevant, 3)) # 1/3Work through it. The top 3 results are d7, d2, and d9. Only d2 is relevant, so precision@3 is 1/3. Three documents are relevant in total (d2, d1, d5), and one of them was retrieved, so recall@3 is 1/3. The document d1 is at position 4 and does not count at k=3. At k=4 it would count, and both metrics would change: precision@4 is 2/4 and recall@4 is 2/3.
Two details of the code are deliberate:
precision_at_kdivides bylen(top_k), not byk. If the retriever returns fewer than k items, precision is computed over what it returned. Some teams divide by k instead, which penalizes short result lists. Pick one convention and document it.relevant_idsis a set, so membership tests are fast and duplicates in the labels cannot inflate the count.
Hit rate
Hit rate@k is the share of questions for which at least one relevant item appears in the top k. It is also called success@k or recall-any@k.
def hit_at_k(retrieved_ids, relevant_ids, k):
return 1.0 if any(d in relevant_ids for d in retrieved_ids[:k]) else 0.0
def mean_ignoring_none(values):
kept = [v for v in values if v is not None]
return sum(kept) / len(kept) if kept else None
# Each tuple is (retrieved ids, relevant ids) for one question.
eval_set = [
(["d7", "d2", "d9", "d1"], {"d2", "d1", "d5"}),
(["d3", "d4", "d6"], {"d8"}),
(["d5", "d1", "d2"], {"d5"}),
]
k = 3
hits = [hit_at_k(r, rel, k) for r, rel in eval_set]
print(hits) # [1.0, 0.0, 1.0]
print(mean_ignoring_none(hits)) # 0.666...Hit rate is the most forgiving of the three. It is the right metric when one good chunk is enough to answer, as in simple factual lookups. It is a weak metric when answers need several pieces of evidence, such as comparing two policies. In that case a question can score a hit while the generator still lacks half the information. Use recall@k alongside it for multi-evidence questions.
Choosing k
The value of k should match what your pipeline does. If the prompt receives 5 chunks, evaluate at k=5. Evaluating at k=20 tells you about the retriever, but not about what the generator saw.
It is common to report several values, for example k=1, 3, 5, and 10, and to look at how the numbers move:
- Recall rises as k grows, and it never falls.
- Precision usually falls as k grows, though it can rise at some steps.
- Hit rate rises as k grows, and it never falls.
A large gap between recall@10 and recall@3 suggests that relevant chunks are being retrieved but ranked too low. That points to a re-ranker or a better scoring function. A low recall@10 suggests the retriever is not finding them at all, which points to chunking, embeddings, or query rewriting.
def sweep(eval_set, ks=(1, 3, 5, 10)):
rows = []
for k in ks:
p = mean_ignoring_none([precision_at_k(r, rel, k) for r, rel in eval_set])
rc = mean_ignoring_none([recall_at_k(r, rel, k) for r, rel in eval_set])
h = mean_ignoring_none([hit_at_k(r, rel, k) for r, rel in eval_set])
rows.append((k, p, rc, h))
return rows
# Uses precision_at_k and recall_at_k from the first listing,
# and hit_at_k and mean_ignoring_none from the second.
for k, p, rc, h in sweep(eval_set):
print(f"k={k:<2} precision={p:.2f} recall={rc:.2f} hit_rate={h:.2f}")Macro averaging and the question mix
The examples above average the per-question scores, which gives each question equal weight. This is macro averaging. It is the usual choice, because you care about how often the system serves a user well, not about how many relevant chunks exist overall.
Pooling all hits and dividing by all relevant items across questions (micro averaging) gives more weight to questions with many relevant chunks. That can hide failures on questions that have one relevant chunk. Prefer macro averages, and say that you used them.
Common errors
- Mixing ID levels. Labels refer to documents but the retriever returns chunk IDs, or the reverse. Every hit then fails to match, and the metrics look terrible. Map chunk IDs to their parent document ID, or label at chunk level, and keep it consistent.
- Duplicate results. If the retriever returns three chunks from the same document and labels are at document level, precision is inflated because one document is counted three times. Deduplicate by document ID, preserving order, before scoring.
- Incomplete labels. If annotators marked only one relevant chunk but three chunks contain the answer, a correct retrieval of the other two counts as a miss. Precision is then understated. Review the top results for a sample of low-precision questions before trusting the number.
- Treating undefined recall as zero. Questions with no relevant documents must be excluded from recall averages.
- Reporting a single number. A mean precision@5 without k, label granularity, and question count cannot be compared with anything.
How the metrics relate
The diagram shows what each metric counts for one question with k=3.
Summary
- Precision@k measures noise in the prompt. Recall@k measures missing evidence. Hit rate@k measures whether any evidence arrived.
- Evaluate at the k your pipeline actually uses, and sweep a few other values to locate the problem.
- Handle undefined recall, duplicates, and label granularity explicitly.
- Average per question (macro), and report k, the number of questions, and the label granularity.
Exercise
A retriever returns ["d4", "d1", "d8", "d2", "d6"] for a question whose relevant set is {"d1", "d2", "d3", "d9"}. Compute precision@3, recall@3, precision@5, recall@5, and hit@3. Then say what the gap between recall@3 and recall@5 suggests.
Show answer
The top 3 are d4, d1, d8, so one hit (d1). Precision@3 = 1/3, recall@3 = 1/4, hit@3 = 1. The top 5 add d2 and d6, so hits = 2 (d1, d2). Precision@5 = 2/5 = 0.4, recall@5 = 2/4 = 0.5. Recall rose because d2 sits at position 4, just outside the prompt at k=3. This suggests the retriever finds some relevant chunks but ranks them low, so a re-ranker or a larger k could help. d3 and d9 are not retrieved at all, which points to a separate retrieval gap.
Exercise
Your eval set has 50 questions. For 6 of them, the labelled relevant set is empty because the answer is not in the corpus. How should you treat these 6 questions when you report mean recall@5 and mean precision@5, and why?
Show answer
Exclude them from mean recall@5, because recall is undefined when there are no relevant documents (the denominator is zero). Returning 0 or 1 would bias the mean. Precision@5 is also not meaningful for them: every retrieved item is irrelevant by definition, so it is always 0 and would drag the mean down without telling you anything about retrieval quality. Report both means over the 44 answerable questions, and evaluate the 6 unanswerable ones separately, for example by checking whether the system declines to answer.
Exercise
A teammate changes the chunk size from 500 to 200 tokens. Precision@5 at document level jumps from 0.30 to 0.55, and hit rate is unchanged. Name one likely artifact in the measurement, and one check to run.
Show answer
Smaller chunks give more results per document, and if the retriever returns several chunks from the same relevant document, the same document is counted more than once. That inflates precision at document level while hit rate, which only asks whether any relevant document appeared, stays the same. Check by deduplicating retrieved IDs by document ID before scoring and recomputing precision@5, or by comparing chunk-level results against chunk-level labels.