BM25: repeated words help, but not without limit
BM25
Inspect term-frequency saturation, length normalization and explicit IDF conventions.
bm25How much should the third cable count?
One invented record says “repair bicycle brake cable.” Another appends cable twice. The second contains more evidence for a query about cable, but should repetition triple its contribution? A third record could mention cable twice inside a long unrelated document. Frequency alone cannot express these differences.
BM25 is a lexical ranking family combining term rarity, saturating within-document frequency and a document-length adjustment. Robertson and Zaragoza explain the saturation and length-normalization choices, including variants rather than one immutable formula. The name is not a calibrated probability of relevance. BM25 framework
Declare the variant before comparing scores
Let f be a term’s count in a document, L its analyzed token length and average L the collection’s mean length. A soft length factor interpolates between no normalization and proportional normalization:
Our term-frequency factor uses a common numerator convention. Missing terms contribute zero, handled before division in the code:
With b=0, length does not matter. With k1=0, every present term has factor one, regardless of frequency. For fixed positive K=k1B(L), the gain from additional frequency shrinks, and the algebraic saturation limit is k1+1. Treating f as continuous makes the mechanism visible:
The limit holds with K fixed; actual token counts cannot exceed a fixed document length. The plotted experiment uses only valid counts from zero to twenty in a twenty-token document. It illustrates diminishing gains without pretending impossible count/length combinations are real documents.
For term t, df_t counts documents containing it. We use a positive IDF form documented by Lucene 9.12.3, with N counting nonempty fields in this fixture:
That API also documents defaults k1=1.2 and b=0.75. They are the demonstration settings, not universally optimal values. Our exact Python lengths do not reproduce Lucene’s complete scoring and norm representation. BM25Similarity
The query is treated as a set of terms; repeating a query term has no extra effect in this variant. Sum its term contributions:
An alternative unsmoothed-inside-the-log form can be negative when a term occurs in more than half the documents:
Do not compare implementations without checking their IDF, numerator, query-frequency and length conventions. Multiplying all terms by the same k1+1 preserves ranking for fixed parameters but changes score scale; changing the IDF can change relative contributions.
A score you can decompose term by term
Run with Python 3.12 and the standard library. The nine original records include one empty record. Corpus statistics count eight nonempty fields and 34 tokens, so average length is 4.25. Empty records receive score zero. The analyzer retains lowercase ASCII letter sequences with no stemming.
import json,math,re
from collections import Counter,defaultdict
DOCUMENTS=(
'repair bicycle brake cable',
'bicycle brake adjustment guide',
'bicycle paint blue frame',
'car brake cable repair',
'cycle stopping wire replacement',
'repair bicycle brake cable cable cable',
'',
'brake cable bicycle repair',
'cell cycle stopping research',
)
def tokens(text):
if not isinstance(text,str) or len(text)>2000:raise ValueError('text of at most2000 characters required')
return re.findall(r'[a-z]+',text.lower())
def corpus(documents):
if not isinstance(documents,(list,tuple)) or not 1<=len(documents)<=100:raise ValueError('one to100 documents required')
return [tokens(d) for d in documents]
def stats(documents=DOCUMENTS):
rows=corpus(documents);counts=[Counter(ts) for ts in rows];nonempty=sum(bool(c) for c in counts);df=Counter(t for c in counts for t in c);lengths=[sum(c.values()) for c in counts]
return dict(counts=counts,df=df,n=nonempty,lengths=lengths,average=sum(lengths)/nonempty if nonempty else 0.)
def idf(n,df,positive=True):
if type(n) is not int or type(df) is not int or not 1<=df<=n:raise ValueError('1<=df<=n required')
ratio=(n-df+.5)/(df+.5)
return math.log1p(ratio) if positive else math.log(ratio)
def factor(tf,length,average,k1=1.2,b=.75):
if type(tf) is not int or type(length) is not int or not 0<=tf<=length or not math.isfinite(average) or average<=0:raise ValueError('valid token counts and positive mean required')
if not math.isfinite(k1) or not 0<=k1<=10 or not math.isfinite(b) or not 0<=b<=1:raise ValueError('bounded k1 and b required')
if tf==0:return 0.
return tf*(k1+1)/(tf+k1*(1-b+b*length/average))
def rank(query,documents=DOCUMENTS,k1=1.2,b=.75):
factor(0,0,1,k1,b);s=stats(documents);terms=set(tokens(query));rows=[]
if not s['n']:return []
for doc,c in enumerate(s['counts']):
pieces={t:idf(s['n'],s['df'][t])*factor(c[t],s['lengths'][doc],s['average'],k1,b) for t in sorted(terms) if s['df'][t] and c[t]}
score=sum(pieces.values())
if score>0:rows.append(dict(doc=doc,score=score,terms=pieces))
return sorted(rows,key=lambda x:(-x['score'],x['doc']))
def demo():
s=stats();query='bicycle brake cable';curves={str(k):[factor(tf,20,20,k,0) for tf in range(21)] for k in [0,.5,1.2,3.]}
lengths=[2,4,8,16,32];penalty={str(b):[factor(2,n,8,1.2,b) for n in lengths] for b in [0,.75,1.]}
return dict(documents=list(DOCUMENTS),query=query,nonempty_documents=s['n'],lengths=s['lengths'],average_length=s['average'],df=dict(s['df']),ranking=rank(query),without_length_norm=rank(query,b=0),repeated_query=rank(query+' cable cable'),tf_axis=list(range(21)),saturation=curves,length_axis=lengths,length_effect=penalty,common_term_idf=dict(term='bicycle',positive=idf(s['n'],s['df']['bicycle']),raw_rsj=idf(s['n'],s['df']['bicycle'],False)),unknown_query=rank('quasar'),empty_corpus=rank('brake',['','']),scope='Declared BM25 variant: positive IDF, k1+1 numerator, unique query terms and exact lengths; not byte-for-byte Lucene scoring.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
For “bicycle brake cable,” the leading records are 5,0,7 with scores about 1.843873,1.719478,1.719478. Record 5 repeats cable, but its longer length also increases the denominator. Each result includes per-term contributions so the total can be audited. Record 4 uses only alternative vocabulary and receives no score: BM25 does not create synonym matches by itself.
Bicycle occurs in five of eight nonempty records. Its positive IDF is about 0.492476, while the raw form is about −0.451985. The program displays both but ranks only with the declared positive form. Adding cable twice to the query leaves that ranking unchanged because query terms are deduplicated.
The length experiment fixes f=2 and average length eight. With b=0, all five document lengths have factor 1.375. With b=0.75, increasing length from two to thirty-two reduces it from about 1.7426 to 0.7458. These are controlled factor calculations, not a measured retrieval-quality improvement.
The simple implementation builds counts in O(T) expected work, scores N documents against Q distinct query terms in O(NQ), and sorts in O(N log N). A real inverted-index implementation can visit matching postings instead of every document. The program needs no GPU or trained parameters.
Tune quality on queries, not on a favorite example
Longer documents may contain repeated wording or genuinely broader subject matter. The b parameter embodies a compromise; it cannot identify those causes from length alone. The framework paper discusses these alternatives and variation in parameter choices. Length assumptions and variants
Compare against Boolean matching or a simple term-overlap ranker. Choose k1 and b using development queries and relevance judgments, then evaluate untouched queries at the intended cutoff. Keep corpus version and analyzer fixed during comparisons: adding documents changes df and average length, and therefore scores even for unchanged documents. A global threshold need not transfer between collections or queries.
BM25 is not a phrase verifier, a multilingual analyzer or a truth checker. Filters, positional conditions, synonym handling and reranking are separate components. Its lexical failure on record 4 is a reason to investigate candidate generation, not to conclude that all numerical tuning is useless or that a neural method must win.
Change one parameter at a time
- What remains when b=0?
Answer: Document-length normalization disappears, but the frequency factor still saturates when k1 is positive. IDF also remains.
- With k1=0, compare a present term appearing once and three times.
Answer: Both have factor one. An absent term contributes zero; the implementation handles that case separately to avoid a zero-over-zero expression.
- Why do five occurrences across eight documents produce different signs for the two IDFs?
Answer: The ratio is 3.5/5.5, below one, so its logarithm is negative. Adding one before taking the logarithm makes the argument greater than one and the result positive.
- Can scores from different corpus snapshots be compared as fixed relevance probabilities?
Answer: No. They are ranking scores, and corpus statistics affect them. Record the snapshot and conventions, then evaluate quality using relevant queries and labels.
A family with consequential conventions
The framework paper explains saturation, soft length adjustment and formula variants. The fixed Lucene API supplies a concrete positive-IDF convention and documented defaults. The original fixture isolates these mechanisms; it does not reproduce Lucene internals or establish the best parameters for a public benchmark.
Make a prediction, then check
What does setting b=0 remove from this BM25 variant?
Learning objectives
- Compute a declared BM25 variant and explain why its scores depend on the corpus and conventions.
- Run the original small corpus and explain a failure case.
Prerequisites & connections
Explore related knowledge →References
- The Probabilistic Relevance Framework: BM25 and Beyond
Stephen Robertson; Hugo Zaragoza · 2009 - BM25Similarity — Lucene 9.12.3 core API
Apache Lucene contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF26/27/29/30/31 (printed356/357/359/360/361): saturation, soft length normalization, equations3.10/3.12–3.15 and numerator/query-frequency variants. Read constructors and idf/avgFieldLength methods: positive log1p IDF, defaults1.2/.75 and overlap policy; no exact scorer implementation parity asserted. 6 paired equations and four explained exercises. Declared positive IDF, unique query terms, eight nonempty fields, exact lengths, hand score, saturation and k1/b boundaries checked; no exact Lucene parity claim.
- Declared positive IDF, unique query terms, eight nonempty fields, exact lengths, hand score, saturation and k1/b boundaries checked; no exact Lucene parity claim.
- Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- The Probabilistic Relevance Framework: BM25 and Beyond · Viewed physical PDF26/27/29/30/31 (printed356/357/359/360/361): saturation, soft length normalization, equations3.10/3.12–3.15 and numerator/query-frequency variants.
- BM25Similarity — Lucene 9.12.3 core API · Read constructors and idf/avgFieldLength methods: positive log1p IDF, defaults1.2/.75 and overlap policy; no exact scorer implementation parity asserted.
Related topics