AI Wiki中文/EN

Retrieval metrics: which ranking deserves the higher score?

检索指标

Calculate precision, recall, AP, reciprocal rank and nDCG, then expose the conventions hidden by an average.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two good documents, four different questions

Consider an invented search task with two known relevant documents: a has grade 3, b has grade 1, and c has grade 0. A search engine returns a, u, b, c. Document u has not been judged. At a cutoff of two results, how good is this ranking?

If the question is “how many of the first two slots are relevant?”, the answer under an unjudged-as-zero scoring convention is 1/2. If it is “how many known relevant documents did we find in those slots?”, it is also 1/2, but for a different reason. A reader looking for one usable answer finds it immediately. A reader collecting every useful source must continue to rank three. Graded evaluation adds another distinction: the grade-3 document contributes more gain than the grade-1 document.

These are different objectives, not competing spellings of accuracy. A test collection must specify the information needs, document collection and relevance judgments before its scores mean anything. Relevance concerns the need, rather than merely matching the query’s words. The IIR evaluation chapter explains that setup; relevance judgments examines how its labels are obtained. This article holds a judgment table fixed and works through the arithmetic.

A fixed judgment table gives different answers for different objectives; gain conventions and query weights are explicit.
A fixed judgment table gives different answers for different objectives; gain conventions and query weights are explicit.

Write the denominator before calculating the score

For one query, let the supplied ranking contain n distinct document IDs. A judgment table, often called qrels, maps assessed documents to nonnegative grades. The implementation treats grade 1 or higher as binary relevance. Missing judgments receive zero for calculation, but remain listed as missing. Write R for the number of known relevant documents in the whole judgment table, including documents that were never retrieved:

ri=1[g(di)≥1],R=∑d∈J1[g(d)≥1].r_i=\mathbf{1}[g(d_i)\geq 1],\qquad R=\sum_{d\in J}\mathbf{1}[g(d)\geq 1].

Here J is the set of judged documents. A positive cutoff k describes slots, not the length of whatever list happened to be returned. With h_k relevant hits in the first k positions:

hk=∑i=1min⁡(k,n)ri,P@k=hkk,Recall⁡@k=hkR(R>0).h_k=\sum_{i=1}^{\min(k,n)}r_i,\qquad P@k=\frac{h_k}{k},\qquad \operatorname{Recall}@k=\frac{h_k}{R}\quad(R>0).

Returning one relevant document when k=3 earns precision 1/3, even if it is the only result returned. Returning the same document twice is rejected; it cannot create another relevant item. Recall is measured against known judgments. If relevant documents are missing from those judgments, this is not recall against an omniscient inventory.

AP credits every relevant discovery

Average precision, AP, adds precision at each rank where a relevant document appears, then divides by R. It does not divide by the number of relevant documents successfully returned. For this article, AP uses the entire supplied ranking; the cutoff k only affects the explicitly cutoff metrics. MAP is the mean AP across a declared query set. These denominator and averaging conventions follow the IIR chapter’s discussion of AP and MAP.

AP⁡=1R∑i=1nri∑j=1irji,MAP⁡=1∣Q+∣∑q∈Q+AP⁡q.\operatorname{AP}=\frac{1}{R}\sum_{i=1}^{n}r_i\frac{\sum_{j=1}^{i}r_j}{i},\qquad \operatorname{MAP}=\frac{1}{|Q_+|}\sum_{q\in Q_+}\operatorname{AP}_q.

For a, u, b, c, relevant ranks are 1 and 3. AP is (1 + 2/3)/2 = 5/6, approximately 0.833333. If only a is returned, AP becomes 1/2. The absent b still belongs in the denominator. Here Q_+ contains queries with at least one known relevant document; the program reports its size. This explicit exclusion is our zero-denominator policy, not a claim that every evaluation package uses it.

Reciprocal rank stops caring after the first hit

Let i* be the first relevant position. Reciprocal rank, RR, is its reciprocal; no hit in the supplied list gives zero. MRR averages RR over all declared queries, including empty runs. The fixed trec_eval metric file describes the first-hit objective. It does not measure how well later relevant documents are ordered.

RR⁡={1/i∗,a relevant result is returned,0,otherwise,MRR⁡=1∣Q∣∑q∈QRR⁡q.\operatorname{RR}=\begin{cases}1/i^*,&\text{a relevant result is returned},\\0,&\text{otherwise},\end{cases}\qquad \operatorname{MRR}=\frac{1}{|Q|}\sum_{q\in Q}\operatorname{RR}_q.

Our example has RR 1. So does a ranking that returns a first and never retrieves b. That invariance is appropriate for a first-success question and unhelpful for an exhaustive-search question. An evaluation truncated at a retrieval depth can only observe success within that depth.

DCG needs both a gain and a discount

Discounted cumulative gain assigns a value to a relevance grade and reduces its contribution at later positions. The implementation uses the IIR chapter’s exponential gain with a shifted logarithmic discount. IDCG is the DCG of the best ordering of all known judged grades at the same cutoff, not just the grades returned by this engine:

DCG⁡@k=∑i=1min⁡(k,n)2g(di)−1log⁡2(i+1),IDCG⁡@k=max⁡π over JDCG⁡@k(π),nDCG⁡@k=DCG⁡@kIDCG⁡@k.\operatorname{DCG}@k=\sum_{i=1}^{\min(k,n)}\frac{2^{g(d_i)}-1}{\log_2(i+1)},\qquad \operatorname{IDCG}@k=\max_{\pi\text{ over }J}\operatorname{DCG}@k(\pi),\qquad \operatorname{nDCG}@k=\frac{\operatorname{DCG}@k}{\operatorname{IDCG}@k}.

The ratio requires positive IDCG. Sorting known grades in descending order constructs the ideal: a larger gain assigned to a larger discount weight can only increase or preserve the sum. Thus valid distinct-document rankings have nDCG between zero and one under these assumptions. IIR, physical PDF page 13 gives this gain/discount combination.

For the first two results a, u, DCG is 7, IDCG is 7 + 1/log2(3), and nDCG is approximately 0.917319. If we instead return b, a, binary precision is 1 but nDCG falls to about 0.709810: the most valuable document arrives second. Changing to linear gain while retaining the shifted discount gives about 0.796708 for that same reversed ranking. Both numbers are reproducible; they answer differently weighted questions.

Do not attribute every modern formula to the original report. Järvelin and Kekäläinen’s 2002 research note uses a different construction: with logarithm base 2, the first grade is undiscounted and subsequent grades are divided by the logarithm of their rank. Written for a nonempty list and cutoff:

DCG⁡RN2002@k=g(d1)+∑i=2min⁡(k,n)g(di)log⁡2i.\operatorname{DCG}_{\mathrm{RN2002}}@k=g(d_1)+\sum_{i=2}^{\min(k,n)}\frac{g(d_i)}{\log_2 i}.

This also leaves rank two undiscounted. It differs from replacing exponential gain with linear gain in the preceding formula, because the logarithm’s argument changes too. Our program implements the preceding shifted-discount family, not this report variant. State the gain, discount, ideal-ranking construction and cutoff whenever comparing implementations.

An average also chooses whom to weight

Add a second query with five known relevant documents, of which only one appears in its first two results. Its recall is 1/5; query A’s is 1/2. An equal-query average and an average weighted by the number of relevant documents are:

Recall⁡macro=1∣Q+∣∑q∈Q+hq,kRq=0.35,Recall⁡micro=∑qhq,k∑qRq=27.\operatorname{Recall}_{\mathrm{macro}}=\frac{1}{|Q_+|}\sum_{q\in Q_+}\frac{h_{q,k}}{R_q}=0.35,\qquad \operatorname{Recall}_{\mathrm{micro}}=\frac{\sum_q h_{q,k}}{\sum_q R_q}=\frac{2}{7}.

Macro recall gives each eligible query equal influence. Micro recall gives larger influence to queries with more known relevant documents. Neither transformation leaves the question unchanged. Our second query returns its one hit first and no other relevant document, so its AP is 0.2. MAP across the two queries is 31/60, about 0.516667, while MRR remains 1.

A complete evaluator with visible policies

Save the following original program as metrics.py and run it with Python 3.12 or later. It uses only the standard library and synthetic document IDs. Grades are integers from 0 to 30; this is an implementation bound, not a universal relevance scale. ranked sorts descending scores and breaks exact ties by document ID. The evaluator accepts an already ordered list and preserves it.

"""Original ranked-retrieval example. Python 3.12+, standard library only."""
import json
import math


def validate(run, qrels, k):
    if type(k) is not int or k < 1:
        raise ValueError('k must be a positive integer')
    if any(not isinstance(d, str) or not d for d in run):
        raise ValueError('document IDs must be nonempty strings')
    if len(set(run)) != len(run):
        raise ValueError('duplicate document ID')
    for d, grade in qrels.items():
        if not isinstance(d, str) or not d or type(grade) is not int or not 0 <= grade <= 30:
            raise ValueError('grades must be integers in [0, 30] with string IDs')


def ranked(scores):
    if any(not isinstance(d, str) or not d for d in scores):
        raise ValueError('document IDs must be nonempty strings')
    if any(not math.isfinite(s) for s in scores.values()):
        raise ValueError('scores must be finite')
    return sorted(scores, key=lambda d: (-scores[d], d))


def evaluate(run, qrels, k, gain='exponential', unjudged='zero'):
    run = list(run)
    validate(run, qrels, k)
    if gain not in ('exponential', 'linear') or unjudged not in ('zero', 'error'):
        raise ValueError('unsupported gain or unjudged policy')
    missing = [d for d in run if d not in qrels]
    if missing and unjudged == 'error':
        raise ValueError('unjudged documents: ' + ', '.join(missing))
    grades = [qrels.get(d, 0) for d in run]
    relevant = sum(g > 0 for g in qrels.values())
    hits = sum(g > 0 for g in grades[:k])
    seen, ap_sum, rr = 0, 0.0, 0.0
    for position, grade in enumerate(grades, 1):
        if grade > 0:
            seen += 1
            ap_sum += seen / position
            if rr == 0:
                rr = 1 / position
    def dcg(values):
        return sum(((2**g - 1) if gain == 'exponential' else g) / math.log2(i + 1)
                   for i, g in enumerate(values[:k], 1))
    actual = dcg(grades)
    ideal = dcg(sorted(qrels.values(), reverse=True))
    n = min(k, len(run))
    return dict(precision=hits/k, recall=hits/relevant if relevant else None,
                ap=ap_sum/relevant if relevant else None, rr=rr,
                dcg=actual, idcg=ideal, ndcg=actual/ideal if ideal else None,
                relevant=relevant, hits=hits, returned_at_k=n,
                judged_at_k=sum(d in qrels for d in run[:k]),
                judged_fraction=sum(d in qrels for d in run[:k])/n if n else None,
                unjudged=missing)


def aggregate(runs, qrels, k):
    if set(runs) - set(qrels):
        raise ValueError('run contains a query outside the declared evaluation set')
    # Missing runs are empty; the declared query set is never silently reduced.
    rows = [evaluate(runs.get(q, []), labels, k) for q, labels in qrels.items()]
    eligible = [r for r in rows if r['relevant']]
    def mean(values):
        return sum(values)/len(values) if values else None
    total = sum(r['relevant'] for r in rows)
    return dict(queries=len(rows), queries_with_relevant=len(eligible),
                map=mean([r['ap'] for r in eligible]),
                macro_recall=mean([r['recall'] for r in eligible]),
                micro_recall=sum(r['hits'] for r in rows)/total if total else None,
                mrr=mean([r['rr'] for r in rows]))


def demo():
    a = {'a': 3, 'b': 1, 'c': 0}
    b = {'d': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1, 'z': 0}
    runs = {'A': ['a', 'u', 'b', 'c'], 'B': ['d', 'z']}
    return dict(query_a=evaluate(runs['A'], a, 2), query_b=evaluate(runs['B'], b, 2),
                aggregate=aggregate(runs, {'A': a, 'B': b}, 2),
                reversed_exponential=evaluate(['b', 'a'], a, 2),
                reversed_linear=evaluate(['b', 'a'], a, 2, gain='linear'),
                tie_order=ranked({'b': 1.0, 'a': 1.0, 'c': 0.0}),
                no_relevant=evaluate(['x'], {'x': 0}, 2))


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, allow_nan=False))

The JSON output reproduces the hand calculations above. judged_fraction divides assessed documents by the number of actual results in the first k positions; an empty list returns null. That diagnostic therefore uses a different denominator from precision. unjudged records missing IDs across the supplied ranking. Setting unjudged='error' rejects them instead of assigning zero gain.

When R=0, recall and AP return null; when IDCG is zero, nDCG returns null. RR remains zero if there is no relevant hit. Aggregation excludes undefined AP and recall while reporting the eligible count; MRR includes every declared query. A missing run becomes an empty ranking, and a run for an undeclared query is rejected. These decisions prevent a system from improving its average merely by omitting difficult queries with known positives.

For n returned and m judged documents, expected dictionary/set operations and the full sort used here cost O(n + m log m) time and O(n + m) auxiliary space. Sorting scores beforehand adds O(n log n). This transparent small-data implementation does not optimize top-k selection or load a large external collection.

A precise number can still answer the wrong question

The judgment table determines both which returned documents count and which documents enter ideal rankings and denominators. A missing positive can reduce measured gain, yet removing positives from a denominator can move other metrics upward. Report judgment coverage and inspect missing documents before interpreting score changes. The companion judgment experiment isolates that effect.

Exact ties also matter. ID-based tie breaking is reproducible, but an arbitrary identifier can decide who occupies the last evaluated slot. It is not an expected score under all possible tie orders. Preserve the policy when comparing systems, or explicitly study sensitivity to alternative tie handling.

An aggregate from two invented queries is arithmetic practice, not evidence that a retrieval method generalizes. Keep tuning queries separate from final evaluation, as the IIR chapter explains. Real comparisons also need per-query behavior, uncertainty and a task-appropriate success definition. Neither MAP nor nDCG measures factual correctness of a generated answer, response latency, or the cost of an unsafe result by itself.

Change one assumption at a time

  1. Explain a denominator. Two relevant documents are known, but the run contains only one relevant document at rank 1. Why is AP 0.5 rather than 1?

    Answer: The numerator contains one precision contribution of 1. The denominator is the two known relevant documents. The unretrieved positive contributes no precision term, but is not removed from the target set.

  2. Calculate a different order. Use the initial grades and the run u, b, a, c. What are P@2, recall@2, AP and RR under the zero policy?

    Answer: P@2 and recall@2 are both 0.5. Relevant ranks are 2 and 3, so AP is (1/2 + 2/3)/2 = 7/12, approximately 0.583333. RR is 1/2. The unjudged document remains unknown even though it contributes zero to these calculations.

  3. Test a failure condition. Change the run to a, a, b. Should silently counting both copies be acceptable? What if a system returns no results for query B?

    Answer: Repeated IDs can count the same known positive twice and invalidate the interpretation; this program rejects them. Empty query-B results remain in the declared query set: their AP and recall are zero because B has known positives, and their RR is zero. They must not disappear from the average.

  4. Choose an evaluation design. A search tool helps users find one official troubleshooting procedure; a different tool gathers a reading list covering many relevant sources. Which metrics would you inspect, and what must accompany them?

    Answer: RR can describe how soon the first useful procedure appears, with a rubric that actually requires an official usable procedure. Recall and AP help describe how many relevant reading-list documents are found and how early. Graded nDCG can distinguish levels of usefulness in either task. Report the cutoff, relevance threshold, gain/discount, judgment coverage and query set; the metric name alone does not encode the user’s need.

Read formulas together with their evaluation protocol

The IIR chapter connects test collections to AP/MAP and a common exponential-gain nDCG formulation. The Tampere research note shows the earlier gain curves, position discount and normalization against an ideal derived from the relevant-document base. Its title and version are kept distinct from the authors’ journal article. The pinned trec_eval RR file makes the first-hit objective concrete.

Read these alongside model evaluation and information retrieval. The program here is an original teaching implementation with declared edge cases, not a compatibility replacement for trec_eval or a reproduction of an empirical benchmark. Inspect the metric configuration and query accounting when moving a result between tools.

Make a prediction, then check

Two known relevant documents exist, but only one is returned at rank 1. What is AP under the full relevant-count denominator?

Choose one answer

Learning objectives

  • Compute ranked metrics from an explicit judgment table and explain their denominators.
  • Compare gain conventions, query weights, missing judgments and zero-relevance policies without changing the question silently.

Prerequisites & connections

Explore related knowledge →

References

  1. Introduction to Information Retrieval — Chapter 8, April 2009 online draft
    Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2009
  2. Cumulated gain-based indicators of IR performance — Research Notes RN 2002·2
    Kalervo Järvelin; Jaana Kekäläinen · 2002
  3. trec_eval reciprocal rank — fixed source file
    Chris Buckley; NIST trec_eval contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Read physical PDF1 opening and PDF2–3,9–10,13 text; viewed PDF13. Information needs, collection separation, AP/MAP and exponential-gain nDCG. No whole-book review or reuse of exercises. Read PDF1 identity and PDF6–10 text; viewed PDF6. Original rank-log discount, recall-base ideal and normalization. This is the Tampere research note, not a claim to have read the differently titled ACM journal article; no numerical benchmark reproduction. Read the complete short metric file at ba38899cbd4de0fb699b47f39b64ef1c107e4a5c: first relevant result and reciprocal position. Read repository README opening 150 lines and complete LICENSE.md. File header retains a noncommercial notice while root license differs; linked only, no code copied or executed. 7 paired equations and four explained exercises. Checked AP against independent rank enumeration and ideal DCG against all 24 permutations; hand calculations for gain conventions, missing positives, query weights, zero denominators, duplicates, finite scores, ties and absent runs. Original standard-library evaluator, not trec_eval compatibility or an empirical benchmark.

  • Checked AP against independent rank enumeration and ideal DCG against all 24 permutations; hand calculations for gain conventions, missing positives, query weights, zero denominators, duplicates, finite scores, ties and absent runs. Original standard-library evaluator, not trec_eval compatibility or an empirical benchmark.
  • Four computed SVG variants per topic;9 numeric/geometry tests and12 responsive cases passed. Four selected current captures visually checked: two identical to viewed images and two re-viewed final captures; title and paragraph-wrap revisions retained. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.