skip to content

Ranking Models: TF-IDF & BM25

Ranked retrieval scores every matching document instead of returning a flat set, and TF-IDF and BM25 are the scoring functions nearly every engine ships. Knowing why BM25 saturates term frequency and normalizes by document length is a standard search-interview checkpoint.

on this pageshow

questions

6

In BM25, what do the k1 and b parameters control?

level: middleimportance: must knowfreq 70%

answer

  1. one shapes repetition, one shapes length
  2. the curve has a ceiling
  3. a bracket that vanishes at zero
  4. fully proportional to average length at one
  5. at zero for the first, scoring goes binary

basics

~20 s

k1 controls term-frequency saturation: how quickly extra occurrences of a term stop adding score. b controls document-length normalisation: how strongly a document longer than the collection average is penalised, from none at zero to full at one.

solid answer

~50 s

BM25 scores each query term as an IDF factor multiplied by a saturating term-frequency factor: `f * (k1 + 1) / (f + k1 * (1 - b + b * dl / avgdl))`. **k1** sets the saturation curve. As term frequency grows the factor approaches a ceiling of `k1 + 1`, so raising k1 pushes that ceiling up and makes repeated occurrences keep mattering for longer; lowering it makes the score flatten almost immediately. At k1 = 0 the whole factor becomes 1 and scoring reduces to pure IDF — presence or absence, no frequency at all. **b** scales the length correction sitting in the denominator. At b = 0 the length term vanishes and document length is ignored. At b = 1 the correction is fully proportional to the ratio of this document's length to the collection average, so a document twice the average is penalised hard. Common defaults are k1 = 1.2 and b = 0.75.

code

python · 8 lines
python
def bm25_term(f, dl, avgdl, idf, k1=1.2, b=0.75):
    # b scales the length correction; k1 sets where saturation bends
    norm = 1.0 - b + b * (dl / avgdl)
    return idf * (f * (k1 + 1)) / (f + k1 * norm)

# b = 0  -> norm is 1.0, document length ignored entirely
# b = 1  -> norm is dl/avgdl, fully proportional penalty
# k1 = 0 -> factor collapses to 1.0, score is just idf (binary presence)

go deeper

for a junior

Memorise the pairing and do not swap it: k1 is about repeated terms saturating, b is about document length. Knowing the common defaults of 1.2 and 0.75 is enough at this level.

for a middle

Explain the shape of the curve — that the term-frequency factor approaches a ceiling of k1 + 1 — and read the length bracket at its endpoints to show what b = 0 and b = 1 actually do.

for a senior

Show judgment about when defaults are wrong: short uniform fields where length normalisation adds noise, verbose corpora where it pays, and per-field configuration where title and body have different length distributions.

for a principal

Own the tuning economics. Argue why parameter re-fitting usually ranks below analysis and field weighting in expected value, and insist on judgment sets and held-out queries before anyone touches a scoring parameter in production.

## The formula BM25 scores a document by summing a contribution per query term: ``` score(d, q) = SUM over t in q of idf(t) * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avgdl)) ``` where f is the number of occurrences of term t in document d, dl is the length of d in tokens, and avgdl is the mean document length across the collection. Two free parameters shape the curve: k1 and b. Everything else is corpus statistics. ## k1: how fast term frequency saturates Ignore length for a moment by setting b = 0. The term-frequency factor is then f(k1+1)/(f+k1). This is a hyperbola: it rises steeply from zero, then bends over toward a horizontal asymptote at k1 + 1. That asymptote is the crucial property — no matter how many times a term is repeated, its contribution is bounded. k1 chooses where the bend happens. Small k1 means the curve flattens almost at once: the first occurrence carries nearly all the weight, and the twentieth is barely different from the second. Large k1 straightens the curve, so the score keeps climbing with frequency and BM25 starts behaving more like raw TF-IDF. In the limit k1 -> infinity you recover linear term frequency; at k1 = 0 the factor collapses to exactly 1 for any f > 0, so the model becomes binary presence-weighted-by-IDF, which is essentially a probabilistic Boolean retrieval. The practical value of saturation is that it defends against repetition. A page that repeats a keyword forty times gains very little over a page mentioning it five times, so keyword stuffing does not buy a top rank, and a genuinely on-topic short document is not automatically beaten by a verbose one. ## b: how strongly length is normalised The denominator contains `k1 * (1 - b + b * dl/avgdl)`. Read the bracket alone: - at **b = 0** it is `1`, independent of dl — the length signal is switched off entirely; - at **b = 1** it is `dl/avgdl` — the correction is fully proportional, so a document twice the average length effectively has its term frequencies halved; - between, it interpolates linearly between those two regimes. A document longer than average therefore inflates the denominator and lowers the score, and a shorter-than-average one gets a boost. The intuition is that finding a term three times in a tweet is far stronger evidence than finding it three times in a book chapter. Note that b sits *inside* the saturation denominator rather than dividing the final score. That coupling is deliberate: length rescales the effective term frequency before saturation applies, rather than being a separate multiplier bolted on afterwards as it is in cosine-normalised TF-IDF. ## Defaults and when they are wrong k1 = 1.2 and b = 0.75 are the widely used defaults and are a reasonable starting point across a broad range of collections. They are not universal truths, and two situations regularly justify deviating. The first is a collection of **near-uniform short fields** — product names, person names, tags, identifiers. Length normalisation has almost nothing to correct there, and a strong b can produce odd effects where a one-token variant beats a natural title. Lowering b, sometimes to zero, is a defensible move. The second is **long, heterogeneous text** where verbosity genuinely correlates with padding: a high b pushes back on it. Conversely, in a corpus where longer documents genuinely are more useful — comprehensive reference pages against thin stubs — a lower b avoids punishing them for being thorough. k1 is adjusted less often. Raising it suits collections where repetition really is evidence of topicality; lowering it suits collections where any mention is as good as many, such as short metadata fields. ## Fields differ, so parameters may differ A single document often has parts with wildly different length distributions — a title of five tokens and a body of two thousand. Applying one b to both is a compromise. Engines commonly allow per-field similarity configuration so a title field can use a small b and the body a larger one; the details of that configuration are engine-specific, but the reasoning is the model's. ## Tuning discipline k1 and b should be changed only against a judgment set and a measurement, never on the strength of one query looking better. The gains from re-fitting them are usually modest compared with fixing analysis, field weighting or query construction, and it is easy to overfit two parameters to a handful of anecdotes. Grid search over a small range with held-out queries is the standard approach when it is worth doing at all. ## What interviewers listen for That you attach k1 to saturation and b to length — getting these backwards is the most common error — and that you can state the boundary behaviours: k1 = 0 gives binary scoring, b = 0 disables length normalisation, b = 1 makes it fully proportional. Knowing the defaults is a bonus, not the point.

  • What does BM25 reduce to when k1 is set to zero?
    Pure IDF-weighted presence. With k1 = 0 the numerator is f and the denominator is also f, so the term-frequency factor is exactly 1 for any non-zero frequency. Term frequency and document length both stop mattering, and the score becomes the sum of IDF over the query terms the document contains — a probabilistic Boolean model.
  • What is the ceiling of BM25's term-frequency factor as frequency grows without bound?
    It approaches k1 + 1. Dividing numerator and denominator by f leaves (k1+1) / (1 + k1*norm/f), and as f grows the second denominator term vanishes. This bounded contribution per term is exactly what raw TF-IDF lacks, and it is why repeating a keyword cannot lift a document arbitrarily.
  • When would you lower b toward zero for a particular field?
    When the field's length carries no relevance signal — product names, person names, tags, short identifiers. Their length distribution is narrow, so normalising against an average mostly adds noise, and a strong b can make a terse variant beat a natural full title. Long free text is the opposite case and typically wants b at or near the default.
  • Is re-fitting k1 and b usually the highest-value relevance work available?
    Rarely. Analysis errors, wrong field weights and badly constructed queries dominate the loss in most systems, and two parameters overfit easily to a few anecdotal queries. Re-fit them only with a judgment set, a held-out split and a measured before-and-after, and expect modest gains relative to fixing the retrieval side.

k1 is the volume knob's compressor: the tenth shout is barely louder than the second. b is a handicap for size: the longer the document, the more it has to prove.

saying these in an interview costs you the question

  • Swaps them, saying b controls saturation and k1 controls length
  • Claims BM25 term frequency grows without bound like TF-IDF
  • Says b = 1 disables document-length normalisation
  • Thinks k1 and b are per-query knobs rather than index-level parameters
  • Tunes k1 and b on a handful of anecdotal queries with no judgment set

context

open as a page

In TF-IDF weighting, what do the term frequency and inverse document frequency factors each measure?

level: middleimportance: must knowfreq 75%

basics

~20 s

Term frequency measures how often a term occurs in one document, a proxy for how much that document is about the term. Inverse document frequency measures how rare the term is across the whole collection, a proxy for how discriminating it is.

open as a page

In information retrieval, how does Boolean retrieval differ from ranked retrieval?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Boolean retrieval treats a query as a logical predicate and returns an unordered set of documents that satisfy it. Ranked retrieval scores every candidate for degree of relevance and returns them ordered, so partial matches still surface.

open as a page

In the vector space model, why is cosine similarity used instead of a raw dot product?

level: middleimportance: should knowfreq 45%

basics

~20 s

A raw dot product grows with vector magnitude, so long documents win simply for containing more terms. Cosine divides by both vector lengths, comparing the direction of the vectors — the mix of terms — rather than their size.

open as a page

Why does BM25 usually rank better than raw TF-IDF on collections with long documents?

level: seniorimportance: should knowfreq 55%

basics

~20 s

BM25 bounds each term's contribution with a saturation curve and folds a tunable length correction into that curve, so a long document cannot win by repetition or bulk. Raw TF-IDF grows linearly with term frequency and normalises length only crudely.

open as a page

Why can BM25's IDF term go negative, and what do implementations do about it?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

The classic probabilistic IDF is a log-odds ratio that falls below zero once a term appears in more than half the collection, meaning a matching document is penalised for containing a very common word. Implementations add one inside the logarithm or floor the value.

open as a page