Modelcore
Okapi BM25
Also called BM25, best match 25.
Scores a document by summing idf times a saturating, length-normalized term frequency, with parameters k1 and b.
Okapi BM25 scores a document for a query by adding, over the query terms that the document contains, an idf weight times a term frequency factor that saturates and is corrected for the length of the document. It came out of the Okapi system of Robertson, Walker and colleagues at City University London, and its standard form was used at TREC-3 in 1994. Two of its parts are derived, the idf from the binary independence model and the shape of the saturation from the two-Poisson model, and the rest are approximations with constants and fitted by experiment. With and it is the usual baseline of ranked retrieval.
The machine
The formula. For a query and a document in a collection of documents with average length , with natural logs,
where the sum is over distinct query terms, and a term with adds 0. Two idf forms are common:
The usual values are from 1.2 to 2.0 and (Robertson and Zaragoza 2009). For , Singhal (2001) gives values from 0 to 1000. As the query factor becomes , and makes it 1. For short queries with no repeated terms it is 1 in any case.
What is derived and what is fitted. BM25 is a family of formulas shaped by experiments, not the output of one derivation.
- The sum over terms is derived. It is the log odds of relevance under the term independence assumption of the binary independence model, ranked by the probability ranking principle.
- The idf is derived. is the Robertson-Sparck Jones weight with no relevance information, with the 0.5 corrections as a smoothing choice. It is 0 for a term in half of the documents and negative above. The Lucene form adds 1 inside the log so that it stays positive. That is an engineering choice, not a derivation.
- The saturation is an approximation. The two-Poisson weight is 0 at , increases with and has a limit. The function has the same three properties and one parameter (Robertson and Walker 1994). sets how fast it saturates: gives a 0-1 weight, and a large gives a weight almost linear in .
- The length factor is a heuristic. Under the verbosity hypothesis, a long document says the same thing with more words, so should be divided by the length. Under the scope hypothesis, it covers more topics, so the length should not matter. The slope mixes the two, exactly as in pivoted length normalization with the pivot at . BM25 divides by inside the saturation.
- The factor makes the tf part equal 1 when and . It multiplies every score by one constant and does not change the ranking, and some implementations leave it out.
- The query factor with is a saturation of the query term frequency of the same form, chosen by analogy.
Example. The toy collection of the information retrieval pages has , , every other document 10 tokens long, and . Take q1 = "sorted array search", , and the Lucene idf. The document frequencies are 4, 3 and 2, so the idf values are for "sorted", for "array" and for "search".
- For , , so , and each query term has , with tf part . The score is .
- For a document of 10 tokens, and . The tf part is for and for . Document holds "sorted" twice and "array" once, so its score is .
| rank | document | query terms with tf | Lucene idf score | RSJ idf score |
|---|---|---|---|---|
| 1 | sorted 1, array 1, search 1 | 3.0283 | 1.4604 | |
| 2 | sorted 2, array 1 | 1.8893 | 0.4497 | |
| 3 | sorted 1, array 1 | 1.6292 | 0.4497 | |
| 4 | search 1 | 1.2743 | 0.9506 | |
| 5 | sorted 1 | 0.6896 | 0.0000 |
The rank column is for the Lucene idf. With the RSJ idf, "sorted" is in exactly half of the documents and gets weight 0, so the order becomes , , , , , and ties with because only "array" counts for both. On q2 = "posting list merge" the Lucene scores are 2.6946, 2.2139, 2.2139 and 1.2743. The scores of and are equal, because "list" and "merge" both have and both documents have 10 tokens, so comes first by id. On q3 = "rank documents" only scores, with 3.5651. On q4 = "quantum circuit" no document contains a query term and the answer is empty.
Evaluation. An index stores in each posting, for each document, and and for the collection. The implementation in impl/python/bm25.py scores term at a time: line L1 computes , line L2 the tf part, line L4 adds each posting's contribution to an accumulator, and line L5 sorts by score descending and then by id ascending.
What it counts
- The score. A real number for each document that contains at least one query term. Only the order matters for the ranking. Scores of different queries are not on a common scale.
- Parameters. , and, for long queries, , tuned on judged queries. The collection statistics are , for each term and .
- Time. postings for exhaustive scoring, plus the selection of the top . Each term adds at most times its query factor, because the tf part is below . This bound lets WAND, MaxScore and block-max WAND skip documents that cannot enter the top .
- Space. One integer for each posting and one length for each document. Some engines store the lengths in a lossy form of one byte.
Relation to other models
- Binary independence model. With the tf part is 1 for every present term, and BM25 is the binary independence model with no relevance information. With judged documents, the idf can be replaced by the full Robertson-Sparck Jones weight with and , which is relevance feedback in this model.
- Two-Poisson model. The saturation stands in for the weight of the two-Poisson model, whose eliteness parameters are not known without judgments.
- Pivoted length normalization. The factor is a pivoted normalization with slope and pivot . The limits and were the Okapi weights BM15 and BM11.
- Vector space model. BM25 is an inner product of a sparse query vector and a sparse document vector, as in the vector space model, but with saturated and length-corrected document weights and no cosine.
- BM25F. For documents with fields such as title and body, BM25F combines the weighted and normalized frequencies of the fields before the saturation.
- Divergence from randomness. Amati and van Rijsbergen (2002) show that their model I(n)L2 is close to BM25 with about 1 and about 0.72; see divergence from randomness.
- Language models. The query likelihood model with Dirichlet smoothing reaches similar effectiveness from a different model, with the prior mass in the role of the length correction.
- Learned sparse retrieval. SPLADE learns the term weights of documents and queries and keeps the same sum over terms, so it runs on the same inverted index.
Known results in the model
- Variants differ little. Kamphuis, de Vries, Boytsov and Lin (2020) compare eight variants of BM25 from papers and from search engines on several test collections and find that the choice among them changes effectiveness very little.
- Limits of the parameters. At the score is a sum of idf values over the query terms present. As the tf part tends to , a raw term frequency divided by the length factor. At the length of the document has no effect.
- Long documents. For a very long document is large, and the tf part of a present term can come close to 0, about as low as the score of a document without the term. Lv and Zhai (2011) add a lower bound to the tf part, which gives BM25+.
- Negative weights. With , a query term in more than half of the documents gets a negative weight, so a document can score lower because it contains a query term. This is why engines use the Lucene form or clamp the idf at 0.
- Use. BM25 is the default similarity of Lucene and of search engines built on it, the first stage of many neural ranking pipelines, and a standard baseline in test collection experiments.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bm25/. The authors are listed in prov/T2NA0M.jsonl.
"""Okapi BM25 over a small in-memory collection.
All logs are natural logs. The score of document d for query q is
sum over distinct t in q of IDF(t) * tf (k1 + 1) / (tf + k1 (1 - b + b |d| / avgdl)) * QTF(t)
where QTF is qtf when k3 is None (k3 infinite), and (k3 + 1) qtf / (k3 + qtf) otherwise.
"""
import math
from typing import Optional
def idf_lucene(n_docs: int, df: int) -> float:
"""The idf of Lucene's BM25, ln(1 + (N - df + 0.5) / (df + 0.5)). Always positive."""
return math.log(1.0 + (n_docs - df + 0.5) / (df + 0.5))
def idf_rsj(n_docs: int, df: int) -> float:
"""The Robertson-Sparck Jones weight with no relevance information, ln((N - df + 0.5) / (df + 0.5)).
It is 0 when df = N / 2 and negative when df > N / 2.
"""
return math.log((n_docs - df + 0.5) / (df + 0.5))
IDFS = {"lucene": idf_lucene, "rsj": idf_rsj}
class BM25:
"""A BM25 index over documents given as token lists, keyed by comparable ids."""
def __init__(self, docs: dict, k1: float = 1.2, b: float = 0.75,
k3: Optional[float] = None, idf: str = "lucene") -> None:
if k1 < 0 or not 0 <= b <= 1:
raise ValueError("need k1 >= 0 and 0 <= b <= 1")
self.k1, self.b, self.k3 = k1, b, k3
self.idf_fn = IDFS[idf]
self.n_docs = len(docs)
self.length = {d: len(toks) for d, toks in docs.items()}
total = sum(self.length.values())
self.avgdl = total / self.n_docs if self.n_docs else 0.0
self.postings: dict = {} # term -> list of (doc id, tf), in increasing id order
for d in sorted(docs):
counts: dict = {}
for t in docs[d]:
counts[t] = counts.get(t, 0) + 1
for t, f in counts.items():
self.postings.setdefault(t, []).append((d, f))
def df(self, term: str) -> int:
return len(self.postings.get(term, ()))
def idf(self, term: str) -> float:
return self.idf_fn(self.n_docs, self.df(term))
def length_factor(self, doc_id) -> float:
"""B(d) = 1 - b + b |d| / avgdl, the pivoted length normalizer with slope b."""
return 1.0 - self.b + self.b * self.length[doc_id] / self.avgdl
def tf_part(self, tf: int, doc_id) -> float:
"""tf (k1 + 1) / (tf + k1 B(d)): 0 at tf = 0, increasing, and below k1 + 1."""
return tf * (self.k1 + 1.0) / (tf + self.k1 * self.length_factor(doc_id))
def qtf_part(self, qtf: int) -> float:
if self.k3 is None:
return float(qtf)
return (self.k3 + 1.0) * qtf / (self.k3 + qtf)
def rank(self, query: list, k: Optional[int] = None) -> list:
"""Documents that contain at least one query term, as (id, score) pairs.
Order: score descending, then id ascending. Term-at-a-time with one accumulator per document.
Cost: O(sum of df over the query terms) plus a sort of the matching documents.
"""
qtf: dict = {}
for t in query:
qtf[t] = qtf.get(t, 0) + 1
acc: dict = {}
for t, f in qtf.items():
plist = self.postings.get(t)
if not plist:
continue
w = self.idf(t) * self.qtf_part(f)
for d, tf in plist:
acc[d] = acc.get(d, 0.0) + w * self.tf_part(tf, d)
out = sorted(acc.items(), key=lambda p: (-p[1], p[0]))
return out if k is None else out[:k]
irtoy.py 76 lines
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.
Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""
DOCS = {
1: "binary search finds a key in a sorted array",
2: "merge sort merges two sorted runs into one sorted array",
3: "an inverted index maps each term to a posting list",
4: "a posting list is a sorted list of document ids",
5: "skip pointers speed up the merge of two posting lists",
6: "a hash table finds a key in constant expected time",
7: "search engines rank documents by a score for the query",
8: "the sorted array of ids is compressed with gap encoding",
}
N = len(DOCS)
QUERIES = {
"q1": "sorted array search",
"q2": "posting list merge",
"q3": "rank documents",
"q4": "quantum circuit",
}
# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
"q1": {1: 2, 2: 1, 8: 1},
"q2": {5: 2, 4: 1, 3: 1},
"q3": {7: 2},
"q4": {},
}
# A fixed run for the metric pages, as scores per query.
RUN = {
"q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}
def tokenize(text):
"""Lower-case words split on spaces."""
return text.lower().split()
_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}
def tf(term, doc_id):
"""Number of times term occurs in document doc_id."""
return _TOKENS[doc_id].count(term)
def df(term):
"""Number of documents that contain term."""
return sum(1 for toks in _TOKENS.values() if term in toks)
def cf(term):
"""Number of occurrences of term in the whole collection."""
return sum(toks.count(term) for toks in _TOKENS.values())
def doc_len(doc_id):
"""Number of tokens in document doc_id."""
return len(_TOKENS[doc_id])
def avgdl():
"""Average document length in tokens."""
return sum(len(toks) for toks in _TOKENS.values()) / N
test_bm25.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bm25/. The authors are listed in prov/T2NA0M.jsonl.
import math
import random
import irtoy
from bm25 import BM25, idf_lucene, idf_rsj
# Scores are compared to the 4 decimals printed on the page.
TOL4 = 5e-5
# Two ways of computing the same float sum are compared with this tolerance.
TOL = 1e-9
DOCS = {d: irtoy.tokenize(t) for d, t in irtoy.DOCS.items()}
def q(name: str) -> list:
return irtoy.tokenize(irtoy.QUERIES[name])
def close(got: list, want: list, tol: float = TOL4) -> None:
assert [d for d, _ in got] == [d for d, _ in want], (got, want)
for (_, s), (_, t) in zip(got, want):
assert abs(s - t) <= tol, (got, want)
def brute_score(docs: dict, query: list, d, k1: float, b: float, idf: str) -> float:
"""The BM25 formula written out directly, for one document, with qtf counted linearly."""
n = len(docs)
avgdl = sum(len(t) for t in docs.values()) / n
total = 0.0
for t in sorted(set(query)):
df = sum(1 for toks in docs.values() if t in toks)
tf = docs[d].count(t)
if df == 0 or tf == 0:
continue
w = math.log(1 + (n - df + 0.5) / (df + 0.5)) if idf == "lucene" else math.log((n - df + 0.5) / (df + 0.5))
big_k = k1 * (1 - b + b * len(docs[d]) / avgdl)
total += query.count(t) * w * tf * (k1 + 1) / (tf + big_k)
return total
def test_check_values_q1_lucene() -> None:
m = BM25(DOCS, k1=1.2, b=0.75)
close(m.rank(q("q1")), [(1, 3.0283), (2, 1.8893), (8, 1.6292), (7, 1.2743), (4, 0.6896)])
def test_hand_computation_of_d2() -> None:
m = BM25(DOCS)
assert abs(m.avgdl - 9.875) <= TOL
assert abs(m.length_factor(1) - 0.933544) <= 1e-6
assert abs(m.length_factor(2) - 1.009494) <= 1e-6
assert abs(m.tf_part(2, 2) - 1.370122) <= 1e-6
assert abs(m.tf_part(1, 2) - 0.994848) <= 1e-6
d2 = m.idf("sorted") * m.tf_part(2, 2) + m.idf("array") * m.tf_part(1, 2)
assert abs(d2 - 1.8893) <= TOL4
def test_rsj_idf_of_sorted_is_zero() -> None:
assert irtoy.df("sorted") == 4 and irtoy.N == 8
assert idf_rsj(8, 4) == 0.0
assert abs(idf_lucene(8, 4) - math.log(2)) <= TOL
m = BM25(DOCS, idf="rsj")
close(m.rank(q("q1")), [(1, 1.4604), (7, 0.9506), (2, 0.4497), (8, 0.4497), (4, 0.0)])
def test_rsj_idf_is_negative_above_half() -> None:
assert idf_rsj(8, 5) < 0 < idf_lucene(8, 5)
assert idf_rsj(8, 3) > 0
def test_q2_tie_broken_by_id() -> None:
got = BM25(DOCS).rank(q("q2"))
close(got, [(4, 2.6946), (3, 2.2139), (5, 2.2139), (2, 1.2743)])
assert got[1][1] == got[2][1]
assert [d for d, _ in got[1:3]] == [3, 5]
def test_q3_and_empty_q4() -> None:
close(BM25(DOCS).rank(q("q3")), [(7, 3.5651)])
assert BM25(DOCS).rank(q("q4")) == []
assert BM25(DOCS).rank([]) == []
def test_top_k_is_a_prefix() -> None:
m = BM25(DOCS)
full = m.rank(q("q1"))
for k in range(0, 7):
assert m.rank(q("q1"), k) == full[:k]
def test_saturation_bound_and_monotone_tf() -> None:
m = BM25(DOCS)
prev = 0.0
for tf in range(1, 200):
cur = m.tf_part(tf, 2)
assert prev < cur < m.k1 + 1
prev = cur
assert m.tf_part(0, 2) == 0.0
def test_b_zero_ignores_length() -> None:
docs = {1: ["x", "y"], 2: ["x"] + ["z"] * 30, 3: ["w"]}
got = BM25(docs, b=0.0).rank(["x"])
assert got[0][1] == got[1][1]
got = BM25(docs, b=0.75).rank(["x"])
assert got[0][0] == 1 and got[0][1] > got[1][1]
def test_k1_zero_is_binary() -> None:
m = BM25(DOCS, k1=0.0)
for d, s in m.rank(q("q1")):
want = sum(m.idf(t) for t in set(q("q1")) if t in DOCS[d])
assert abs(s - want) <= TOL
def test_k3_query_term_frequency() -> None:
m_lin = BM25(DOCS)
m_bin = BM25(DOCS, k3=0.0)
m_k3 = BM25(DOCS, k3=7.0)
s1 = dict(m_lin.rank(["sorted"]))
s2 = dict(m_lin.rank(["sorted", "sorted"]))
assert all(abs(s2[d] - 2 * s1[d]) <= TOL for d in s1)
assert dict(m_bin.rank(["sorted", "sorted"])) == dict(m_bin.rank(["sorted"]))
s3 = dict(m_k3.rank(["sorted", "sorted"]))
assert all(abs(s3[d] - s1[d] * 8 * 2 / 9) <= TOL for d in s1)
def test_dropping_the_k1_plus_1_factor_keeps_the_order() -> None:
m = BM25(DOCS)
for name in irtoy.QUERIES:
query = q(name)
alt = {}
for d, _ in m.rank(query):
alt[d] = sum(m.idf(t) * DOCS[d].count(t) / (DOCS[d].count(t) + m.k1 * m.length_factor(d))
for t in set(query))
order = sorted(alt, key=lambda d: (-alt[d], d))
assert order == [d for d, _ in m.rank(query)]
def test_random_collections_against_the_formula() -> None:
rng = random.Random(20261115)
vocab = [f"t{i}" for i in range(12)]
for _ in range(300):
n = rng.randint(1, 15)
ids = rng.sample(range(100), n)
docs = {d: [rng.choice(vocab[: rng.randint(1, 12)]) for _ in range(rng.randint(1, 25))] for d in ids}
k1 = rng.choice([0.0, 0.5, 1.2, 2.0])
b = rng.choice([0.0, 0.3, 0.75, 1.0])
idf = rng.choice(["lucene", "rsj"])
m = BM25(docs, k1=k1, b=b, idf=idf)
query = [rng.choice(vocab + ["absent"]) for _ in range(rng.randint(0, 5))]
got = m.rank(query)
matching = sorted(d for d in docs if any(t in docs[d] for t in query))
assert sorted(d for d, _ in got) == matching
for d, s in got:
assert abs(s - brute_score(docs, query, d, k1, b, idf)) <= TOL
keys = [(-s, d) for d, s in got]
assert keys == sorted(keys)
def test_bad_parameters() -> None:
for kw in ({"k1": -1.0}, {"b": 1.5}, {"b": -0.1}):
try:
BM25(DOCS, **kw)
except ValueError:
pass
else:
raise AssertionError(f"accepted {kw}")
References
- Stephen E. Robertson and Steve Walker, Some simple effective approximations to the 2-Poisson model for probabilistic weighted retrieval, Proceedings of SIGIR 1994, 232 to 241, the saturation function tf/(k1 + tf) as an approximation of the two-Poisson weight, the verbosity and scope hypotheses, and the length correction
- Stephen E. Robertson, Steve Walker, Susan Jones, Micheline M. Hancock-Beaulieu and Mike Gatford, Okapi at TREC-3, in D. K. Harman (ed.), Overview of the Third Text REtrieval Conference (TREC-3), NIST Special Publication 500-225, 1995, the weighting function BM25 with the parameters k1, b and k3, as used by the Okapi system in TREC-3
- Stephen Robertson and Hugo Zaragoza, The probabilistic relevance framework, BM25 and beyond, Foundations and Trends in Information Retrieval 3(4), 333 to 389, 2009, the derivation of BM25 from the binary independence model and eliteness, the meaning of k1 and b, and the usual values k1 from 1.2 to 2.0 and b equal to 0.75
- Chris Kamphuis, Arjen P. de Vries, Leonid Boytsov and Jimmy Lin, Which BM25 do you mean? A large-scale reproducibility study of scoring variants, Proceedings of ECIR 2020, Lecture Notes in Computer Science 12036, 28 to 34, eight variants of BM25 from the literature and from search engines, compared on several test collections, with small differences in effectiveness
- Yuanhua Lv and ChengXiang Zhai, Lower-bounding term frequency normalization, Proceedings of CIKM 2011, 7 to 16, the lower bound delta added to the term frequency part of BM25 for very long documents
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 11, Section 11.4.3 (Okapi BM25, a non-binary model)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag T2NA0M Edit this page History Report an error Markdown