Algorithmcore
Deleted interpolation
Also called held-out interpolation weights.
Mix the n-gram estimates of every order with weights fitted by EM on held-out data, often in buckets by the count of the history.
- Time
- Θ(n N (K + I)) worst
- Space
- Θ(n N) extra
- Where
- I = the number of EM iterations; K = the number of parts; N = the number of training tokens; n = the order of the model
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Frederick Jelinek, Robert L. Mercer, 1980
Deleted interpolation builds a smoothed n-gram language model as a weighted mix of simpler estimates: the relative frequency of the word after the full history, after a shorter history, after no history, and a uniform guess. The weights are not set by hand. They are fitted by expectation-maximization to make held-out text as likely as possible, and in the "deleted" form each part of the training data is held out in turn, so that no data is set aside for good. Frederick Jelinek and Robert Mercer introduced it in 1980 for speech recognition. Jelinek-Mercer smoothing in retrieval is the same mix with one fixed weight and two components, and Witten-Bell smoothing sets the weights from the counts with no held-out data at all.
In plain words
You want to guess the next word. You have several advisers. One looks at the last two words, one at the last word only, one at no context, and one says every word is equally likely. The first is sharp but often has no data; the last is never wrong by zero but never sharp. You mix their answers with weights.
To pick the weights, hide some text from the advisers, let them guess it, and see how much each one helped on each word. Give each adviser a weight equal to its average share of the credit, and repeat until the weights stop changing. Then show the advisers all the text, and keep the weights. Because the sharp adviser is reliable only when its context was seen often, use a separate set of weights for contexts seen once, a few times, or many times.
The problem
The training text is a list of sentences, each padded with start markers <s> on the left and one </s> on the right. The vocabulary holds every predicted token, with </s> and <unk>. For a history of tokens, write for its last tokens, so . Let be the maximum likelihood estimate of order , defined when , and . Let be the largest with . The model is
with weights that sum to 1 in each bucket . The bucket groups histories that should share weights. Here is the pair of and the number of bits of , so the histories seen once, two or three times, four to seven times, and so on, get their own weights. The task is to choose the weights that maximize the likelihood of text not used for the counts.
The algorithm
Cut the training sentences into parts . For each part, count the other parts and record, for each token of the part, its bucket and the values of its components. Then run EM on all these rows together.
DELETED-INTERPOLATION(B_1 .. B_K, n)- 1
for j ← 1 to K do - 2
count the n-grams of every part except B_j - 3
for each token w after history h in B_j do add the row (b(h), p_m(w|h), ..., p_0(w|h), 1/|V|) to R - 4
for each bucket b do give each of its components the weight 1 / (its number of components) - 5
repeat - 6
for each row (b, p) of R do z ← Σ_i λ_{b,i} p_i; e_{b,i} ← e_{b,i} + λ_{b,i} p_i / z for each i - 7
for each bucket b and component i do λ_{b,i} ← e_{b,i} / |R_b|; e_{b,i} ← 0 - 8
until the log likelihood Σ_rows log z rises by less than a tolerance - 9
count all the parts; return P(w | h) = Σ_i λ_{b(h),i} p_i(w | h)
Lines L1 to L3 are the "deleted" part: each token is scored by counts that do not include its own part. Line L6 is the E step: is the posterior chance that component produced the token. Line L7 is the M step: the new weight is the average posterior. Line L9 builds the final model from the counts of the whole text. With and a separate held-out set in place of the loop, this is plain held-out interpolation.
Example
Take one bucket with two components, a bigram estimate and a unigram estimate, and three held-out tokens whose component values are , and . Write for the weight of the bigram. The log likelihood is
Start at . The posteriors of the bigram are , and , so the M step gives . The next step gives . In general one step maps to , and the steps converge to , where . There the three tokens get , and , for a product of . The bigram alone () gives the second token 0, and the unigram alone gives the product .
Correctness
Every row is a distribution. Each component with sums to 1 over , because all its counts are of tokens in , and the uniform component sums to 1. The weights of a bucket are nonnegative and sum to 1, since line L7 divides the posteriors, which sum to 1 per row, by the number of rows. So is a convex combination of distributions. It has no zeros as long as , which holds after every EM step from a start with all weights positive.
EM never lowers the held-out likelihood. By Jensen's inequality, in each bucket, where is the Kullback-Leibler divergence of the new weights from the old. The log likelihood is concave in the weights, so every point where no component can gain (the mean of is 1 for each weight in use and at most 1 for the others) is a global maximum, and the fixed points of EM with all weights positive are such points.
Proof: Deleted interpolation gives distributions, and its EM steps never lower the held-out likelihoodfull
Fix one bucket with components and its rows , , from line L3, where is the value of component on held-out token . The last component is the uniform one, so for every . The buckets do not share weights, so it is enough to treat one bucket. Let and
Lemma 1 (the step stays in the simplex). If and , then every , the step of lines L6 and L7 gives , and . If then .
Proof. . Let . Then for each , and line L7 sets , so and . Also for every , so . If , every and .
By Lemma 1 and line L4, which starts with all weights equal to , every iterate has and so all and is finite.
Theorem 2 (monotone likelihood). With and as in Lemma 1, , where .
Proof. Fix . For each with we have , and
The weights over the with sum to 1, and is concave, so by Jensen's inequality
If then , so each logarithm is finite. Sum over and use :
by Gibbs' inequality: , again by Jensen.
So the sequence does not decrease. It is bounded above by 0, since each , so it converges, and the test of line L8 is met after finitely many steps for any positive tolerance.
Theorem 3 (the fixed points are optima). is concave on . A point with maximizes over if and only if equals 1 for every with and is at most 1 for every other . Every fixed point of the EM step with all is such a maximum.
Proof. Each is linear in and is concave and increasing, so is concave, and so is the sum . is differentiable on the open set where all , which contains . For a concave differentiable function on the convex set , the point is a maximum if and only if for every . The partial derivatives are , and . Taking to be the vertices of , the condition is , that is , for every ; it then holds for every by linearity. Since and each , equality must hold for every with . This is the stated condition.
The EM step can be written . At a fixed point with all , for every , which is the condition above.
Theorem 4 (the final model). For every history , of line L9 is a distribution on , and for every if the bucket of has or no fitted weights.
Proof. For , and every token counted after is in , so . The uniform component sums to 1. The weights of the bucket lie in by Lemma 1, or are all equal to for a bucket with no held-out rows. A convex combination of distributions on is a distribution on , and it is positive where a component with positive weight is positive; the uniform component is positive everywhere.
Complexity
Counting the folds takes expected time each, with a hash table, so in all. There are rows of at most components, and one EM iteration takes time, so iterations take . The rows take space. The final model is a count table of size and the weights, and one query takes expected time. EM can be slow near the end: in the example the error shrinks by a factor of about per step.
Properties
- Data decides the mix. The weights are maximum likelihood estimates on held-out text, so they reflect how reliable each order is on new data.
- No zeros. The uniform component gives every word of some probability.
- Weights tied by buckets. Histories seen the same number of times share weights, which keeps the number of parameters small: a few dozen numbers for the whole model.
- Interpolated. Every n-gram, seen or not, gets mass from all lower orders.
- The deleted form uses all data. Every token is held out once, so no part of the text is lost to the counts of the final model.
- Floating point. The weights come from an iterative method, so they are not exact.
Variants and improvements
- Held-out interpolation. Fit the weights on one held-out set and use only the rest for counts. It is simpler but wastes data.
- The recursive form. , with one weight per bucket and order. Expanded, it is a mix of the same kind, with products of weights. This is the form of Jelinek-Mercer smoothing in Chen and Goodman (1999).
- Weights from counts. Witten-Bell smoothing uses the weight and needs no held-out data.
- Bucket rules. Chen and Goodman bucketed by the average count per non-zero word, , which worked better than the count alone.
- Grid or gradient search. With few weights, a direct search over the held-out perplexity gives the same optimum as EM.
- Other models. The same EM fits the weights of any mixture of fixed models, such as an interpolated Markov model of DNA or a cache language model.
When to use it
Use it when you have several estimates of the same distribution with different detail and you can afford to hold out text: word n-gram models, character models, models of DNA sequences, or mixtures of a general and a topic model. It is a good baseline that needs no tuning by hand. On word n-grams, Kneser-Ney smoothing is usually better, because it also changes the lower-order distributions.
Pitfalls
- Fitting the weights on the training text. On the text that gave the counts, the highest order already maximizes the likelihood, so EM puts all the weight on it and the model has zeros again. The data for the weights must be held out.
- Unseen histories. If , is . Drop the component and use the bucket of the longest seen history, as above, so that the weights of each bucket refer to the same components.
- Empty buckets. A bucket with no held-out rows has no fitted weights. Use equal weights or merge it with a neighbour.
- Zero weights stay zero. EM cannot move a weight that is exactly 0. Start every weight above 0.
- Slow convergence. Stop on a small change of the log likelihood, not on a fixed small number of steps.
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/deleted-interpolation/. The authors are listed in prov/S7TPCG.jsonl.
"""Deleted interpolation of n-gram estimates, with weights fitted by EM.
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 model is a mixture
P(w | h) = sum_j lambda_(b, j) P_j(w | h)
of the maximum likelihood estimates P_j of the orders m, m - 1, ..., 1 and
the uniform distribution 1 / |V|, where m is the longest order whose history
was seen in training. The weights depend on the bucket b = (m, the bit length
of c(h_m)) and are fitted by EM on held-out tokens. In the deleted version the
corpus is cut into parts, each part is held out in turn against the counts of
the others, and the final model uses the counts of the whole corpus.
"""
import math
from collections import Counter
from typing import Iterable, Sequence
BOS, EOS = "<s>", "</s>"
MAX_BUCKET = 8
def count_ngrams(corpus: Iterable[Sequence[str]], n: int):
"""Return (c, ch): the m-gram counts for m = 1 to n and the history counts."""
c: Counter = Counter()
ch: 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])
c[g] += 1
ch[g[:-1]] += 1
return c, ch
def events(corpus: Iterable[Sequence[str]], n: int):
"""Yield (w, h) for every predicted token, with h the n - 1 tokens before it."""
for sent in corpus:
toks = [BOS] * (n - 1) + list(sent) + [EOS]
for i in range(n - 1, len(toks)):
yield toks[i], tuple(toks[i - n + 1 : i])
class Components:
"""The maximum likelihood estimates of every order, plus the uniform distribution."""
def __init__(self, corpus: Iterable[Sequence[str]], n: int, vocab: set[str]):
self.n, self.vocab = n, vocab
self.c, self.ch = count_ngrams(corpus, n)
if self.ch[()] == 0:
raise ValueError("the training corpus has no tokens")
def __call__(self, w: str, h: tuple) -> tuple[tuple, list[float]]:
"""Return the bucket and the component probabilities of w after h."""
m = len(h)
while self.ch[h[len(h) - m :]] == 0:
m -= 1
hm = h[len(h) - m :]
probs = [self.c[hm[j:] + (w,)] / self.ch[hm[j:]] for j in range(m + 1)]
probs.append(1 / len(self.vocab))
return (m, min(self.ch[hm].bit_length(), MAX_BUCKET)), probs
def fit_weights(rows: dict[tuple, list[list[float]]], max_iter: int = 200, tol: float = 1e-12):
"""EM for the mixture weights of each bucket. Return (weights, log likelihood after each step)."""
lam = {b: [1 / len(ps[0])] * len(ps[0]) for b, ps in rows.items()} # @line L4
trace = []
for _ in range(max_iter): # @line L5
ll = 0.0
new = {}
for b, ps in rows.items():
e = [0.0] * len(lam[b])
for p in ps: # @line L6
z = sum(l * q for l, q in zip(lam[b], p))
ll += math.log(z)
for j, (l, q) in enumerate(zip(lam[b], p)):
e[j] += l * q / z
new[b] = [x / len(ps) for x in e] # @line L7
trace.append(ll)
lam = new
if len(trace) > 1 and trace[-1] - trace[-2] < tol: # @line L8
break
return lam, trace
def collect_rows(train: list[list[str]], held: list[list[str]], n: int, vocab: set[str], rows: dict):
"""Add the component probabilities of every held-out token, under the training counts."""
comp = Components(train, n, vocab) # @line L2
for w, h in events(held, n): # @line L3
b, p = comp(w, h)
rows.setdefault(b, []).append(p)
class InterpolatedLM:
"""The interpolated model with fixed weights and the counts of a corpus."""
def __init__(self, corpus: Iterable[Sequence[str]], n: int, weights: dict, vocab: set[str]):
self.n, self.weights, self.vocab = n, weights, vocab
self.comp = Components(corpus, n, vocab)
def prob(self, w: str, history: Sequence[str] = ()) -> float:
"""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 = ((BOS,) * (self.n - 1) + tuple(history))[len(history) :]
b, p = self.comp(w, h)
lam = self.weights.get(b) or [1 / len(p)] * len(p) # a bucket never seen in held-out data
return sum(l * q for l, q in zip(lam, p)) # @line L9
def distribution(self, history: Sequence[str] = ()) -> dict[str, float]:
"""The full conditional distribution over the vocabulary."""
return {w: self.prob(w, history) for w in sorted(self.vocab)}
def log_likelihood(self, corpus: Iterable[Sequence[str]]) -> float:
"""The natural log of the probability of a corpus, with every </s>."""
return sum(math.log(self.prob(w, h)) for w, h in events(corpus, self.n))
def make_vocab(corpus: Iterable[Sequence[str]], vocab: Iterable[str] | None) -> set[str]:
seen = {w for s in corpus for w in s} | {EOS}
v = set(seen) if vocab is None else set(vocab) | {EOS}
if BOS in v:
raise ValueError("<s> is never predicted, so it is not in the vocabulary")
if not seen <= v:
raise ValueError("the vocabulary must hold every token; map the others to <unk>")
return v
def heldout_interpolation(train, held, n: int, vocab: Iterable[str] | None = None) -> InterpolatedLM:
"""Fit the weights on one held-out set; the model keeps the training counts only."""
train, held = [list(s) for s in train], [list(s) for s in held]
v = make_vocab(train + held, vocab)
rows: dict = {}
collect_rows(train, held, n, v, rows)
weights, _ = fit_weights(rows)
return InterpolatedLM(train, n, weights, v)
def deleted_interpolation(corpus, n: int, parts: int = 2, vocab: Iterable[str] | None = None) -> InterpolatedLM:
"""Hold out each of the parts in turn, fit one set of weights, and count the whole corpus."""
if n < 1 or parts < 2:
raise ValueError("need n >= 1 and at least two parts")
corpus = [list(s) for s in corpus]
if len(corpus) < parts:
raise ValueError("need at least one sentence in each part")
v = make_vocab(corpus, vocab)
rows: dict = {}
for j in range(parts): # @line L1
held = corpus[j::parts]
train = [s for i, s in enumerate(corpus) if i % parts != j]
collect_rows(train, held, n, v, rows)
weights, _ = fit_weights(rows)
return InterpolatedLM(corpus, n, weights, v)
test_deleted_interpolation.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deleted-interpolation/. The authors are listed in prov/S7TPCG.jsonl.
import itertools
import math
import random
import pytest
from deleted_interpolation import (
BOS,
EOS,
Components,
deleted_interpolation,
fit_weights,
heldout_interpolation,
)
# three held-out tokens, with (bigram, unigram) probabilities
HAND = {"b": [[0.5, 0.25], [0.0, 0.125], [1.0, 0.5]]}
TOY = [s.split() for s in ["a b", "a c", "b c", "a b c", "c a b"]]
def test_hand_example() -> None:
lam, trace = fit_weights(HAND, max_iter=1)
assert math.isclose(lam["b"][0], 4 / 9)
lam, trace = fit_weights(HAND, max_iter=2)
assert math.isclose(lam["b"][0], 16 / 39)
# the log likelihood is log((1 + l)/4) + log((1 - l)/8) + log((1 + l)/2), largest at l = 1/3
lam, trace = fit_weights(HAND, max_iter=3000, tol=0.0)
assert abs(lam["b"][0] - 1 / 3) < 1e-6
assert math.isclose(sum(lam["b"]), 1.0)
def random_rows(rng: random.Random, k: int, size: int) -> list[list[float]]:
rows = []
for _ in range(size):
p = [rng.choice([0.0, rng.random()]) for _ in range(k - 1)]
p.append(rng.uniform(0.05, 0.3)) # the uniform component is never zero
rows.append(p)
return rows
def test_em_never_decreases_the_likelihood() -> None:
rng = random.Random(1)
for _ in range(30):
k = rng.randrange(2, 5)
rows = {"b": random_rows(rng, k, rng.randrange(1, 30))}
lam, trace = fit_weights(rows, max_iter=60, tol=-1.0)
for x, y in zip(trace, trace[1:]):
assert y >= x - 1e-9
assert math.isclose(sum(lam["b"]), 1.0) and min(lam["b"]) >= 0
def test_em_reaches_the_grid_optimum() -> None:
rng = random.Random(2)
for _ in range(20):
rows = random_rows(rng, 2, 20)
lam, trace = fit_weights({"b": rows}, max_iter=5000, tol=1e-14)
best = max(
sum(math.log(g * p[0] + (1 - g) * p[1]) for p in rows) for g in (i / 1000 for i in range(1000))
)
got = sum(math.log(lam["b"][0] * p[0] + lam["b"][1] * p[1]) for p in rows)
assert got >= best - 1e-6
def test_fixed_point_condition() -> None:
"""At the optimum, the mean of p_j / z is 1 for every component with positive weight, and at most 1 otherwise."""
rng = random.Random(3)
rows = random_rows(rng, 3, 40)
lam, _ = fit_weights({"b": rows}, max_iter=5000, tol=1e-15)
lam = lam["b"]
for j in range(3):
g = sum(p[j] / sum(l * q for l, q in zip(lam, p)) for p in rows) / len(rows)
if lam[j] > 1e-3:
assert abs(g - 1) < 1e-3
else:
assert g <= 1 + 1e-3
def test_components_use_the_longest_seen_history() -> None:
comp = Components(TOY, 3, {"a", "b", "c", EOS})
b, p = comp("b", ("c", "a"))
assert b == (2, 1) and p == [1.0, 3 / 4, 4 / 17, 1 / 4]
b, p = comp("b", ("b", "a")) # "b a" never seen, "a" seen 4 times
assert b == (1, 3) and p == [3 / 4, 4 / 17, 1 / 4]
def test_rows_sum_to_one() -> None:
rng = random.Random(9)
words = ["a", "b", "c", "d"]
for trial in range(40):
n = rng.randrange(1, 4)
corpus = [[rng.choice(words[:3]) for _ in range(rng.randrange(0, 6))] for _ in range(rng.randrange(3, 9))]
if trial % 2:
m = deleted_interpolation(corpus, n, parts=rng.randrange(2, 4), vocab=words)
else:
m = heldout_interpolation(corpus[1:], corpus[:1], n, vocab=words)
for lam in m.weights.values():
assert math.isclose(sum(lam), 1.0) and min(lam) >= 0
for h in itertools.product([BOS] + words, repeat=n - 1):
d = m.distribution(h)
assert math.isclose(sum(d.values()), 1.0, abs_tol=1e-12)
assert all(p > 0 for p in d.values())
def test_unseen_test_tokens_get_mass() -> None:
m = deleted_interpolation(TOY, 2, parts=2, vocab={"a", "b", "c", "d"})
ll = m.log_likelihood([["d", "a"], ["c", "c"]])
assert math.isfinite(ll)
assert m.prob("d", ["a"]) > 0
def test_errors() -> None:
with pytest.raises(ValueError):
deleted_interpolation(TOY, 2, parts=1)
with pytest.raises(ValueError):
deleted_interpolation(TOY[:1], 2, parts=2)
with pytest.raises(ValueError):
deleted_interpolation(TOY, 2, vocab={"a"})
with pytest.raises(ValueError):
deleted_interpolation(TOY, 2, vocab={"a", "b", "c", BOS})
m = deleted_interpolation(TOY, 2)
with pytest.raises(KeyError):
m.prob("z", ["a"])
History
Frederick Jelinek and Robert Mercer described interpolated estimation of Markov source parameters at a workshop on pattern recognition in practice in 1980, from their work on speech recognition at IBM. They fitted the weights by the forward-backward method of hidden Markov models, since a mixture is the same as a hidden choice of the component, and they tied the weights of histories with similar counts. The deleted form, which holds out each block of the training data in turn, gave the method its name. Chen and Goodman (1999) compared it, as Jelinek-Mercer smoothing, with the other classical methods.
References
- Jelinek and Mercer 1980, the interpolated estimate, the fit of its weights on held-out data, the deleted form, and the tying of the weights by the count of the history
- Arthur P. Dempster, Nan M. Laird and Donald B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society Series B 39(1), 1977, the EM algorithm and the proof that each step does not decrease the likelihood
- 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, Jelinek-Mercer smoothing with the weights bucketed by the count of the history, and its measured performance
- Christopher D. Manning and Hinrich Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999, Chapter 6, Section 6.3 (combining estimators, with linear interpolation and its weights)
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 S7TPCG Edit this page History Report an error Markdown