Skip to content

Unit 8 · BM25 and Probabilistic Retrieval

3 h contact · 6 h self study Prerequisites: Unit 7 CLO 5

1. Setting the scene

Scenario: The keyword stuffed report

The TF·IDF ranking goes live. Within a week, complaints arrive:

  • For parking permit, a 300 page traffic master plan (which mentions parking 400 times in passing) outranks the one page "How to apply for a parking permit" guide.
  • A citizen services page that repeats "permit permit permit" in its metadata climbs to the top.
  • A document containing both query words ranks below one that repeats only one of them.

TF·IDF rewards repetition linearly and has no principled notion of probably relevant. We need a better ranking function.

Guiding questions

  1. Why is retrieval inherently uncertain?
  2. Should the 50th occurrence of a word add as much as the 1st?
  3. How should document length be treated: ignored, fully normalised, or something in between?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 8.1 Explain sources of uncertainty in IR and the Probability Ranking Principle. UNDERSTAND 5
ILO 8.2 Identify the three components of BM25 and the role of \(k_1\) and \(b\). UNDERSTAND 5
ILO 8.3 Compute BM25 scores by hand for a small collection. APPLY 5
ILO 8.4 Compare TF·IDF and BM25 rankings and justify which is preferable. EVALUATE 5

3. Why probabilities?

Retrieval is uncertain at every step:

flowchart TB
    N["User information need"] -->|"uncertain: did the user phrase it well?"| Q["Query"]
    Q -->|"uncertain: did we represent it well?"| QR["Query representation"]
    C["Document collection"] -->|"uncertain: is the representation adequate?"| DR["Document representation"]
    QR --> M{"Relevant?"}
    DR --> M
  • We are unsure the user mapped their need into a good query.
  • We are unsure our representations of query and documents capture meaning.
  • We are unsure whether a given document is relevant.

Probability theory is the standard framework for reasoning under uncertainty.

4. The Probability Ranking Principle (PRP)

Treat relevance as a binary random variable \(R \in \{0, 1\}\) and estimate, for each document,

\[ P(R = 1 \mid d, q) \]

Probability Ranking Principle

If documents are ranked in decreasing order of their probability of relevance, the ranking is optimal (under the assumptions that relevance of each document is independent and the costs of errors are uniform).

Worked example

Query machine learning for healthcare; the system estimates \(P(R{=}1 \mid d_1, q) = 0.85\), \(P(R{=}1 \mid d_2, q) = 0.60\), \(P(R{=}1 \mid d_3, q) = 0.20\) → rank \(d_1 > d_2 > d_3\).

How do we estimate these probabilities? Both query and document consist of terms; more matching, important terms → higher probability of relevance.

flowchart TB
    PIR["Probabilistic IR"] --> CL["Classic models<br/>BIM · <b>BM25</b>"]
    PIR --> LM["Language models<br/>query likelihood"]
    PIR --> BN["Bayesian networks<br/>inference networks"]

Among the oldest models: and still among the best performing and most widely used.

5. From the Binary Independence Model to BM25

The Binary Independence Model (BIM) represents documents as binary term vectors. Two problems:

  1. Binary: one occurrence and ten occurrences look the same.
  2. Length blind: long documents contain more words by chance.

We need a model that rewards term frequency, but not infinitely, and adjusts for document length. That model is BM25 ("Best Match 25", Robertson & Spärck Jones and colleagues, Okapi system, 1990s). It is the default ranking function in Apache Lucene, Elasticsearch and OpenSearch and the standard lexical baseline in research.

Where the IDF in BM25 comes from

The BIM ranks documents by the log odds of relevance. For each query term \(t\) let \(p_t = P(t \in d \mid R = 1)\) and \(u_t = P(t \in d \mid R = 0)\). The retrieval status value sums over the query terms present in the document:

\[ \text{RSV}(d) = \sum_{t \in q \cap d} \log \frac{p_t\,(1 - u_t)}{u_t\,(1 - p_t)} \]

Without relevance judgements we assume \(p_t = 0.5\) and estimate \(u_t \approx \mathrm{df}_t / N\) (almost every document is non relevant). Then

\[ \log \frac{p_t\,(1 - u_t)}{u_t\,(1 - p_t)} = \log \frac{1 - u_t}{u_t} \approx \log \frac{N - \mathrm{df}_t}{\mathrm{df}_t} \approx \log \frac{N}{\mathrm{df}_t} \]

This is IDF. The ranking principle of Section 4 therefore derives the IDF weight that Unit 7 introduced as a heuristic. BM25 keeps this IDF and adds the TF and length components.

BM25 in three sentences

  1. Rare words matter more. transformer (in 5 documents) says more than neural (in 900).
  2. More occurrences help: but not infinitely. 5 occurrences beat 1; 50 are not 10× better than 5.
  3. Long documents shouldn't cheat. A 2,000 word chapter matches more words by chance than a 300 word post.
flowchart LR
    A["Rare word?<br/>IDF"] --> F["BM25 score"]
    B["Many times?<br/>saturating TF"] --> F
    C["Too long?<br/>length normalisation"] --> F

6. The formula

\[ \mathrm{BM25}(D, Q) = \sum_{t \in Q} \mathrm{IDF}(t) \cdot \frac{f_{t,D}\,(k_1 + 1)}{f_{t,D} + k_1 \left(1 - b + b \,\dfrac{|D|}{\mathrm{avgdl}}\right)} \]
Symbol Meaning
\(f_{t,D}\) frequency of term \(t\) in document \(D\)
\(\lvert D\rvert\), avgdl length of \(D\); average document length
\(k_1\) repetition knob: how fast TF saturates (typical 1.2 to 2.0; we use 1.5)
\(b\) length knob: 0 = ignore length, 1 = full normalisation (typical 0.75)
\(\mathrm{IDF}(t)\) rarity; in class \(\log(N / n_t)\)

Part 1, IDF: rare words matter more. Part 2, TF component: repetition helps with saturation. Part 3, length correction: the denominator grows for longer than average documents.

Connection to Unit 7

\(1 - b + b\,\lvert D\rvert/\mathrm{avgdl}\) is exactly pivoted length normalisation with the average document length as pivot and \(b\) as slope \(s\).

Saturation: what \(k_1\) does

With \(b = 0\) (or \(\lvert D\rvert = \mathrm{avgdl}\)) and \(k_1 = 1.5\), the TF component is \(\dfrac{2.5 f}{f + 1.5}\):

\(f\) 1 2 3 5 10 50
TF component 1.00 1.43 1.67 1.92 2.17 2.43

It can never exceed \(k_1 + 1 = 2.5\). Keyword stuffing buys almost nothing. Small \(k_1\) → repetition matters little; large \(k_1\) → behaves more like raw TF.

The same saturation for three values of \(k_1\):

xychart-beta
    title "BM25 TF component (k1 + 1) f / (k1 + f)"
    x-axis "Occurrences f" [0, 1, 2, 3, 4, 5, 6, 8, 10]
    y-axis "TF component" 0 --> 3
    line [0, 1.0, 1.2, 1.29, 1.33, 1.36, 1.38, 1.41, 1.43]
    line [0, 1.0, 1.38, 1.57, 1.69, 1.77, 1.83, 1.91, 1.96]
    line [0, 1.0, 1.5, 1.8, 2.0, 2.14, 2.25, 2.4, 2.5]

From bottom to top: \(k_1 = 0.5\), \(1.2\), \(2.0\). Each curve flattens towards its ceiling \(k_1 + 1\).

What \(b\) does

The denominator multiplies \(k_1\) by the length factor \(1 - b + b \cdot \frac{\lvert D \rvert}{\mathrm{avgdl}}\):

\(\lvert D \rvert / \mathrm{avgdl}\) 0.5 1 1.5 2 3
\(b = 0\) 1.00 1.00 1.00 1.00 1.00
\(b = 0.75\) 0.62 1.00 1.38 1.75 2.50
\(b = 1\) 0.50 1.00 1.50 2.00 3.00

A document three times longer than average behaves, at \(b = 0.75\), as if \(k_1\) were 2.5 times larger, so each occurrence counts for less.

7. Worked example: TF·IDF vs. BM25

Collection (\(N = 3\)): D1 data mining techniques · D2 data data data analysis · D3 mining methods and models. Query: data mining.

Step 1: term frequencies

data mining
D1 1 1
D2 3 0
D3 0 1

Step 2: IDF. Both terms appear in 2 of 3 documents: \(\mathrm{IDF} = \ln(3/2) \approx 0.4\).

Step 3: TF·IDF scores

Doc Score
D1 \(1 \times 0.4 + 1 \times 0.4 = 0.8\)
D2 \(3 \times 0.4 = \mathbf{1.2}\)
D3 \(1 \times 0.4 = 0.4\)

TF·IDF ranking: D2 > D1 > D3.

Step 4: BM25 (\(k_1 = 1.5\); first assume equal lengths): TF component 1.00 for \(f=1\) and 1.67 for \(f=3\).

Doc Score
D1 \(1.00 \times 0.4 + 1.00 \times 0.4 = \mathbf{0.80}\)
D2 \(1.67 \times 0.4 = 0.67\)
D3 \(1.00 \times 0.4 = 0.40\)

BM25 ranking: D1 > D2 > D3.

Insight

D1 matches both query words; D2 repeats only one. Because BM25 saturates term frequency, coverage of the query beats repetition, which is what users want.

Step 5: now with real lengths (\(b = 0.75\); after stopword removal lengths are 3, 4, 3; avgdl ≈ 3.33): D1 0.85 · D2 0.64 · D3 0.43. D2 is the longest document and is pushed down a little further.

import math
from collections import Counter

docs = {"D1": "data mining techniques".split(),
        "D2": "data data data analysis".split(),
        "D3": "mining methods models".split()}          # 'and' removed as stopword
N = len(docs)
avgdl = sum(len(d) for d in docs.values()) / N

def idf(term):
    n = sum(term in d for d in docs.values())
    return math.log(N / n)

def bm25(query, doc, k1=1.5, b=0.75):
    tf, score = Counter(doc), 0.0
    for t in query:
        f = tf[t]
        if f:
            norm = k1 * (1 - b + b * len(doc) / avgdl)
            score += idf(t) * f * (k1 + 1) / (f + norm)
    return score

q = ["data", "mining"]
for b in (0.0, 0.75):
    print(f"b={b}:", {d: round(bm25(q, toks, b=b), 2) for d, toks in docs.items()})
# b=0.0:  {'D1': 0.81, 'D2': 0.68, 'D3': 0.41}
# b=0.75: {'D1': 0.85, 'D2': 0.64, 'D3': 0.43}
from rank_bm25 import BM25Okapi

corpus = [d.split() for d in ["data mining techniques",
                              "data data data analysis",
                              "mining methods models"]]
bm25 = BM25Okapi(corpus, k1=1.5, b=0.75)
print(bm25.get_scores(["data", "mining"]))

Libraries use a smoothed IDF, e.g. Lucene's \(\ln\!\left(1 + \frac{N - n_t + 0.5}{n_t + 0.5}\right)\), which never becomes negative for very common terms. Absolute scores differ from the hand calculation; rankings are what to compare.

8. TF·IDF vs. BM25

TF·IDF BM25
Rare words important ✔ ✔
More frequency helps ✔ linearly (or log) ✔ with saturation (\(\le k_1 + 1\))
Document length separate step (cosine / pivot) built in via \(b\)
Theoretical basis heuristic, geometric probabilistic (derived from BIM + two Poisson ideas)
Tunable weighting scheme choice \(k_1\), \(b\)
In practice teaching, feature engineering default in Lucene / Elasticsearch / OpenSearch; strong baseline even against neural models

9. Classwork: tune the knobs

Explore k₁ and b (20 min)

Using the Python code above:

  1. Set \(b = 0\) and vary \(k_1 \in \{0, 0.5, 1.5, 5, 100\}\). When does D2 overtake D1? Explain what \(k_1 = 0\) and \(k_1 \to \infty\) mean.
  2. Add D4 = D1 repeated five times (data mining techniques ×5). Compare its score with D1 for \(b = 0\) and \(b = 1\).
Discussion
  1. \(k_1 = 0\): the TF component is 1 whenever the term occurs: a binary model. As \(k_1 \to \infty\) the TF component approaches raw TF, so BM25 behaves like TF·IDF and D2 overtakes D1 (for \(b = 0\) this happens around \(k_1 = 3\)).
  2. With \(b = 0\), D4 scores almost twice as high as D1 (more occurrences, no length penalty). With \(b = 1\), D4's frequencies and its length both scale by 5 and cancel out: D4 scores exactly the same as D1, copies of the same content should not be more relevant. (Adding D4 also changes the IDFs, so recompute D1 too.)

10. Check your understanding

What is the maximum contribution a single query term can make to BM25 (per document)?

\(\mathrm{IDF}(t) \cdot (k_1 + 1)\), approached as \(f_{t,D} \to \infty\).

Which parameter would you raise for a collection of very uneven document lengths, and why?

\(b\) (towards 1): stronger length normalisation stops long documents from accumulating matches by chance.

Why did BM25 prefer D1 while TF·IDF preferred D2?

TF·IDF lets three occurrences of data triple the score; BM25 saturates them (1.67 instead of 3), so D1's coverage of both terms wins.

11. Key takeaways

  • Retrieval is uncertain; the PRP says: rank by \(P(\text{relevant} \mid d, q)\).
  • BM25 = IDF × saturating TF × length normalisation.
  • \(k_1\) controls repetition, \(b\) controls length; typical values \(k_1 \approx 1.2 \text{ to } 2\), \(b = 0.75\).
  • BM25 favours query coverage over repetition and remains the industry standard lexical ranker.

If you choose BM25, implement the formula yourself, report your \(k_1\) and \(b\), and include a small sensitivity analysis (how rankings change with the parameters) in your evaluation section, alongside Precision/Recall or a qualitative analysis.

Further reading

  • Robertson & Zaragoza (2009), The Probabilistic Relevance Framework: BM25 and Beyond, Foundations and Trends in IR 3(4).
  • Manning, Raghavan & Schütze, Introduction to IR, ch. 11.