A 73-line Python implementation of precision and recall at $k$, average precision, reciprocal rank and nDCG reproduces this topic's hand calculations: AP 0.522 and 0.425 on the two worked queries, MAP 0.474, MRR 0.75, and nDCG 0.961 on the graded example. It averages over every topic in the qrels, divides AP by all relevant documents, counts unjudged documents as nonrelevant, and builds nDCG's ideal ranking from all judged documents. Correct code can still disagree with trec_eval. Its tie-break, by identifier descending as strings, gives a four-document tie an AP of 0.700 where the intended order gives 1.000, and changes 179 of the BIM's 225 Cranfield queries. Interpolation, unjudged documents and missing topics each admit two conventions.
The worked ranking of this topic retrieves four of its five relevant documents, at ranks 1, 3, 6 and 9, and its average precision is 0.522 by hand. Almost any program will get the same number. Real runs raise cases the formula does not settle: two documents with the same score, a topic in the judgments with no ranking at all, a retrieved document that was never judged. This article shows what correct evaluation code looks like, and the cases in which two correct programs still disagree.
The measures in this topic are short formulas, and implementing them looks trivial. Yet hand-written evaluation code is a common source of wrong results in retrieval experiments. It may divide average precision by the wrong count, or build the ideal ranking for nDCG from the wrong documents. It may break ties differently from the standard tools, or silently skip topics with no relevant documents. Each mistake changes the numbers, often in a direction that flatters the system being tested.
Here is the route. First we describe the two TREC file formats that hold judgments and rankings. Then we give a compact implementation of the main measures, as defined by Manning, Raghavan, and Schütze (2008, chapter 8), and test it against the worked examples of the other articles. Next we work small cases where the code, the textbook definitions and the standard tool trec_eval disagree. Finally we list the standard tools that make results comparable across research groups.
The TREC formats
Two plain-text formats, introduced by TREC, are the common currency of retrieval evaluation.
A qrels file holds the relevance judgments, one per line:
401 0 FBIS3-10082 1
401 0 FBIS3-10169 0
402 0 FT921-1123 2
The fields are the topic identifier, an unused iteration field (conventionally 0), the document identifier, and the relevance grade. Grades greater than zero count as relevant for binary measures.
A run file holds a system's rankings:
401 Q0 FBIS3-10082 1 14.73 mysystem
401 Q0 LA052390-0089 2 13.91 mysystem
The fields are the topic, the literal Q0, the document identifier, the rank, the score, and a name for the run.
The rank column looks authoritative, but the standard tool, trec_eval, ignores it. It orders each topic's documents by score, breaking ties by document identifier in descending order, compared as strings (National Institute of Standards and Technology, trec_eval source, form_res_rels.c). Runs whose scores contain ties can therefore be evaluated in a different order from the one their author intended, and other tools may break ties differently. The implementation below breaks ties by ascending identifier, so it orders tied documents differently from trec_eval. The safe practice is to make scores strictly decreasing, so that no tie-break is needed. A later section shows how much the tie-break can matter.
With the formats fixed, the readers and the main measures fit in the 73 lines of Python printed below, docstrings and blank lines included.
An implementation
import math
from collections import defaultdict
def read_qrels(lines):
"""TREC qrels: 'topic iteration docno relevance' per line."""
qrels = defaultdict(dict)
for line in lines:
topic, _, doc, rel = line.split()
qrels[topic][doc] = int(rel)
return qrels
def read_run(lines):
"""TREC run: 'topic Q0 docno rank score tag'. Ranked by score, ties by docno."""
scored = defaultdict(list)
for line in lines:
topic, _, doc, _, score, _ = line.split()
scored[topic].append((float(score), doc))
return {t: [d for _, d in sorted(docs, key=lambda x: (-x[0], x[1]))]
for t, docs in scored.items()}
def precision_at(ranking, judged, k):
return sum(1 for d in ranking[:k] if judged.get(d, 0) > 0) / k
def recall_at(ranking, judged, k):
relevant = sum(1 for g in judged.values() if g > 0)
return sum(1 for d in ranking[:k] if judged.get(d, 0) > 0) / relevant if relevant else 0.0
def average_precision(ranking, judged):
relevant = sum(1 for g in judged.values() if g > 0)
if relevant == 0:
return 0.0
hits, total = 0, 0.0
for k, d in enumerate(ranking, 1):
if judged.get(d, 0) > 0:
hits += 1
total += hits / k
return total / relevant # divide by all relevant, not just those retrieved
def reciprocal_rank(ranking, judged):
for k, d in enumerate(ranking, 1):
if judged.get(d, 0) > 0:
return 1 / k
return 0.0
def ndcg_at(ranking, judged, k, exponential=False):
gain = (lambda g: 2 ** max(g, 0) - 1) if exponential else (lambda g: max(g, 0)) # negative grades gain 0
dcg = sum(gain(judged.get(d, 0)) / math.log2(i + 1) for i, d in enumerate(ranking[:k], 1))
ideal = sorted(judged.values(), reverse=True)[:k]
idcg = sum(gain(g) / math.log2(i + 1) for i, g in enumerate(ideal, 1))
return dcg / idcg if idcg > 0 else 0.0
def evaluate(qrels, run, k=10):
per_topic = {}
for topic, judged in qrels.items():
ranking = run.get(topic, [])
per_topic[topic] = {
f"P@{k}": precision_at(ranking, judged, k),
f"R@{k}": recall_at(ranking, judged, k),
"AP": average_precision(ranking, judged),
"RR": reciprocal_rank(ranking, judged),
f"nDCG@{k}": ndcg_at(ranking, judged, k),
}
means = {m: sum(s[m] for s in per_topic.values()) / len(per_topic)
for m in next(iter(per_topic.values()))}
return per_topic, means
Several details in this code prevent the common mistakes:
- The topics come from the qrels, not the run. A topic the system returned nothing for still counts, with a score of zero. Iterating over the run's topics instead would silently drop failures and inflate the mean. By default, trec_eval averages only over topics that appear in both the run and the qrels; its
-coption includes the missing topics with scores of zero. - Average precision divides by every relevant document in the qrels, including those never retrieved, as explained in mean average precision.
- Unjudged documents count as nonrelevant, through
judged.get(d, 0). This is the standard convention, with the consequences discussed in relevance judgments, pooling, and agreement. - The ideal ranking for nDCG uses all judged documents for the topic, not only the retrieved ones, as explained in nDCG.
- A negative grade counts as gain 0 in nDCG. Some judgment files use a negative code for a judged document that is not relevant, such as the −1 entries of Cranfield described in test collections. The binary measures already treat any grade that is not above 0 as nonrelevant, and
ndcg_atgives such a grade a gain of 0, so that it can never subtract from the score. - Topics with no relevant documents score zero for recall, AP, and nDCG. Some tools skip them instead. Whichever convention is used should be stated, because it changes the mean.
Testing against the worked examples
The code reproduces the hand calculations of the other articles. Two example queries serve as the test:
- the worked ranking of evaluating ranked results, with relevant documents at ranks 1, 3, 6 and 9, and its never-retrieved fifth relevant document included in the qrels;
- the second query of mean average precision, with three relevant documents at ranks 2, 5 and 8.
Encoded as qrels and run lines and evaluated at $k = 5$, they give:
| Topic | P@5 | R@5 | AP | RR | nDCG@5 |
|---|---|---|---|---|---|
| 1 | 0.400 | 0.400 | 0.522 | 1.000 | 0.509 |
| 2 | 0.400 | 0.667 | 0.425 | 0.500 | 0.478 |
| Mean | 0.400 | 0.533 | 0.474 | 0.750 | 0.493 |
These match the hand calculations: AP 0.522 and 0.425, MAP 0.474, and MRR 0.75. On the graded example from nDCG, ndcg_at returns 0.961 with linear gain and 0.949 with exponential gain, again matching. Tests like these, built from small cases computed by hand, are the cheapest protection against evaluation bugs, and every measure should have one.
The code above is kept, character for character, in tools/experiments/eval_measures/measures.py in the site's repository. The script worked_examples.py there checks two things: that the article's code block matches the file, and that the file reproduces the numbers of this topic's measure articles. Most are compared with a value copied from the article into the script; the worked problems of significance testing are compared with the article's own text, which the script reads.
The same file holds, after the printed block, the measures that the other articles define and this code block omits. They take a list of judgments in rank order instead of run and qrels dictionaries, and each is tested against its article's hand calculation on the worked ranking:
| Function | Measure | Value on the worked ranking |
|---|---|---|
r_precision |
R-precision (evaluating ranked results) | 0.400 |
interpolated |
interpolated precision at given recall levels | 11-point mean 0.566 |
dcg, ndcg_list |
DCG and nDCG with either gain and several discounts (nDCG) | binary nDCG@10 0.732 |
bpref |
bpref as defined by Buckley and Voorhees, bpref-10, and trec_eval's variant (relevance judgments) | 0.44; 0.64 with ranks 2 and 4 unjudged |
rbp, rbp_residual |
rank-biased precision and its residual | 0.427 and 0.107 at $p = 0.8$ |
err |
expected reciprocal rank | 0.922 on the graded example of the nDCG article |
The last two rows are measures built on an explicit model of the user, derived in user models behind retrieval metrics.
Matching the hand calculations shows the code is right on cases where everyone agrees. The harder cases are those where the definitions leave room.
Where implementations disagree
Two correct implementations of the same measure can still return different numbers, because the definitions leave some decisions open. The cases below are small enough to check by hand, and each shows a real difference between the code above, the textbook definitions, and trec_eval. The trec_eval behavior is read from its source code (National Institute of Standards and Technology, trec_eval, the files named below).
Ties in the scores
A topic has three relevant documents, 12, 10 and 7. A run scores document 12 at 3.0, documents 10, 7, 8 and 9 all at 2.0, and document 11 at 1.0. Its rank column lists the tied documents in the order 10, 7, 8, 9.
Example (string order is not numeric order). trec_eval breaks the tie by identifier in descending order, compared as strings, so of the four tied documents it puts 9 first and 10 last. As strings, 9 comes after 8, 7 and 10, because the comparison looks at the first character. Each tool sorts by score and then resolves the tie its own way:
| Tie-break | Order of the tied documents | AP | P@3 |
|---|---|---|---|
| The rank column, as the author intended | 10, 7, 8, 9 | 1.000 | 1.000 |
| trec_eval: identifier descending, as strings | 9, 8, 7, 10 | 0.700 | 0.333 |
| The code above: identifier ascending, as strings | 10, 7, 8, 9 | 1.000 | 1.000 |
| Identifier ascending, as numbers | 7, 8, 9, 10 | 0.867 | 0.667 |
Over all 24 orderings of the tied block, AP ranges from 0.700 to 1.000. The order of four tied documents alone moves AP by as much as 0.3.
Is that a curiosity, or does it happen on a real collection? It depends on how often a model produces ties. The Binary Independence Model without relevance information scores a document by summing a weight for each query term it contains. All documents containing the same query terms therefore tie. On Cranfield, 121 of the 225 queries have a tie within the BIM's top ten. BM25 and TF-IDF use term frequencies and document lengths, which almost never coincide exactly.
| Model | MAP, ties by ascending number (as in comparing ranking models) | MAP, ties by ascending string (the code above) | MAP, trec_eval's tie-break | Queries whose AP differs between the first and third |
|---|---|---|---|---|
| BIM | 0.2204 | 0.2184 | 0.2182 | 179 |
| TF-IDF | 0.2942 | 0.2942 | 0.2942 | 0 |
| BM25 | 0.3066 | 0.3066 | 0.3065 | 8 |
The means barely move, because the per-query changes go both ways and largely cancel. But individual queries change by up to 0.321. A significance test works on the per-query values, so it sees those changes in full. A run with heavy ties should therefore do one of two things:
- break them deliberately, for example by adding a tiny decreasing amount to the scores in the intended order;
- or be reported with the tie-break stated.
A retrieval engine meets the same question when it chooses its top $k$. Dynamic Pruning with MaxScore and WAND fixes a tie rule, decreasing score and then increasing document identifier, so that its proof that pruning returns exactly the top $k$ still holds when scores tie.
Interpolated precision at recall levels
The textbook definition takes interpolated precision at recall level $r$ as the maximum precision at any recall of at least $r$. trec_eval's iprec_at_recall works differently (m_iprec_at_recall.c). It turns each level into a number of relevant documents, rounding $r \times R$ to the nearest integer. Then it takes the maximum precision from the rank of that relevant document onward.
When $R = 5$, as in the first worked query, the two agree at all eleven levels, since every level times 5 rounds to the right count. When $R = 3$ they need not. For the second worked query, with relevant documents at ranks 2, 5 and 8:
| Recall level | 0.0 to 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1.0 | 11-point mean |
|---|---|---|---|---|---|---|---|---|---|
| Textbook | 0.500 | 0.400 | 0.400 | 0.400 | 0.375 | 0.375 | 0.375 | 0.375 | 0.427 |
| trec_eval | 0.500 | 0.500 | 0.400 | 0.400 | 0.400 | 0.400 | 0.375 | 0.375 | 0.441 |
At level 0.4, the textbook needs recall of at least 0.4, which the query first reaches with its second relevant document (recall 0.667, at rank 5, precision 0.4). trec_eval rounds $0.4 \times 3 = 1.2$ to 1 and starts from the first relevant document (rank 2, precision 0.5). At 0.7 and 0.8 the same rounding, $2.1$ and $2.4$ to 2, uses the second relevant document instead of the third. The difference is small and systematic: trec_eval's curve is never below the textbook's.
Unjudged documents
The code above, like trec_eval by default, counts an unjudged document as nonrelevant. trec_eval's -J option instead removes unjudged documents from the ranking before computing anything. Its documentation warns against using it without care. Suppose the documents at ranks 2 and 4 of the first worked query had never been judged:
| Treatment of the unjudged documents | AP | P@5 |
|---|---|---|
| As nonrelevant (default) | 0.522 | 0.400 |
Removed from the ranking (-J) |
0.664 | 0.600 |
Removing them closes the gaps, so the relevant documents at ranks 3, 6 and 9 move up to 2, 4 and 7. Neither number is the true value, which depends on whether the two documents are relevant. The first treats ignorance as failure, the second as if the documents did not exist. Measures designed for this situation are described in relevance judgments, pooling, and agreement.
Topics missing from the run
Example (a topic the run omits). The qrels have three topics, and the run has rankings for only the two worked queries. trec_eval reports a MAP of 0.474 by default, and the code above reports 0.316. trec_eval by default averages over the two topics it has, giving MAP $(0.522 + 0.425)/2 = 0.474$. With -c it averages over all three, scoring the missing topic 0, and MAP is $0.947/3 = 0.316$. The code above always does the latter, because it iterates over the qrels. A system that crashes on a third of the topics should not be able to keep its score by producing no output for them.
GMAP and zero scores
The geometric mean is undefined when a topic has AP of zero. trec_eval's gm_map replaces each AP by the larger of it and 0.00001 before taking logarithms (m_gm_map.c), while other tools add a small constant to every value. The MAP article explains why the floor matters.
A checklist of conventions
| Decision | The code above | trec_eval default |
|---|---|---|
| Order of documents | by score, ties by identifier ascending | by score, ties by identifier descending (as strings) |
| Topics averaged | all topics in the qrels | topics in both qrels and run (-c for all) |
| Unjudged documents | nonrelevant | nonrelevant (-J removes them) |
| Relevant | grade greater than 0 | grade at least 1 (-l changes the threshold) |
| AP denominator | all relevant documents in the qrels | the same |
| nDCG gain and discount | grade (a negative grade as 0), $1/\log_2(i + 1)$ | grade (configurable), $1/\log_2(i + 1)$ |
| nDCG ideal ranking | all judged documents | the same |
| Ranking depth | everything in the run | everything in the run (-M limits it) |
Standard tools
Every one of these differences is a reason to prefer a shared tool. For published results, standard tools are preferable to custom code, because reviewers and other researchers can reproduce the numbers exactly.
- trec_eval, maintained by NIST, is the reference implementation used in TREC. It reads qrels and run files and reports dozens of measures, per topic or averaged.
- pytrec_eval gives Python programs direct access to trec_eval's implementation, without writing files or calling an external program (Van Gysel and de Rijke, 2018).
- ir_measures provides one interface to measures from several implementations, with measures named precisely, for example
nDCG@10orP(rel=2)@5, so that the exact variant used is recorded with the result (MacAvaney, Macdonald, and Ounis, 2022).
Even with standard tools, these should all be reported:
- the measure variant and the cutoff;
- the treatment of unjudged documents and of topics with no relevant documents;
- the version of the qrels.
Two papers can both report "nDCG@10" for the same collection and mean different things.
Putting it together
A complete offline evaluation follows these steps:
- Run each system on the test topics and write a run file.
- Compute per-topic measures for each run against the qrels.
- Report the means, the cutoffs, and the measure variants.
- Compare systems with a paired significance test over the per-topic scores.
- Check how many top-ranked documents were unjudged.
The per-topic scores from step 2 are the input to the significance tests. That is one reason evaluation code should always produce them, not only the means. Evaluating Embedding Models follows these steps for two embedding models on Cranfield and on this site, reporting recall at a cutoff and nDCG@10 with intervals and paired tests.
Worked problems
The problems below are posed on this article's code and cases; the course text sets no exercises on implementation. Each answer is produced by running the code, in the reference-pass block of tools/experiments/eval_measures/worked_examples.py.
Problem 1 (what evaluate returns at a different cutoff). The second worked query has three relevant documents, at ranks 2, 5 and 8 of ten results. Give the five values that evaluate returns for it with k=3, by hand.
Solution. P@3 = 0.333, R@3 = 0.333, AP = 0.425, RR = 0.500 and nDCG@3 = 0.296. The top three results hold one relevant document, at rank 2, so precision_at returns $1/3$ and recall_at returns $1/3$ as well, because the query also has three relevant documents. AP and RR do not depend on $k$: AP is $(1/2 + 2/5 + 3/8)/3 = 0.425$ and RR is $1/2$. For nDCG@3 the gain is the grade, 1 for each relevant document. The DCG of the top three is $1/\log_2 3 = 0.631$. The ideal ranking, built from all the judged documents, has relevant documents at ranks 1, 2 and 3, with DCG $1 + 0.631 + 0.5 = 2.131$. So nDCG@3 $= 0.631/2.131 = 0.296$.
Problem 2 (the two interpolation rules with four relevant documents). A query has $R = 4$ relevant documents, retrieved at ranks 1, 4, 5 and 10 of ten results. Compute the interpolated precision at the eleven standard recall levels by the textbook's definition and by trec_eval's rule, and the two 11-point means.
Solution. The textbook's values have mean 0.655 and trec_eval's 0.709; they differ at recall 0.3 and 0.8. The four relevant documents give the points (recall, precision) $= (0.25, 1)$, $(0.5, 0.5)$, $(0.75, 0.6)$ and $(1, 0.4)$.
| Recall level | 0.0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1.0 | Mean |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Textbook | 1 | 1 | 1 | 0.6 | 0.6 | 0.6 | 0.6 | 0.6 | 0.4 | 0.4 | 0.4 | 0.655 |
| trec_eval | 1 | 1 | 1 | 1 | 0.6 | 0.6 | 0.6 | 0.6 | 0.6 | 0.4 | 0.4 | 0.709 |
Textbook. For a level up to 0.25, every point qualifies and the largest precision is 1. For a level above 0.25 and up to 0.75, the points at recall 0.5, 0.75 and 1 qualify, and the largest precision among them is 0.6. (The point at recall 0.5 has precision 0.5, lower than the one after it; interpolation passes over it.) Above 0.75 only the last point qualifies, with 0.4.
trec_eval. Each level is turned into a count of relevant documents, $\text{level} \times 4$ rounded to the nearest integer: 0, 0, 1, 1, 2, 2, 2, 3, 3, 4, 4 for the eleven levels. The value is the largest precision from that relevant document onward: 1 for counts 0 and 1, 0.6 for counts 2 and 3, and 0.4 for count 4. Level 0.3 becomes $1.2 \to 1$, so trec_eval starts from the first relevant document where the textbook, needing recall of at least 0.3, starts from the second. Level 0.8 becomes $3.2 \to 3$, where the textbook needs all four. As in the article's example, trec_eval's values are never below the textbook's: where the product rounds down, trec_eval asks for less recall than the level, and where it rounds up, it asks for the same number of relevant documents as the textbook does.
Problem 3 (a zero in the geometric mean). Three topics have average precisions 0.522, 0.425 and 0. Compute MAP, and GMAP with trec_eval's floor of 0.00001.
Solution. MAP is 0.316 and GMAP is 0.013. MAP is $(0.522 + 0.425 + 0)/3 = 0.316$. For GMAP the zero is replaced by 0.00001, and the geometric mean of three values is the cube root of their product: $(0.522 \times 0.425 \times 0.00001)^{1/3} = (2.22 \times 10^{-6})^{1/3} = 0.013$. One failed topic takes a third off MAP and divides GMAP by 36, from the 0.471 of the two successful topics. The result depends on the floor: with a floor of 0.001 instead, the same data give $(2.22 \times 10^{-4})^{1/3} = 0.061$. A GMAP is therefore comparable only with others computed with the same floor.
Problem 4 (the average over all ways of breaking a tie). In the tie example above, the four documents 10, 7, 8 and 9 share a score, and 10 and 7 are relevant. If the tie were broken uniformly at random, find the possible values of AP and its expected value.
Solution. AP takes six values between 0.700 and 1.000, and its expected value is 0.841. The tied block occupies ranks 2 to 5, after the relevant document 12 at rank 1, and $R = 3$. Only the two ranks at which the relevant documents of the block fall matter, and there are $\binom{4}{2} = 6$ choices, each arising from 4 of the 24 orderings:
| Ranks of the two relevant documents | AP |
|---|---|
| 2, 3 | $(1 + 1 + 1)/3 = 1.000$ |
| 2, 4 | $(1 + 1 + 3/4)/3 = 0.917$ |
| 2, 5 | $(1 + 1 + 3/5)/3 = 0.867$ |
| 3, 4 | $(1 + 2/3 + 3/4)/3 = 0.806$ |
| 3, 5 | $(1 + 2/3 + 3/5)/3 = 0.756$ |
| 4, 5 | $(1 + 2/4 + 3/5)/3 = 0.700$ |
The six are equally likely, so the expected AP is their mean, $5.044/6 = 0.841$. The rank column's order scores 1.000 and trec_eval's order 0.700, the two extremes; neither is the value a tie-neutral evaluation would report.
What we have learned
The 73 printed lines of Python reproduce the hand calculations of precision and recall at $k$, average precision, reciprocal rank and nDCG in this topic, and the rest of measures.py (197 lines in all) covers the other measures. Correct code can still disagree with trec_eval: tie-breaking moves the AP of a four-document tie between 0.700 and 1.000 and changes 179 of the BIM's 225 Cranfield queries. Interpolation, unjudged documents and missing topics each admit two conventions, and the one used should be stated.
This topic has asked only how to score rankings. The next asks how to produce a good one, by estimating each document's probability of relevance. Probabilistic Retrieval begins with Probability for Information Retrieval.
References
- MacAvaney, S., Macdonald, C., and Ounis, I. (2022). Streamlining evaluation with ir-measures. In Proceedings of ECIR 2022, 305–310. record
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, chapter 8. Cambridge University Press. record · 102 pages
- National Institute of Standards and Technology. trec_eval. https://github.com/usnistgov/trec_eval record · 4 pages
- Van Gysel, C., and de Rijke, M. (2018). Pytrec_eval: An extremely fast Python interface to trec_eval. In Proceedings of SIGIR 2018, 873–876. record
Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 9 revisions