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
- Model
- Word RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 (the words before the one we predict), it mixes the counts seen after with the estimate of the shorter history, and it sets the mix from one number: , how many different words were seen after . 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 that holds every predicted token: the words, the end marker </s> and the unknown word <unk>. Each sentence is padded with start markers <s> on the left and one </s> on the right. For a history of up to tokens, is the number of times is followed by , , and is the number of distinct with . Write for without its first token, and for the empty history, so that is the number of predicted tokens. The task is a conditional distribution over for every history, with no zeros.
The algorithm
The interpolated Witten-Bell estimate is
and if . Below the unigrams sits the uniform distribution . In the form of Jelinek-Mercer smoothing, the weight of the maximum likelihood estimate is , and the lower order gets .
P-WB(w, h) ▷ c, T counted once on the training text- 1
if h = ε then lower ← 1 / |V| else lower ← P-WB(w, h') - 2
if c(h) = 0 then return lower - 3
λ ← c(h) / (c(h) + T(h)) - 4
return λ 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 calls P-WB with the last tokens before .
Example
Train a bigram model () on the three sentences "a b", "a c" and "b c", with . The padded sentences give predicted tokens: a, b and c twice each and </s> three times. Every token of occurs, so .
The unigram level mixes the counts with the uniform : , the same for b and c, and .
| history | followers and counts | ||||||
|---|---|---|---|---|---|---|---|
<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, , and . After c only </s> was seen, so and the history c gives its own estimate the weight . 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 .
If <unk> is added to , the uniform level becomes , stays 4, and <unk> gets and .
Correctness
Every row is a distribution. By induction on the length of . The uniform level sums to 1. If the row is the row of . If , sum line L4 over : . The first sum is 1 because every token seen after is in .
No zeros. The uniform level is positive. If then , so and line L4 is positive whenever the lower order is. So for every and every history.
The meaning of the weight. Read the text after token by token. The number of tokens that are the first of their type is , out of tokens. Then is the escape estimate of Witten and Bell for the chance that the next token after 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 , with . Assume that every token predicted in training is in . For a history (a tuple of at most tokens), is the number of times is followed by in the padded text, , and . For , is without its first token.
Theorem. For every history , the values of P-WB for satisfy and .
Proof. By induction on the length of . Write for the value of lower in line L1: if , and otherwise.
The values of lower. If , then and . If , then has length , and by the induction hypothesis and . So in both cases is a distribution on with no zeros.
Case . Line L2 returns , which has both properties.
Case . Some token follows , so . Line L3 gives with . Line L4 returns . The first term is at least 0 and the second is positive, so the value is positive. Every with is a token predicted in training, so it is in , and therefore . Summing over ,
The closed form. In the case , and , so line L4 equals , the formula on the page.
Sentences. A sentence gets with $w_{k+1} = $ </s> and the tokens before 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 tokens over and <s>, and by the theorem each gives </s> a positive probability, so for one and all of them. The total probability of the sentences with more than tokens is then at most , 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 , and for every order: expected time, and space in the worst case, since each token adds at most one new n-gram per order. is counted when an n-gram is seen for the first time. One query P-WB makes calls, so it takes expected time; a full row takes . With exact fractions, as in the implementation, the denominators grow with ; 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 , 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 .
Variants and improvements
- The backoff form. Use for the seen words and share among the unseen words in proportion to the lower order, normalized as in Katz backoff.
- A scaled weight. Replace by with a constant 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 , but as the number of discounts of a fixed size , 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
- counts types, not tokens. It is the number of different words after , not the number of times was followed by something.
- The vocabulary of the base level. The uniform level divides by , which must hold
</s>and<unk>. If 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 , and it is not counted in .- Unseen histories. If , the formula has . 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.
# 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 and compared it with the other classical methods.
References
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag FME53F Edit this page History Report an error Markdown