Algorithm Search⌘K

Algorithmcore

Witten-Bell smoothing

Also called Witten-Bell discounting, Witten-Bell interpolation.

Interpolate each n-gram estimate with the lower order, giving the lower order the weight T(h)/(c(h) + T(h)), where T(h) is the number of distinct words seen after the history h.

Time
Θ(n N) worst
Space
Θ(n N) extra
Where
N = the number of training tokens; n = the order of the model
Properties
deterministicexactofflinerecursive
Origin
Ian H. Witten, Timothy C. Bell, 1991

Witten-Bell smoothing is a way to fill the zeros of an n-gram language model. For each history hh (the words before the one we predict), it mixes the counts seen after hh with the estimate of the shorter history, and it sets the mix from one number: T(h)T(h), how many different words were seen after hh. A history followed by many different words gets a large share from the lower order, because a new word after it is likely; a history that is always followed by the same word keeps almost all of its own estimate. Unlike Jelinek-Mercer smoothing and deleted interpolation, it fits no weights on held-out data, and unlike Kneser-Ney smoothing it subtracts no fixed discount.

In plain words

Read a text and watch what comes after one word, say "the". Each time a word follows "the" that has never followed it before, count one surprise. The number of surprises, over the number of times "the" was followed by anything plus the surprises, is a good guess for the chance that the next word after "the" is again a surprise.

Witten-Bell gives exactly that share of the probability to a simpler model that ignores "the", and keeps the rest for the words already seen after "the", in proportion to their counts. The simpler model is built the same way, from a shorter context, down to the case where every word is equally likely.

The problem

The training text is a list of sentences over a vocabulary VV that holds every predicted token: the words, the end marker </s> and the unknown word <unk>. Each sentence is padded with n−1n - 1 start markers <s> on the left and one </s> on the right. For a history hh of up to n−1n - 1 tokens, c(hw)c(h w) is the number of times hh is followed by ww, c(h)=∑wc(hw)c(h) = \sum_w c(h w), and T(h)=N1+(h ⋅)T(h) = N_{1+}(h \,\cdot) is the number of distinct ww with c(hw)>0c(h w) > 0. Write h′h' for hh without its first token, and ϵ\epsilon for the empty history, so that c(ϵ)=Nc(\epsilon) = N is the number of predicted tokens. The task is a conditional distribution P(w∣h)P(w \mid h) over VV for every history, with no zeros.

The algorithm

The interpolated Witten-Bell estimate is

PWB(w∣h)=c(hw)+T(h) PWB(w∣h′)c(h)+T(h)if c(h)>0,P_{WB}(w \mid h) = \frac{c(h w) + T(h) \, P_{WB}(w \mid h')}{c(h) + T(h)} \quad \text{if } c(h) > 0,

and PWB(w∣h)=PWB(w∣h′)P_{WB}(w \mid h) = P_{WB}(w \mid h') if c(h)=0c(h) = 0. Below the unigrams sits the uniform distribution 1/∣V∣1/|V|. In the form of Jelinek-Mercer smoothing, the weight of the maximum likelihood estimate is λ(h)=c(h)/(c(h)+T(h))\lambda(h) = c(h) / (c(h) + T(h)), and the lower order gets 1−λ(h)=T(h)/(c(h)+T(h))1 - \lambda(h) = T(h) / (c(h) + T(h)).

  1. P-WB(w, h) ▷ c, T counted once on the training text
  2. 1if h = ε then lower ← 1 / |V| else lower ← P-WB(w, h')
  3. 2if c(h) = 0 then return lower
  4. 3λ ← c(h) / (c(h) + T(h))
  5. 4return λ c(h w) / c(h) + (1 - λ) lower

Line L1 gets the estimate of the shorter history. Line L2 skips a history that never occurred, so the whole mass goes down one order. Line L3 is the Witten-Bell weight. Line L4 mixes the two estimates. A model of order nn calls P-WB with the last n−1n - 1 tokens before ww.

Example

Train a bigram model (n=2n = 2) on the three sentences "a b", "a c" and "b c", with V={a,b,c,⟨/s⟩}V = \{a, b, c, \langle /s \rangle\}. The padded sentences give N=9N = 9 predicted tokens: a, b and c twice each and </s> three times. Every token of VV occurs, so T(ϵ)=4T(\epsilon) = 4.

The unigram level mixes the counts with the uniform 1/41/4: P(a)=(2+4⋅14)/(9+4)=3/13P(a) = (2 + 4 \cdot \tfrac14)/(9 + 4) = 3/13, the same for b and c, and P(⟨/s⟩)=(3+1)/13=4/13P(\langle /s \rangle) = (3 + 1)/13 = 4/13.

history hh followers and counts c(h)c(h) T(h)T(h) P(⟨/s⟩∣h)P(\langle /s \rangle \mid h) P(a∣h)P(a \mid h) P(b∣h)P(b \mid h) P(c∣h)P(c \mid h)
<s> a 2, b 1 3 2 8/65 32/65 19/65 6/65
a b 1, c 1 2 2 2/13 3/26 19/52 19/52
b c 1, </s> 1 2 2 21/52 3/26 3/26 19/52
c </s> 2 2 1 10/13 1/13 1/13 1/13

For example, P(b∣a)=(1+2⋅313)/(2+2)=19/52P(b \mid a) = (1 + 2 \cdot \tfrac{3}{13})/(2 + 2) = 19/52, and P(⟨/s⟩∣c)=(2+1⋅413)/(2+1)=10/13P(\langle /s \rangle \mid c) = (2 + 1 \cdot \tfrac{4}{13})/(2 + 1) = 10/13. After c only </s> was seen, so T(c)=1T(c) = 1 and the history c gives its own estimate the weight λ=2/3\lambda = 2/3. After a two different words were seen in two tokens, so a gives half its mass to the unigram level. Each row sums to 1. The sentence "a b c" gets 3265⋅1952⋅1952⋅1013=1444/28561\tfrac{32}{65} \cdot \tfrac{19}{52} \cdot \tfrac{19}{52} \cdot \tfrac{10}{13} = 1444/28561.

If <unk> is added to VV, the uniform level becomes 1/51/5, T(ϵ)T(\epsilon) stays 4, and <unk> gets P(⟨unk⟩)=(4/5)/13=4/65P(\langle \text{unk} \rangle) = (4/5)/13 = 4/65 and P(⟨unk⟩∣a)=2/65P(\langle \text{unk} \rangle \mid a) = 2/65.

Correctness

Every row is a distribution. By induction on the length of hh. The uniform level sums to 1. If c(h)=0c(h) = 0 the row is the row of h′h'. If c(h)>0c(h) > 0, sum line L4 over w∈Vw \in V: λ∑wc(hw)/c(h)+(1−λ)∑wPWB(w∣h′)=λ+(1−λ)=1\lambda \sum_w c(h w)/c(h) + (1 - \lambda) \sum_w P_{WB}(w \mid h') = \lambda + (1 - \lambda) = 1. The first sum is 1 because every token seen after hh is in VV.

No zeros. The uniform level is positive. If c(h)>0c(h) > 0 then T(h)≥1T(h) \ge 1, so 1−λ>01 - \lambda > 0 and line L4 is positive whenever the lower order is. So PWB(w∣h)>0P_{WB}(w \mid h) > 0 for every w∈Vw \in V and every history.

The meaning of the weight. Read the text after hh token by token. The number of tokens that are the first of their type is T(h)T(h), out of c(h)c(h) tokens. Then T(h)/(c(h)+T(h))T(h) / (c(h) + T(h)) is the escape estimate of Witten and Bell for the chance that the next token after hh is new, and line L4 gives that share to the lower order.

Proof: Witten-Bell smoothing gives every history a distribution over the vocabulary with no zerosfull

Fix the training text and the vocabulary VV, with ∣V∣≥1|V| \ge 1. Assume that every token predicted in training is in VV. For a history hh (a tuple of at most n−1n - 1 tokens), c(hw)c(h w) is the number of times hh is followed by ww in the padded text, c(h)=∑wc(hw)c(h) = \sum_w c(h w), and T(h)=∣{w:c(hw)>0}∣T(h) = |\{w : c(h w) > 0\}|. For h≠ϵh \ne \epsilon, h′h' is hh without its first token.

Theorem. For every history hh, the values PWB(w∣h)P_{WB}(w \mid h) of P-WB for w∈Vw \in V satisfy PWB(w∣h)>0P_{WB}(w \mid h) > 0 and ∑w∈VPWB(w∣h)=1\sum_{w \in V} P_{WB}(w \mid h) = 1.

Proof. By induction on the length ℓ\ell of hh. Write L(w)L(w) for the value of lower in line L1: L(w)=1/∣V∣L(w) = 1/|V| if h=ϵh = \epsilon, and L(w)=PWB(w∣h′)L(w) = P_{WB}(w \mid h') otherwise.

The values of lower. If ℓ=0\ell = 0, then L(w)=1/∣V∣>0L(w) = 1/|V| > 0 and ∑w∈VL(w)=1\sum_{w \in V} L(w) = 1. If ℓ≥1\ell \ge 1, then h′h' has length ℓ−1\ell - 1, and by the induction hypothesis L(w)>0L(w) > 0 and ∑w∈VL(w)=1\sum_{w \in V} L(w) = 1. So in both cases LL is a distribution on VV with no zeros.

Case c(h)=0c(h) = 0. Line L2 returns L(w)L(w), which has both properties.

Case c(h)>0c(h) > 0. Some token follows hh, so T(h)≥1T(h) \ge 1. Line L3 gives λ=c(h)/(c(h)+T(h))\lambda = c(h)/(c(h) + T(h)) with 0<λ<10 < \lambda < 1. Line L4 returns λ c(hw)/c(h)+(1−λ)L(w)\lambda \, c(h w)/c(h) + (1 - \lambda) L(w). The first term is at least 0 and the second is positive, so the value is positive. Every ww with c(hw)>0c(h w) > 0 is a token predicted in training, so it is in VV, and therefore ∑w∈Vc(hw)=c(h)\sum_{w \in V} c(h w) = c(h). Summing over VV,

∑w∈VPWB(w∣h)=λ⋅c(h)c(h)+(1−λ)∑w∈VL(w)=λ+(1−λ)=1.■\sum_{w \in V} P_{WB}(w \mid h) = \lambda \cdot \frac{c(h)}{c(h)} + (1 - \lambda) \sum_{w \in V} L(w) = \lambda + (1 - \lambda) = 1. \qquad \blacksquare

The closed form. In the case c(h)>0c(h) > 0, λc(hw)/c(h)=c(hw)/(c(h)+T(h))\lambda c(h w)/c(h) = c(h w)/(c(h) + T(h)) and 1−λ=T(h)/(c(h)+T(h))1 - \lambda = T(h)/(c(h) + T(h)), so line L4 equals (c(hw)+T(h)PWB(w∣h′))/(c(h)+T(h))\bigl(c(h w) + T(h) P_{WB}(w \mid h')\bigr)/\bigl(c(h) + T(h)\bigr), the formula on the page.

Sentences. A sentence w1…wkw_1 \ldots w_k gets ∏i=1k+1PWB(wi∣hi)\prod_{i=1}^{k+1} P_{WB}(w_i \mid h_i) with $w_{k+1} = $ </s> and hih_i the n−1n - 1 tokens before wiw_i in the padded sentence. Since every row is a distribution with </s> in it, the probabilities of all finite sentences sum to at most 1. There are finitely many histories of n−1n - 1 tokens over VV and <s>, and by the theorem each gives </s> a positive probability, so PWB(</s>∣h)≥δP_{WB}(\text{</s>} \mid h) \ge \delta for one δ>0\delta > 0 and all of them. The total probability of the sentences with more than kk tokens is then at most (1−δ)k(1 - \delta)^k, which tends to 0, so the probabilities of all finite sentences sum to exactly 1.

Complexity

One pass over the padded training text with a hash table or a trie counts c(hw)c(h w), c(h)c(h) and T(h)T(h) for every order: Θ(nN)\Theta(n N) expected time, and Θ(nN)\Theta(n N) space in the worst case, since each token adds at most one new n-gram per order. T(h)T(h) is counted when an n-gram is seen for the first time. One query P-WB(w,h)(w, h) makes nn calls, so it takes Θ(n)\Theta(n) expected time; a full row takes Θ(n∣V∣)\Theta(n |V|). With exact fractions, as in the implementation, the denominators grow with nn; in practice the model stores floating point log probabilities.

Properties

  • No free parameters. Everything comes from the counts. There is no held-out set and no discount to tune.
  • Adaptive to the history. A history with a fixed follower (like "San" before "Francisco") gets little from the lower order; a history with many followers (like "the") gets much.
  • Interpolated. Every n-gram, seen or not, gets some mass from the lower order, so seen n-grams are discounted by a share of the lower order and unseen ones are not all equal.
  • Recursive and exact. The recursion has depth nn, and with fractions the rows sum to 1 exactly.
  • Strong discount for small counts. A history seen once gives half its mass to the lower order, since c(h)=T(h)=1c(h) = T(h) = 1.

Variants and improvements

  • The backoff form. Use c(hw)/(c(h)+T(h))c(h w)/(c(h) + T(h)) for the seen words and share T(h)/(c(h)+T(h))T(h)/(c(h) + T(h)) among the unseen words in proportion to the lower order, normalized as in Katz backoff.
  • A scaled weight. Replace T(h)T(h) by βT(h)\beta T(h) with a constant β\beta tuned on held-out data.
  • Escape methods in compression. In prediction by partial matching the same estimate decides when to escape from a long context to a shorter one. There, the lower order often excludes the symbols already seen in the longer context.
  • Kneser-Ney. Kneser-Ney smoothing also uses T(h)T(h), but as the number of discounts of a fixed size DD, and it uses continuation counts at the lower orders. Chen and Goodman (1999) found it better than Witten-Bell.

When to use it

Use it when you need a smoothed n-gram model with no tuning and no held-out data, for example for small or quickly changing text, for a character model, or as a baseline. It is simple to implement, it never gives a zero, and it adapts to the diversity of each history. For a model of words trained on a large corpus, modified Kneser-Ney smoothing usually gives a lower perplexity.

Pitfalls

  • T(h)T(h) counts types, not tokens. It is the number of different words after hh, not the number of times hh was followed by something.
  • The vocabulary of the base level. The uniform level divides by ∣V∣|V|, which must hold </s> and <unk>. If VV is only the words seen in training, an unseen word in the test text gets no probability.
  • <s> is not predicted. It is part of histories only. It must not be in VV, and it is not counted in NN.
  • Unseen histories. If c(h)=0c(h) = 0, the formula has 0/00/0. The rule is to use the lower order directly.
  • Mixing up the two forms. The interpolated and the backoff forms give different numbers. Say which one a result uses.

Implementations

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.

witten_bell_smoothing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/witten-bell-smoothing/. The authors are listed in prov/FME53F.jsonl.

"""Interpolated Witten-Bell smoothing of an n-gram language model, exact in Fraction.

A corpus is a list of sentences, and a sentence is a list of str tokens.
Each sentence is padded with n - 1 copies of "<s>" on the left and one
"</s>" on the right. "</s>" is predicted and counted; "<s>" is never
predicted. The recursion is

    P(w | h) = (c(h w) + T(h) P(w | h')) / (c(h) + T(h))   if c(h) > 0
    P(w | h) = P(w | h')                                  if c(h) = 0

where h' is h without its first token, c(h) is the number of times h is
followed by a token, and T(h) = N_1+(h .) is the number of distinct tokens
that follow h. Below the unigrams sits the uniform distribution 1 / |V|.
"""

from collections import Counter
from fractions import Fraction
from typing import Iterable, Sequence

BOS, EOS, UNK = "<s>", "</s>", "<unk>"


def count_ngrams(corpus: Iterable[Sequence[str]], n: int):
    """Return (c, ch, t): the counts of the m-grams for m = 1 to n, the history counts and T(h)."""
    c: Counter = Counter()
    ch: Counter = Counter()
    t: Counter = Counter()
    for sent in corpus:
        toks = [BOS] * (n - 1) + list(sent) + [EOS]
        for i in range(n - 1, len(toks)):
            for m in range(1, n + 1):
                g = tuple(toks[i - m + 1 : i + 1])
                if c[g] == 0:
                    t[g[:-1]] += 1
                c[g] += 1
                ch[g[:-1]] += 1
    return c, ch, t


class WittenBellLM:
    """An interpolated Witten-Bell n-gram model over a closed vocabulary."""

    def __init__(self, corpus: Iterable[Sequence[str]], n: int, vocab: Iterable[str] | None = None):
        if n < 1:
            raise ValueError("the order n must be at least 1")
        corpus = [list(s) for s in corpus]
        self.n = n
        self.c, self.ch, self.t = count_ngrams(corpus, n)
        seen = {g[0] for g in self.c if len(g) == 1}
        self.vocab = set(seen) if vocab is None else set(vocab)
        self.vocab.add(EOS)
        if BOS in self.vocab:
            raise ValueError("<s> is never predicted, so it is not in the vocabulary")
        if not seen <= self.vocab:
            raise ValueError("the vocabulary must hold every training token; map the others to <unk>")

    def prob(self, w: str, history: Sequence[str] = ()) -> Fraction:
        """P(w | the last n - 1 tokens of history)."""
        if w not in self.vocab:
            raise KeyError(f"{w!r} is not in the vocabulary")
        h = tuple(history)[-(self.n - 1) :] if self.n > 1 else ()
        return self._prob(w, h)

    def _prob(self, w: str, h: tuple) -> Fraction:
        if h:  # @line L1
            lower = self._prob(w, h[1:])
        else:
            lower = Fraction(1, len(self.vocab))
        ch = self.ch[h]
        if ch == 0:  # @line L2
            return lower
        lam = Fraction(ch, ch + self.t[h])  # @line L3
        return lam * Fraction(self.c[h + (w,)], ch) + (1 - lam) * lower  # @line L4

    def distribution(self, history: Sequence[str] = ()) -> dict[str, Fraction]:
        """The full conditional distribution over the vocabulary."""
        return {w: self.prob(w, history) for w in sorted(self.vocab)}

    def sentence_prob(self, sent: Sequence[str]) -> Fraction:
        """The probability of a sentence, with its </s>."""
        toks = [BOS] * (self.n - 1) + list(sent) + [EOS]
        p = Fraction(1)
        for i in range(self.n - 1, len(toks)):
            p *= self.prob(toks[i], toks[:i])
        return p
test_witten_bell_smoothing.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/witten-bell-smoothing/. The authors are listed in prov/FME53F.jsonl.

import itertools
import random
from fractions import Fraction as F

import pytest

from witten_bell_smoothing import BOS, EOS, WittenBellLM

TOY = [["a", "b"], ["a", "c"], ["b", "c"]]


def test_toy_values() -> None:
    m = WittenBellLM(TOY, 2)
    assert m.distribution(()) == {EOS: F(4, 13), "a": F(3, 13), "b": F(3, 13), "c": F(3, 13)}
    assert m.distribution((BOS,)) == {EOS: F(8, 65), "a": F(32, 65), "b": F(19, 65), "c": F(6, 65)}
    assert m.prob("b", ["a"]) == F(19, 52)
    assert m.prob(EOS, ["c"]) == F(10, 13)
    assert m.sentence_prob(["a", "b", "c"]) == F(32, 65) * F(19, 52) * F(19, 52) * F(10, 13)
    assert m.sentence_prob(["b", "a"]) > 0


def test_unk_in_vocabulary() -> None:
    m = WittenBellLM(TOY, 2, vocab={"a", "b", "c", "<unk>"})
    assert m.prob("<unk>", ["a"]) == F(2, 65)
    assert sum(m.distribution(["a"]).values()) == 1


def test_errors() -> None:
    m = WittenBellLM(TOY, 2)
    with pytest.raises(KeyError):
        m.prob("z", ["a"])
    with pytest.raises(ValueError):
        WittenBellLM(TOY, 2, vocab={"a"})
    with pytest.raises(ValueError):
        WittenBellLM(TOY, 2, vocab={"a", "b", "c", BOS})
    with pytest.raises(ValueError):
        WittenBellLM(TOY, 0)


def direct_bigram(corpus, vocab):
    """The bigram formula written out, with counts found by a plain scan."""
    pairs, toks = [], []
    for s in corpus:
        x = [BOS] + s + [EOS]
        pairs += list(zip(x, x[1:]))
        toks += x[1:]
    n = len(toks)
    t0 = len(set(toks))

    def uni(w):
        return (toks.count(w) + F(t0, len(vocab))) / (n + t0)

    def bi(w, v):
        cv = sum(1 for p in pairs if p[0] == v)
        if cv == 0:
            return uni(w)
        tv = len({p[1] for p in pairs if p[0] == v})
        return (pairs.count((v, w)) + tv * uni(w)) / (cv + tv)

    return bi


def test_against_direct_formula() -> None:
    rng = random.Random(4)
    for _ in range(40):
        words = ["a", "b", "c", "d", "e"][: rng.randrange(2, 6)]
        corpus = [[rng.choice(words) for _ in range(rng.randrange(0, 5))] for _ in range(rng.randrange(1, 6))]
        vocab = set(words) | {EOS}
        m = WittenBellLM(corpus, 2, vocab=words)
        bi = direct_bigram(corpus, vocab)
        for v in [BOS] + words:
            for w in vocab:
                assert m.prob(w, [v]) == bi(w, v)


def test_rows_sum_to_one() -> None:
    rng = random.Random(9)
    for _ in range(60):
        n = rng.randrange(1, 4)
        words = ["a", "b", "c", "d"]
        corpus = [[rng.choice(words[:3]) for _ in range(rng.randrange(0, 6))] for _ in range(rng.randrange(1, 5))]
        m = WittenBellLM(corpus, n, vocab=words)
        for h in itertools.product([BOS] + words, repeat=n - 1):
            d = m.distribution(h)
            assert sum(d.values()) == 1
            assert all(0 < p <= 1 for p in d.values())


def test_short_sentences_have_mass_below_one() -> None:
    m = WittenBellLM(TOY, 2)
    total = F(0)
    for length in range(4):
        for s in itertools.product(["a", "b", "c"], repeat=length):
            total += m.sentence_prob(list(s))
    assert F(1, 2) < total < 1

History

Witten and Bell (1991) studied the zero-frequency problem in adaptive text compression: a coder that predicts the next symbol from its context must give some probability to a symbol never seen in that context. They compared several estimates of this escape probability, among them the one based on the number of distinct symbols seen in the context. Language modeling took the estimate over as Witten-Bell smoothing, and Chen and Goodman (1999) described it as a form of Jelinek-Mercer interpolation with the weight T(h)/(c(h)+T(h))T(h)/(c(h) + T(h)) and compared it with the other classical methods.

References

  1. Ian H. Witten and Timothy C. Bell, The zero-frequency problem, estimating the probabilities of novel events in adaptive text compression, IEEE Transactions on Information Theory 37(4), 1991, pages 1085 to 1094, the escape estimate based on the number of distinct symbols seen in a context, and its comparison with other escape methods
  2. Stanley F. Chen and Joshua Goodman, An empirical study of smoothing techniques for language modeling, Computer Speech and Language 13(4), 1999, pages 359 to 394, Witten-Bell smoothing as interpolation with the weight N_1+(h .)/(N_1+(h .) + c(h)), and its measured performance
  3. Daniel Jurafsky and James H. Martin, Speech and Language Processing, third edition draft, chapter N-gram Language Models (draft of January 2026), smoothing and interpolation

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example