Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 n−1n - 1 start markers <s> on the left and one </s> on the right. The vocabulary VV holds every predicted token, with </s> and <unk>. For a history hh of n−1n - 1 tokens, write hjh_j for its last jj tokens, so h0=ϵh_0 = \epsilon. Let pj(w∣h)=c(hjw)/c(hj)p_j(w \mid h) = c(h_j w)/c(h_j) be the maximum likelihood estimate of order j+1j + 1, defined when c(hj)>0c(h_j) > 0, and pu(w)=1/∣V∣p_{\mathrm{u}}(w) = 1/|V|. Let m(h)m(h) be the largest jj with c(hj)>0c(h_j) > 0. The model is

P(w∣h)=∑j=0m(h)λb,j pj(w∣h)+λb,u 1∣V∣,b=b(h),P(w \mid h) = \sum_{j=0}^{m(h)} \lambda_{b,j} \, p_j(w \mid h) + \lambda_{b,\mathrm{u}} \, \frac{1}{|V|}, \qquad b = b(h),

with weights λb,⋅≥0\lambda_{b,\cdot} \ge 0 that sum to 1 in each bucket bb. The bucket groups histories that should share weights. Here b(h)b(h) is the pair of m(h)m(h) and the number of bits of c(hm(h))c(h_{m(h)}), 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 KK parts B1,…,BKB_1, \ldots, B_K. 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.

  1. DELETED-INTERPOLATION(B_1 .. B_K, n)
  2. 1for j ← 1 to K do
  3. 2count the n-grams of every part except B_j
  4. 3for 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
  5. 4for each bucket b do give each of its components the weight 1 / (its number of components)
  6. 5repeat
  7. 6for 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
  8. 7for each bucket b and component i do λ_{b,i} ← e_{b,i} / |R_b|; e_{b,i} ← 0
  9. 8until the log likelihood Σ_rows log z rises by less than a tolerance
  10. 9count 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: λb,ipi/z\lambda_{b,i} p_i / z is the posterior chance that component ii 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 K=1K = 1 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 (1/2,1/4)(1/2, 1/4), (0,1/8)(0, 1/8) and (1,1/2)(1, 1/2). Write λ\lambda for the weight of the bigram. The log likelihood is

L(λ)=log⁡1+λ4+log⁡1−λ8+log⁡1+λ2.L(\lambda) = \log \frac{1 + \lambda}{4} + \log \frac{1 - \lambda}{8} + \log \frac{1 + \lambda}{2}.

Start at λ=1/2\lambda = 1/2. The posteriors of the bigram are 1/43/8=2/3\frac{1/4}{3/8} = 2/3, 00 and 1/23/4=2/3\frac{1/2}{3/4} = 2/3, so the M step gives λ=(2/3+0+2/3)/3=4/9\lambda = (2/3 + 0 + 2/3)/3 = 4/9. The next step gives 16/39=0.41016/39 = 0.410. In general one step maps λ\lambda to 4λ3(1+λ)\frac{4\lambda}{3(1+\lambda)}, and the steps converge to λ=1/3\lambda = 1/3, where L′(λ)=21+λ−11−λ=0L'(\lambda) = \frac{2}{1+\lambda} - \frac{1}{1-\lambda} = 0. There the three tokens get 1/31/3, 1/121/12 and 2/32/3, for a product of 1/541/54. The bigram alone (λ=1\lambda = 1) gives the second token 0, and the unigram alone gives the product 1/641/64.

Correctness

Every row is a distribution. Each component pj(⋅∣h)p_j(\cdot \mid h) with j≤m(h)j \le m(h) sums to 1 over VV, because all its counts are of tokens in VV, 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 P(⋅∣h)P(\cdot \mid h) is a convex combination of distributions. It has no zeros as long as λb,u>0\lambda_{b,\mathrm{u}} > 0, which holds after every EM step from a start with all weights positive.

EM never lowers the held-out likelihood. By Jensen's inequality, L(λ′)−L(λ)≥∣R∣ D(λ′ ∥ λ)≥0L(\lambda') - L(\lambda) \ge |R| \, D(\lambda' \,\|\, \lambda) \ge 0 in each bucket, where DD is the Kullback-Leibler divergence of the new weights from the old. The log likelihood ∑log⁡∑iλb,ipi\sum \log \sum_i \lambda_{b,i} p_i is concave in the weights, so every point where no component can gain (the mean of pi/zp_i / z 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 bb with JJ components and its rows p(1),…,p(M)p^{(1)}, \ldots, p^{(M)}, M≥1M \ge 1, from line L3, where pi(t)≥0p^{(t)}_i \ge 0 is the value of component ii on held-out token tt. The last component is the uniform one, so pJ(t)=1/∣V∣>0p^{(t)}_J = 1/|V| > 0 for every tt. The buckets do not share weights, so it is enough to treat one bucket. Let Δ={λ∈RJ:λi≥0,∑iλi=1}\Delta = \{\lambda \in \mathbb{R}^J : \lambda_i \ge 0, \sum_i \lambda_i = 1\} and

L(λ)=∑t=1Mlog⁡zt(λ),zt(λ)=∑i=1Jλipi(t).L(\lambda) = \sum_{t=1}^{M} \log z_t(\lambda), \qquad z_t(\lambda) = \sum_{i=1}^{J} \lambda_i p^{(t)}_i .

Lemma 1 (the step stays in the simplex). If λ∈Δ\lambda \in \Delta and λJ>0\lambda_J > 0, then every zt(λ)>0z_t(\lambda) > 0, the step of lines L6 and L7 gives λ′∈Δ\lambda' \in \Delta, and λJ′>0\lambda'_J > 0. If λi=0\lambda_i = 0 then λi′=0\lambda'_i = 0.

Proof. zt≥λJ/∣V∣>0z_t \ge \lambda_J / |V| > 0. Let rti=λipi(t)/zt≥0r_{ti} = \lambda_i p^{(t)}_i / z_t \ge 0. Then ∑irti=1\sum_i r_{ti} = 1 for each tt, and line L7 sets λi′=1M∑trti\lambda'_i = \frac1M \sum_t r_{ti}, so λi′≥0\lambda'_i \ge 0 and ∑iλi′=1M∑t1=1\sum_i \lambda'_i = \frac1M \sum_t 1 = 1. Also rtJ>0r_{tJ} > 0 for every tt, so λJ′>0\lambda'_J > 0. If λi=0\lambda_i = 0, every rti=0r_{ti} = 0 and λi′=0\lambda'_i = 0. □\square

By Lemma 1 and line L4, which starts with all weights equal to 1/J1/J, every iterate has λJ>0\lambda_J > 0 and so all zt>0z_t > 0 and LL is finite.

Theorem 2 (monotone likelihood). With λ\lambda and λ′\lambda' as in Lemma 1, L(λ′)−L(λ)≥M D(λ′ ∥ λ)≥0L(\lambda') - L(\lambda) \ge M \, D(\lambda' \,\|\, \lambda) \ge 0, where D(λ′∥λ)=∑i:λi′>0λi′log⁡(λi′/λi)D(\lambda' \| \lambda) = \sum_{i : \lambda'_i > 0} \lambda'_i \log(\lambda'_i / \lambda_i).

Proof. Fix tt. For each ii with rti>0r_{ti} > 0 we have λi>0\lambda_i > 0, and

zt(λ′)zt(λ)=∑iλi′pi(t)zt(λ)≥∑i:rti>0rtiλi′λi.\frac{z_t(\lambda')}{z_t(\lambda)} = \sum_i \frac{\lambda'_i p^{(t)}_i}{z_t(\lambda)} \ge \sum_{i : r_{ti} > 0} r_{ti} \frac{\lambda'_i}{\lambda_i}.

The weights rtir_{ti} over the ii with rti>0r_{ti} > 0 sum to 1, and log⁡\log is concave, so by Jensen's inequality

log⁡zt(λ′)zt(λ)≥∑i:rti>0rtilog⁡λi′λi.\log \frac{z_t(\lambda')}{z_t(\lambda)} \ge \sum_{i : r_{ti} > 0} r_{ti} \log \frac{\lambda'_i}{\lambda_i}.

If rti>0r_{ti} > 0 then λi′>0\lambda'_i > 0, so each logarithm is finite. Sum over tt and use ∑trti=Mλi′\sum_t r_{ti} = M \lambda'_i:

L(λ′)−L(λ)≥∑i:λi′>0Mλi′log⁡λi′λi=M D(λ′∥λ).L(\lambda') - L(\lambda) \ge \sum_{i : \lambda'_i > 0} M \lambda'_i \log \frac{\lambda'_i}{\lambda_i} = M \, D(\lambda' \| \lambda).

D(λ′∥λ)≥0D(\lambda' \| \lambda) \ge 0 by Gibbs' inequality: −D=∑i:λi′>0λi′log⁡(λi/λi′)≤log⁡∑i:λi′>0λi≤log⁡1=0-D = \sum_{i : \lambda'_i > 0} \lambda'_i \log(\lambda_i / \lambda'_i) \le \log \sum_{i : \lambda'_i > 0} \lambda_i \le \log 1 = 0, again by Jensen. □\square

So the sequence L(λ(0))≤L(λ(1))≤⋯L(\lambda^{(0)}) \le L(\lambda^{(1)}) \le \cdots does not decrease. It is bounded above by 0, since each zt≤max⁡ipi(t)≤1z_t \le \max_i p^{(t)}_i \le 1, 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). LL is concave on Δ\Delta. A point λ∈Δ\lambda \in \Delta with λJ>0\lambda_J > 0 maximizes LL over Δ\Delta if and only if gi(λ)=1M∑tpi(t)/zt(λ)g_i(\lambda) = \frac1M \sum_t p^{(t)}_i / z_t(\lambda) equals 1 for every ii with λi>0\lambda_i > 0 and is at most 1 for every other ii. Every fixed point of the EM step with all λi>0\lambda_i > 0 is such a maximum.

Proof. Each ztz_t is linear in λ\lambda and log⁡\log is concave and increasing, so log⁡zt\log z_t is concave, and so is the sum LL. LL is differentiable on the open set where all zt>0z_t > 0, which contains λ\lambda. For a concave differentiable function on the convex set Δ\Delta, the point λ\lambda is a maximum if and only if ∇L(λ)⋅(μ−λ)≤0\nabla L(\lambda) \cdot (\mu - \lambda) \le 0 for every μ∈Δ\mu \in \Delta. The partial derivatives are ∂L/∂λi=Mgi\partial L / \partial \lambda_i = M g_i, and ∇L(λ)⋅λ=∑tzt/zt=M\nabla L(\lambda) \cdot \lambda = \sum_t z_t / z_t = M. Taking μ\mu to be the vertices of Δ\Delta, the condition is Mgi≤MM g_i \le M, that is gi≤1g_i \le 1, for every ii; it then holds for every μ\mu by linearity. Since ∑iλigi=1\sum_i \lambda_i g_i = 1 and each gi≤1g_i \le 1, equality gi=1g_i = 1 must hold for every ii with λi>0\lambda_i > 0. This is the stated condition.

The EM step can be written λi′=λigi(λ)\lambda'_i = \lambda_i g_i(\lambda). At a fixed point with all λi>0\lambda_i > 0, gi=1g_i = 1 for every ii, which is the condition above. ■\blacksquare

Theorem 4 (the final model). For every history hh, P(⋅∣h)P(\cdot \mid h) of line L9 is a distribution on VV, and P(w∣h)>0P(w \mid h) > 0 for every w∈Vw \in V if the bucket of hh has λb,u>0\lambda_{b,\mathrm{u}} > 0 or no fitted weights.

Proof. For j≤m(h)j \le m(h), c(hj)>0c(h_j) > 0 and every token counted after hjh_j is in VV, so ∑w∈Vc(hjw)/c(hj)=1\sum_{w \in V} c(h_j w)/c(h_j) = 1. The uniform component sums to 1. The weights of the bucket lie in Δ\Delta by Lemma 1, or are all equal to 1/J1/J for a bucket with no held-out rows. A convex combination of distributions on VV is a distribution on VV, and it is positive where a component with positive weight is positive; the uniform component is positive everywhere. ■\blacksquare

Complexity

Counting the KK folds takes Θ(nN)\Theta(n N) expected time each, with a hash table, so Θ(KnN)\Theta(K n N) in all. There are NN rows of at most n+1n + 1 components, and one EM iteration takes Θ(nN)\Theta(n N) time, so II iterations take Θ(InN)\Theta(I n N). The rows take Θ(nN)\Theta(n N) space. The final model is a count table of size Θ(nN)\Theta(n N) and the weights, and one query takes Θ(n)\Theta(n) expected time. EM can be slow near the end: in the example the error shrinks by a factor of about 3/43/4 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 VV 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. P(w∣h)=λ(h)pML(w∣h)+(1−λ(h))P(w∣h′)P(w \mid h) = \lambda(h) p_{\mathrm{ML}}(w \mid h) + (1 - \lambda(h)) P(w \mid h'), 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 c(h)/(c(h)+T(h))c(h)/(c(h) + T(h)) and needs no held-out data.
  • Bucket rules. Chen and Goodman bucketed by the average count per non-zero word, c(h)/T(h)c(h)/T(h), which worked better than the count c(h)c(h) 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 c(hj)=0c(h_j) = 0, pjp_j is 0/00/0. 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.

deleted_interpolation.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

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