Module contents
Lesson 16 of 31Core 90 min

Lexical retrieval: inverted indexes, TF-IDF and BM25

Build an inverted index, derive BM25 from probability ranking and probabilistic relevance, study frequency saturation and length normalization, and implement ranking metrics using relevance judgments.

After this lesson you can

  • Build an inverted index and evaluate queries by accumulating term scores with a top-k heap.
  • Derive BM25 IDF from the Robertson and Spärck Jones weight without relevance judgments.
  • Explain k1 and b in frequency saturation and length normalization and tune them on a custom corpus.
  • Implement precision and recall at k, MRR, MAP, and nDCG from relevance judgments and calculate query intervals.
  • Evaluate BM25 on a BEIR dataset and compare with published values.

Before you start

Finding evidence

A system answering with external documents cannot cite a passage it has not retrieved. An error identifier, formula, or exact protein name illustrates queries where literal matching matters. Lexical search does not itself understand synonyms, but lets us inspect why a document was retrieved and offers a baseline worth measuring before replacing it.

Repeating a word should not increase its contribution indefinitely: ten occurrences usually add less evidence than the first. At the same time, an occurrence in a long document may be less specific than in a short one.

InteractiveHow much is a repeated word worth?
  • Short: half the mean
  • Average
  • Long: twice the mean
  • Linear TF
1.2
0.75
BM25 / IDF limit2.20
Long, frequency 4 / IDF1.44
Adjust k1 and b. Compare lengths half, equal to, and twice the mean. The dashed line is linear TF; all curves assume IDF one.

With b=0b=0 the length difference disappears. With b>0b>0, at equal frequency the long document scores lower. The limit of BM25 curves is k1+1k_1+1: repetition does not provide unlimited evidence. The figure represents this lesson’s formula, not experimental data.

From text to candidates

An inverted index associates each term with a list of document-frequency pairs, its postings. Build it by applying the same tokenization and normalization to documents and queries: otherwise a visible match may disappear. The index is a term table whose entries point to lists; it can also store positions for phrases and metadata.

InteractiveBuild and query the index
Indexed documents: 10/10
D1: sol luna sol
D2: luna mar
D3: sol mar
D4: estrella sol
D5: mar ola
D6: luna estrella
D7: sol ola
D8: estrella mar
D9: ola luna
D10: sol sol mar
Postings (document, frequency)
estrella: D4 (1), D6 (1), D8 (1)
luna: D1 (1), D2 (1), D6 (1), D9 (1)
mar: D2 (1), D3 (1), D5 (1), D8 (1), D10 (1)
ola: D5 (1), D7 (1), D9 (1)
sol: D1 (2), D3 (1), D4 (1), D7 (1), D10 (2)
Provisional top 3
1. D10: 3
2. D1: 2
3. D3: 2

Heap (root first): D3:2, D1:2, D10:3. Each candidate competes with the root.

22
Postings visited10
Document-term pairs in scan20
Step through the ten documents and then the terms “sol” and “mar”. Compare postings visits with document-term pairs from a full scan.

The figure scores by summing frequencies so you can follow each accumulation. A real index can store frequencies and compute BM25 at query time. Process each query term and add its contribution in a per-document accumulator. Then traverse candidates with a min-heap of size kk: replace the minimum if the next candidate exceeds it. With CC candidates, selection costs O(Clog⁡k)O(C\log k) and requires O(k)O(k) additional space beyond accumulators. Ties need a stable criterion.

The counters compare distinct operations: postings visits versus document-term pairs examined by a naive scan. They are not timings. A very common term may have a list almost as long as the corpus; the index does not guarantee identical speedup for every query.

The starting point is the bag of words: it omits order and represents each document by frequencies. In TF-IDF, the weight of a frequent document term combines with higher IDF for rare terms. Cosine similarity divides the inner product by query and document norms, measuring direction and removing global vector scale. BM25 uses different normalization and saturation; it is not TF-IDF cosine.

From probability to weight

The probability ranking principle proposes ordering by relevance probability for a query when decisions have equal cost and the criterion favors placing relevant items earlier. It does not claim BM25 computes calibrated probabilities. For example, under additive utility weighting earlier positions more, swapping two misordered documents improves expected utility if the higher-probability document moves up.

Let YY be binary relevance, xtx_t presence of term tt, pt=P(xt=1∣Y=1)p_t=\Pr(x_t=1\given Y=1), and ut=P(xt=1∣Y=0)u_t=\Pr(x_t=1\given Y=0). Assuming conditional independence of presences given YY and probabilities strictly between zero and one, Bayes’ theorem turns posterior probabilities into a sum of log ratios:

log⁡P(Y=1∣x)P(Y=0∣x)=log⁡P(Y=1)P(Y=0)+∑t[xtlog⁡ptut+(1−xt)log⁡1−pt1−ut].\log\frac{\Pr(Y=1\given\vb{x})}{\Pr(Y=0\given\vb{x})} =\log\frac{\Pr(Y=1)}{\Pr(Y=0)} +\sum_t\left[x_t\log\frac{p_t}{u_t} +(1-x_t)\log\frac{1-p_t}{1-u_t}\right].

Taking the all-terms-absent case as reference, its sum is constant across documents. The additional contribution of each presence is

wt=log⁡pt(1−ut)ut(1−pt).w_t=\log\frac{p_t(1-u_t)}{u_t(1-p_t)}.

If there are NN documents, ntn_t contain the term, RR are relevant, and rtr_t relevant documents contain it, smoothing by half a document per cell gives

p^t=rt+0.5R+1,u^t=nt−rt+0.5N−R+1.\hat p_t=\frac{r_t+0.5}{R+1},\qquad \hat u_t=\frac{n_t-r_t+0.5}{N-R+1}.

Estimated odds among relevant documents are (rt+0.5)/(R−rt+0.5)(r_t+0.5)/(R-r_t+0.5) and among nonrelevant documents (nt−rt+0.5)/(N−nt−R+rt+0.5)(n_t-r_t+0.5)/(N-n_t-R+r_t+0.5). Their ratio gives the Robertson and Spärck Jones weight:

wt=log⁡(rt+0.5)(N−nt−R+rt+0.5)(R−rt+0.5)(nt−rt+0.5).w_t=\log\frac{(r_t+0.5)(N-n_t-R+r_t+0.5)} {(R-r_t+0.5)(n_t-r_t+0.5)}.

Without known judgments, R=rt=0R=r_t=0, leaving log⁡((N−nt+0.5)/(nt+0.5))\log((N-n_t+0.5)/(n_t+0.5)). This IDF can be negative for terms present in more than half the collection. Many implementations modify it, for example using log⁡(1+(N−nt+0.5)/(nt+0.5))\log(1+(N-n_t+0.5)/(n_t+0.5)), which is positive. The variant matters for reproducibility. The framework and approximations are developed by Robertson and Zaragoza; frequency saturation and length are practical extensions, not exact consequences of binary independence.

BM25 and its parameters

The BM25 score for a query with distinct terms, without additional query-frequency weighting, is

s(d,q)=∑t∈qIDF⁡(t)ftd(k1+1)ftd+k1(1−b+b∣d∣/∣d∣‾).s(d,q)=\sum_{t\in q}\operatorname{IDF}(t) \frac{f_{td}(k_1+1)} {f_{td}+k_1(1-b+b|d|/\overline{|d|})}.

Here ftdf_{td} is document frequency, ∣d∣|d| its token length, and ∣d∣‾\overline{|d|} the corpus mean. We use k1>0k_1>0 and 0≤b≤10\le b\le1. For f=0f=0 contribution is zero. At fixed length, the derivative with respect to ff is positive and decreases with ff when IDF is positive; the limit is IDF⁡(t)(k1+1)\operatorname{IDF}(t)(k_1+1). A larger k1k_1 delays saturation. Parameter bb interpolates between no length correction and full relative-length correction. Negative IDF reverses the interpretation of a “reward”: another reason to declare the variant.

To see this algebraically, write K=k1(1−b+b∣d∣/∣d∣‾)K=k_1(1-b+b|d|/\overline{|d|}). With K>0K>0, the frequency-factor derivative with respect to ff is (k1+1)K/(f+K)2(k_1+1)K/(f+K)^2: positive and decreasing. Half the limit is reached at f=Kf=K, so KK gives a concrete saturation scale. Increasing bb for a longer-than-average document increases KK and reduces its fixed-frequency score. For a shorter document the opposite occurs; at average length it is unchanged.

The figure’s corpus has ten documents, mean length 2.2, and five documents contain “sol”; five also contain “mar”. With this lesson’s positive IDF, each term weighs log⁡2\log 2. For k1=1.2k_1=1.2 and b=0.75b=0.75, document D10 (“sol sol mar”) gets approximately 0.8646 for “sol” and 0.6034 for “mar”, totaling 1.4680. D3 (“sol mar”) gets 0.7199 for each term, totaling 1.4398. D10 wins by repeating “sol” despite being longer. Both scores follow from the formula, and the next cell computes ordering without rounding.

Judgments and per-query metrics

A set of relevance judgments (qrels) assigns binary or graded labels to query-document pairs. Because judging the whole collection may be infeasible, candidates from several systems form a pool and that subset is judged. An unjudged document is not necessarily irrelevant: treating it as zero is a convention that may favor systems represented in the pool.

Ranking metrics answer different questions. Let rir_i be relevance at position ii, Ii=1[ri>0]I_i=\ind[r_i>0], and RqR_q the total number of judged relevant documents for the query.

P@k=∑i=1kIik,R@k=∑i=1kIiRq,RR=1min⁡{i:Ii=1}.P@k=\frac{\sum_{i=1}^k I_i}{k},\quad R@k=\frac{\sum_{i=1}^k I_i}{R_q},\quad RR=\frac{1}{\min\{i:I_i=1\}}.

If no relevant document appears, RR=0RR=0. Average precision APAP sums P@iP@i at each relevant position and divides by RqR_q; MAP averages AP over queries. Dividing by all judged relevant documents, including unretrieved ones, penalizes omissions. Discounted cumulative gain uses gain function gg and rewards high grades near the top:

DCG@k=∑i=1kg(ri)log⁡2(i+1),nDCG@k=DCG@kIDCG@k.DCG@k=\sum_{i=1}^k\frac{g(r_i)}{\log_2(i+1)},\qquad nDCG@k=\frac{DCG@k}{IDCG@k}.

IDCGIDCG orders judgments by descending gain, not just retrieved documents. Here we use g(r)=rg(r)=r unless stated otherwise; 2r−12^r-1 is also used. If no relevant documents are judged, recall and nDCG have no informative denominator: state whether the query is excluded or assigned zero. Rankings must not repeat documents.

For example, with grades (3,0,2,0,1)(3,0,2,0,1) at depth five there are three relevant documents: P@5=3/5P@5=3/5 and R@5=1R@5=1. The first relevant document is at position one, so RR=1RR=1 even if the other two fall much lower. Average precision distinguishes their positions: (1+2/3+3/5)/3(1+2/3+3/5)/3. With linear gain, nDCG also distinguishes grade 3 from grade 1. An aggregate metric can hide improvement coming only from easy queries; retain individual metrics to inspect wins and losses.

InteractiveFive documents, five metrics
  1. Relevance 0 · within cutoff
  2. Relevance 3 · within cutoff
  3. Relevance 0 · within cutoff
  4. Relevance 2 · within cutoff
  5. Relevance 1 · within cutoff
2
5
P@k0.600
R@k1.000
MRR0.500
Full AP0.533
Linear nDCG@k0.660
Select a position and use Up or Down. Vary k: MRR depends only on the first relevant document, while nDCG distinguishes grades and positions.

MRR averages RRRR over queries. The figure shows RRRR for one query, so it equals its MRR. Its AP uses the full ranking, while P, recall, and nDCG use the selected cutoff.

Lab: sparse index and metrics

This artificial corpus checks arithmetic and traversal, not domain quality. Python indices start at zero. We build a sparse document-term matrix, its transpose to query postings, and the positive IDF above. Tuning queries are separated from the final query: with so few queries selection is illustrative and does not reliably estimate generalization.

[ ]Index and BM25 from scratchBrowser
import re, heapq
import numpy as np
from scipy.sparse import csr_matrix

docs = ["sol luna sol", "luna mar", "sol mar", "estrella sol",
        "mar ola", "luna estrella", "sol ola", "estrella mar",
        "ola luna", "sol sol mar"]
def tokenize(s):
    return re.findall(r"\w+", s.lower())
tokens = [tokenize(d) for d in docs]
vocab = {t: j for j, t in enumerate(sorted(set(sum(tokens, []))))}
rows, cols, vals = [], [], []
for i, doc in enumerate(tokens):
    for t in set(doc):
        rows.append(i); cols.append(vocab[t]); vals.append(doc.count(t))
X = csr_matrix((vals, (rows, cols)), shape=(len(docs), len(vocab)))
post = X.tocsc()
lengths = np.asarray(X.sum(axis=1)).ravel()
df = np.asarray((X > 0).sum(axis=0)).ravel()
idf = np.log1p((len(docs) - df + 0.5) / (df + 0.5))

def scores(query, k1=1.2, b=0.75):
    acc = {}
    for t in set(tokenize(query)):
        if t not in vocab: continue
        j = vocab[t]
        for p in range(post.indptr[j], post.indptr[j + 1]):
            i, f = int(post.indices[p]), float(post.data[p])
            v = idf[j] * f * (k1 + 1) / (f + k1 * (1-b+b*lengths[i]/lengths.mean()))
            acc[i] = acc.get(i, 0.0) + v
    return acc

def topk(acc, k):
    # El desempate favorece al índice menor.
    h = []
    for i, s in acc.items():
        item = (s, -i)
        if len(h) < k: heapq.heappush(h, item)
        elif item > h[0]: heapq.heapreplace(h, item)
    return [-i for s, i in sorted(h, reverse=True)]

print("vocabulario:", vocab)
print("top 3 sol mar:", topk(scores("sol mar"), 3))
print("D10 sol, mar, total; D3 total:", scores("sol")[9], scores("mar")[9], scores("sol mar")[9], scores("sol mar")[2])
assert topk({0: 1., 1: 2., 2: 2.}, 2) == [1, 2]
[ ]Metrics, manual cases, and tuningBrowser
import math

def metrics(ranking, qrels, k):
    assert len(set(ranking)) == len(ranking)
    rel = sum(v > 0 for v in qrels.values())
    hits = 0
    ap_sum = 0.
    rr = 0.
    for i, d in enumerate(ranking, 1):
        if qrels.get(d, 0) > 0:
            hits += 1
            ap_sum += hits / i
            if rr == 0: rr = 1 / i
    h = sum(qrels.get(d, 0) > 0 for d in ranking[:k])
    gain = lambda xs: sum(v / math.log2(i + 2) for i, v in enumerate(xs[:k]))
    ideal = gain(sorted(qrels.values(), reverse=True))
    return {"p": h / k, "recall": h / rel if rel else 0.,
            "rr": rr, "ap": ap_sum / rel if rel else 0.,
            "ndcg": gain([qrels.get(d, 0) for d in ranking]) / ideal if ideal else 0.}

qrels = {0: 3, 1: 0, 2: 2, 3: 0, 4: 1}
m = metrics([0, 1, 2, 3, 4], qrels, 5)
print("ejemplo:", m)
assert abs(m["ndcg"] - 0.9212478445981336) < 1e-12
assert abs(m["ap"] - (1 + 2/3 + 3/5)/3) < 1e-12

train = [("sol", {0: 1, 2: 1, 9: 1}), ("luna", {1: 1, 5: 1, 8: 1})]
test = ("mar ola", {4: 1, 9: 1})
grid = [(a, b) for a in (0.5, 1.2, 2.0) for b in (0., 0.75, 1.)]
def mean_ndcg(pairs, a, b):
    return np.mean([metrics(topk(scores(q, a, b), len(docs)), rel, 3)["ndcg"] for q, rel in pairs])
best = max(grid, key=lambda p: (mean_ndcg(train, *p), -p[0], -p[1]))
print("par elegido:", best, "ajuste:", round(mean_ndcg(train, *best), 4),
      "consulta retenida:", round(mean_ndcg([test], *best), 4))

ID tie-breaking is part of the protocol. The index returns only documents sharing a term; filling positions with zero-scoring documents is another choice to fix before comparison. The example treats unjudged documents as zero and assigns zero when none are judged relevant.

The grid picks the best pair using two tuning queries. Its result is not an unbiased estimate: the held-out query only shows that the function supports separate evaluation. In a real study, reserve test queries before designing the grid and fix metric, tokenization, and tie-breaking. A query split can still share documents between tuning and test; state whether that is the intended use.

To measure costs, the next control compares sparse accumulation with a full matrix scan. The corpus is too small for a performance conclusion: constants, implementation, and environment determine the winner. Do not treat these timings as universal algorithm properties.

[ ]Compare sparse traversal and full scanBrowser
import time
def dense_scores(query, k1=1.2, b=0.75):
    values = np.zeros(len(docs))
    dense = X.toarray()
    for t in set(tokenize(query)):
        if t not in vocab: continue
        j = vocab[t]
        f = dense[:, j]
        values += idf[j] * f * (k1+1) / (f+k1*(1-b+b*lengths/lengths.mean()))
    return values
query = "sol mar"
sp = scores(query)
de = dense_scores(query)
assert np.allclose([sp.get(i, 0.) for i in range(len(docs))], de)
for name, fn in [("postings y montículo", lambda: topk(scores(query), 3)),
                 ("denso y ordenación", lambda: np.argsort(-dense_scores(query))[:3])]:
    start = time.perf_counter()
    for _ in range(100):
        fn()
    print(name, "segundos para 100 consultas:", time.perf_counter()-start)

Comparing while preserving queries

For two systems, calculate dq=mq(A)−mq(B)d_q=m_q(A)-m_q(B) on the same queries and average. Paired comparison preserves that some queries are hard for both. A paired bootstrap resamples complete queries with replacement, calculates each sample mean, and takes percentiles; it does not resample documents as though they were independent queries. An interval describes variation under that query sampling, not incomplete judgments or test leakage.

BEIR collects heterogeneous tasks and domains for evaluating retrieval without in-domain tuning. In table 2 of the original BEIR paper, BM25 obtains nDCG@10 of 0.665 on SciFact. This is a published result for its configuration, not a measurement from our lab. Tokenization, corpus version, parameters, and evaluation convention can change the figure. Comparing a custom variant with it helps detect discrepancies but does not prove reproduction when protocols differ.

Local lab: BEIR SciFact

The cell downloads the official SciFact file and uses rank_bm25 in a temporary folder. It requires connectivity and local Python with NumPy and requests; it installs a specific library version in that folder without changing the environment. It evaluates all test-split queries with judgments. Both variants use the same tokens, parameters, library IDF, and tie-breaking: the comparison checks implementation, not two independent systems. The library uses RSJ IDF with negative values replaced by a fraction of mean IDF; this differs from the small cell’s positive IDF and the paper’s analyzer. Therefore do not expect to reproduce 0.665 exactly.

[ ]SciFact: implementation and libraryLocal GPU
import sys, subprocess, tempfile, zipfile, json, csv, re, math
from pathlib import Path
from collections import defaultdict, Counter
import numpy as np
import requests

with tempfile.TemporaryDirectory() as tmp:
    tmp = Path(tmp)
    subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "--no-deps",
                    "--target", str(tmp / "packages"), "rank_bm25==0.2.2"], check=True)
    sys.path.insert(0, str(tmp / "packages"))
    from rank_bm25 import BM25Okapi
    url = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip"
    response = requests.get(url, timeout=90)
    response.raise_for_status()
    archive = tmp / "scifact.zip"
    archive.write_bytes(response.content)
    with zipfile.ZipFile(archive) as z:
        z.extractall(tmp)
    root = tmp / "scifact"
    def jsonlines(path):
        with path.open(encoding="utf-8") as f:
            return [json.loads(line) for line in f]
    corpus = jsonlines(root / "corpus.jsonl")
    queries = {x["_id"]: x["text"] for x in jsonlines(root / "queries.jsonl")}
    qrels = defaultdict(dict)
    with (root / "qrels" / "test.tsv").open(encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f, delimiter="\t"):
            qrels[row["query-id"]][row["corpus-id"]] = int(row["score"])
    ids = [x["_id"] for x in corpus]
    def words(s):
        return re.findall(r"\w+", s.lower())
    tokens = [words(x.get("title", "") + " " + x["text"]) for x in corpus]
    model = BM25Okapi(tokens, k1=1.2, b=0.75)
    no_length = BM25Okapi(tokens, k1=1.2, b=0.0)
    postings = defaultdict(list)
    for i, ts in enumerate(tokens):
        for term, freq in Counter(ts).items():
            postings[term].append((i, freq))
    lengths = np.array([len(ts) for ts in tokens])
    def own_scores(query):
        out = np.zeros(len(ids))
        for term in set(words(query)):
            for i, f in postings.get(term, []):
                out[i] += model.idf[term] * f * 2.2 / (f + 1.2 * (0.25 + 0.75 * lengths[i] / model.avgdl))
        return out
    def order(scores):
        return sorted(range(len(ids)), key=lambda i: (-scores[i], ids[i]))[:10]
    def ndcg(indices, rel):
        def dcg(rs):
            return sum(r / math.log2(i+2) for i, r in enumerate(rs[:10]))
        ideal = dcg(sorted(rel.values(), reverse=True))
        return dcg([rel.get(ids[i], 0) for i in indices]) / ideal if ideal else 0.
    ours, library, baseline = [], [], []
    for qid, rel in qrels.items():
        q = queries[qid]
        a = own_scores(q)
        b = model.get_scores(list(set(words(q))))
        assert np.allclose(a, b, rtol=1e-10, atol=1e-10)
        ours.append(ndcg(order(a), rel))
        library.append(ndcg(order(b), rel))
        baseline.append(ndcg(order(no_length.get_scores(list(set(words(q))))), rel))
    ours, library, baseline = np.array(ours), np.array(library), np.array(baseline)
    rng = np.random.default_rng(0)
    indices = rng.integers(0, len(ours), (2000, len(ours)))
    interval = np.quantile(ours[indices].mean(axis=1), [0.025, 0.975])
    diff_interval = np.quantile((ours-baseline)[indices].mean(axis=1), [0.025, 0.975])
    print("documentos y consultas:", len(ids), len(ours))
    print("nDCG@10 propia y librería:", ours.mean(), library.mean())
    print("IC bootstrap por consulta:", interval)
    print("sin normalización, nDCG@10:", baseline.mean())
    print("diferencia pareada frente a b=0 e IC:", (ours-baseline).mean(), diff_interval)
    print("referencia BEIR publicada, protocolo diferente: 0.665")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Distinguish uncertainty from reproducibility: equivalent implementations should give the same scores apart from numerical error. The paired b=0.75 versus b=0 comparison uses the same queries and resamples differences; the mean interval describes the query sample. Neither extrapolates to other domains or measures preprocessing changes. Since test was examined, this comparison is descriptive, not validated parameter selection.

Exercises

ProofFrom binary presence to IDF
Prove: Derive the RSJ weight under conditional independence and show the form without judgments.
0
For one term, p is presence probability among relevant documents and u among nonrelevant documents. All probabilities are strictly interior.

Step 1 of 2. What does a present term contribute relative to an absent one in the log likelihood ratio?

NumericPosition discount
With linear gains, calculate nDCG@5 for relevance grades (3, 0, 2, 0, 1) and ideal (3, 2, 1, 0, 0).
QuizThe effect of b
With positive IDF, fixed frequency, and document length above average, what happens as b rises from 0 to 1?
CodeLinear or exponential gain
Implement ndcg_at_k(ranking, qrels, k, exponential=False). The ranking contains unique identifiers and qrels is a dictionary of nonnegative grades. Treat unjudged documents as zero and return zero if the ideal is zero.
def ndcg_at_k(ranking, qrels, k, exponential=False):
  pass
Shift+Enter to run
CodeAccumulation and heap
Implement retrieve(postings, terms, k). Postings maps each term to (integer document, contribution) pairs; sum once per distinct term and return up to k documents ordered by descending score, with the smaller identifier first in ties. Assume positive k.
def retrieve(postings, terms, k):
  pass
Shift+Enter to run
Key idea
A reliable retriever combines an explicit representation and index with per-query evaluation: BM25 controls saturation and length, and no average replaces examination of judgments and paired differences.