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 5 of 6 · Concept · 15 min · revision 3

Rank-Aware Metrics and the Limits of Labels

Compute MRR, average precision and nDCG with graded labels, see them reverse a recall@3 verdict, check what each tool means by a metric name, and recognise incomplete judgements, chunk-versus-document relevance and label drift.

Contentsand lesson path

What you will learn

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

Prerequisites: RAG Foundations

01. Why it matters

Precision@k and recall@k treat the top k as a set: a relevant article at rank 1 and the same article at rank 3 score the same. Order often matters, though. A search page draws the eye to the first result, an assistant may quote only its first passage, and models do not attend evenly to everything in a long context. In lesson 4, recall@3 put vector search ahead while at k = 1 keyword search led. Rank-aware metrics capture that kind of difference in one number.

The second half of the lesson turns to the labels. Every metric in this skill assumes that the labels are complete, at the right granularity and still true. In practice each assumption fails sometimes, and knowing how keeps you from trusting a number that is precise but wrong.

02. Three rank-aware metrics

Each is computed per query at a cut-off k and averaged over queries, like precision and recall.

  • Reciprocal rank (RR) is 1 divided by the rank of the first relevant document, or 0 if none is in the top k. Its mean over queries is MRR, which you used as MRR@10 to compare embedding models. It asks how far down someone must look for the first useful result, and ignores every relevant document after the first, so it suits questions with one right answer.
  • Average precision (AP) walks down the ranking and, at each rank that holds a relevant document, takes precision at that rank. It sums those values and divides by the number of relevant documents in the reference set, so a relevant document that was never retrieved adds 0 and pulls AP down, much as it pulls down recall. Its mean is MAP.
  • nDCG (normalised discounted cumulative gain) uses graded labels. Each result earns a gain, here simply its grade, divided by a discount that grows with rank, log2(rank + 1): 1 at rank 1, 1.585 at rank 2, 2 at rank 3. The sum is the DCG. Dividing it by the DCG of the ideal order of the labelled documents (the IDCG) gives a score between 0 and 1. Benchmarks such as BEIR report nDCG@10 as their main metric.

Take query q01 from lesson 3, charged twice for the same order, labelled d01 = 2 and d13 = 1. Keyword search returned d13, d01 and vector search d01, d13, d02. Both found both articles, so precision@3, recall@3, RR and AP are identical. Only nDCG notices that keyword search put the partly relevant article first:

  • keyword: DCG = 1/1 + 2/1.585 = 2.262
  • vector, which is also the ideal order: DCG = IDCG = 2/1 + 1/1.585 = 2.631
  • nDCG@3 = 2.262 / 2.631 = 0.860 for keyword, and 1.000 for vector
Python · rank_metrics.py (in the retrieval-eval folder)
"""Rank-aware metrics for one ranked list, cut off at k."""

import math


def reciprocal_rank(ranked: list[str], relevant: set[str], k: int) -> float:
    """1 / rank of the first relevant document in the top k; 0 if there is none."""
    for rank, doc_id in enumerate(ranked[:k], start=1):
        if doc_id in relevant:
            return 1 / rank
    return 0.0


def average_precision(ranked: list[str], relevant: set[str], k: int) -> float:
    """Precision@i at every rank i that holds a relevant document, summed and
    divided by ALL relevant documents, so a missed one counts as zero."""
    hits, total = 0, 0.0
    for rank, doc_id in enumerate(ranked[:k], start=1):
        if doc_id in relevant:
            hits += 1
            total += hits / rank
    return total / len(relevant)


def ndcg(ranked: list[str], grades: dict[str, int], k: int) -> float:
    """Gain = the grade itself; a result at rank i is discounted by log2(i + 1)."""
    dcg = sum(grades.get(doc_id, 0) / math.log2(rank + 1)
              for rank, doc_id in enumerate(ranked[:k], start=1))
    best = sorted(grades.values(), reverse=True)[:k]
    ideal = sum(grade / math.log2(rank + 1) for rank, grade in enumerate(best, start=1))
    return dcg / ideal
Python · demo_rank.py
from metrics import precision_recall_at_k
from rank_metrics import average_precision, ndcg, reciprocal_rank

grades = {"d01": 2, "d13": 1}   # q01 "charged twice for the same order"
relevant = set(grades)          # the binary view: grade 1 or 2 counts as relevant
runs = {"keyword": ["d13", "d01"], "vector": ["d01", "d13", "d02"]}
for name, ranked in runs.items():
    p, r = precision_recall_at_k(ranked, relevant, 3)
    rr = reciprocal_rank(ranked, relevant, 3)
    ap = average_precision(ranked, relevant, 3)
    print(f"{name:<8} P@3 {p:.3f}  R@3 {r:.3f}  RR {rr:.3f}  AP {ap:.3f}  "
          f"nDCG@3 {ndcg(ranked, grades, 3):.3f}")
Expected output (python demo_rank.py)
keyword  P@3 0.667  R@3 1.000  RR 1.000  AP 1.000  nDCG@3 0.860
vector   P@3 0.667  R@3 1.000  RR 1.000  AP 1.000  nDCG@3 1.000

03. When the rank-aware metrics disagree with recall

Score the two runs from lesson 4 on all four metrics at k = 3. The graded labels come straight from data/test.jsonl.

Python · rank_report.py
"""Mean recall@3 and the rank-aware metrics for both runs on the test split."""

from metrics import load_run, precision_recall_at_k
from rank_metrics import average_precision, ndcg, reciprocal_rank
from validate import read_jsonl

K = 3
rows = read_jsonl("data/test.jsonl")  # graded labels, not just the binary sets
print(f"{'':<8} {'R@3':>6} {'MRR@3':>6} {'MAP@3':>6} {'nDCG@3':>7}")
for name in ("keyword", "vector"):
    run = load_run(f"runs/{name}.jsonl")
    totals = [0.0, 0.0, 0.0, 0.0]
    for row in rows:
        ranked, grades = run[row["id"]], row["relevant"]
        relevant = set(grades)
        scores = (precision_recall_at_k(ranked, relevant, K)[1],
                  reciprocal_rank(ranked, relevant, K),
                  average_precision(ranked, relevant, K),
                  ndcg(ranked, grades, K))
        totals = [t + s for t, s in zip(totals, scores)]
    recall, mrr, map_k, ndcg_k = (t / len(rows) for t in totals)
    print(f"{name:<8} {recall:>6.3f} {mrr:>6.3f} {map_k:>6.3f} {ndcg_k:>7.3f}")
Expected output (python rank_report.py)
            R@3  MRR@3  MAP@3  nDCG@3
keyword   0.875  0.938  0.816   0.896
vector    0.917  0.812  0.785   0.822

The rank-aware metrics reverse the recall@3 verdict: keyword search has the higher MRR, MAP and nDCG at 3, because it more often puts the right article first, while vector search more often gets a related article somewhere into the top 3. Neither verdict is wrong; they answer different questions. If your prompt includes all three passages and the model uses them all, recall@3 is closest to what you care about. If the first passage dominates, the rank-aware metrics are. Choose the metric before you look at the numbers, and test any gap the way you did in lesson 4.

04. Read the definition, not just the name

Metric names hide choices, and tools make different ones:

  • nDCG gain. trec_eval, scikit-learn's ndcg_score and the plain ndcg in ranx use the grade itself as the gain, as above. A variant from Burges and colleagues uses 2^grade − 1, which weights highly relevant documents more; ranx calls it ndcg_burges. The two give different numbers for the same ranking.
  • AP denominator. This lesson and trec_eval divide by all relevant documents in the reference set. Some libraries divide by the smaller of k and that count, so a query with more relevant documents than k can still reach 1.
  • Cut-offs. trec_eval's recip_rank has no cut-off: on q20, where vector search ranks the invoice article fourth, it gives 0.25 where reciprocal_rank(..., 3) gives 0.
  • RAG toolkit names. Ragas context precision is not precision@k. It is a rank-aware, average-precision-style score whose relevance usually comes from an LLM comparing each chunk with a reference answer, and it divides by the relevant chunks found in the top K rather than by all relevant ones. Ragas context recall asks an LLM whether each claim in a reference answer is supported by the retrieved context. Ragas also offers ID-based variants that compare ids directly, as this skill does.

Write the tool, its version, the gain and the cut-off next to every number. The functions above agree with trec_eval's P_3, recall_3, map_cut_3 and ndcg_cut_3 on every query of the lab runs, but in production use a maintained implementation such as pytrec_eval or ir-measures rather than your own.

05. The limits of labels

Incomplete judgements. In a large corpus, labels come from pooling, so only documents that someone looked at are judged. Metric code treats every unjudged document as irrelevant. A new configuration that finds good documents nobody judged is scored down for them, and the comparison quietly favours the configurations that built the pool. Before comparing a new configuration, check what share of its top k has any judgement at all (ir-measures calls this Judged@k). If it is clearly lower than for the others, judge the new documents first, recording explicit grade 0s, and only then compare. Metrics designed for incomplete judgements exist, such as bpref (Buckley and Voorhees, 2004), but at the scale of a RAG evaluation set, filling the pool is usually simpler.

Chunk versus document relevance. Labels are often per document while the retriever returns chunks. Mapping each chunk to its document and counting a hit is convenient but loose: a long document may be retrieved through a chunk that does not contain the answer, which inflates recall, and several chunks of one document in the top k must count once, or precision counts the same document twice. Labels on chunk ids avoid the first problem but break every time you re-chunk. A sturdier choice for RAG is the one from the recall lab in the Chunking skill: label the answering passage as a span (document id plus character offsets) and count it as found when the retrieved chunks cover it; such labels survive re-chunking.

Label drift. Labels describe the corpus and the product at one moment. Articles are edited, merged and deleted; the app's minimum Android version changes; a new article answers an old query better than the labelled one; and the questions users ask move with each new feature. Each change makes some labels wrong without any error. Guard against it: keep the corpus hash in the manifest (lesson 3) and per-document hashes if you can, rerun validate.py after every corpus update, re-review the labels of documents that changed, add a sample of fresh production queries each release, and publish the result as a new version of the set instead of editing the old one.

06. Check your understanding

Practice check · 3 questions

Ranks and labels

Work from the definitions in this lesson.

Q1. Ranked results, best first: d4, d9, d2, d7, d1. The labels mark d7 and d1 as relevant. What reciprocal rank does this ranking get at a cut-off of 5?
Q2. Two rankings hold the same two relevant articles, graded 2 and 1, plus one irrelevant article. Ranking A is (grade-1 article, grade-2 article, irrelevant); ranking B is (grade-2 article, grade-1 article, irrelevant). Which metric at k = 3 tells them apart?
Q3. A new embedding model scores a lower precision@5 than the old one, but 40% of its top-5 results were never judged, against 5% of the old model's. What should you do first?
Practice only: not graded, not saved, not evidence.

07. Apply it

For your practice project:

  1. Add rank_metrics.py to your evaluation and report MRR@k and nDCG@k beside precision@k and recall@k for your two configurations. Say in one sentence which metric matches how your system uses its results, and base the decision on that one.
  2. Compute Judged@k for each run: the share of top-k results that carry any label. If one configuration is clearly lower, judge its new documents and score again.
  3. If your labels are per document but you retrieve chunks, count each document once in the top k, and open two hits to check that the retrieved chunk really contains the answer.
  4. Write a short drift plan: which events trigger a re-check of the labels, who does it, and how the new version is published.

08. Review prompt

Without looking back:

  1. Define RR, AP and nDCG in one sentence each, and say which of them uses graded labels.
  2. Compute nDCG@3 for a ranking with a grade-1 article first, a grade-2 article second and nothing else relevant.
  3. Why can unjudged documents make a better configuration look worse, and what do you check before comparing?
  4. Give two ways in which document-level labels mislead when the retriever returns chunks.
  5. Name three events that cause label drift, and one safeguard for each.

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