Algorithm Search⌘K

Algorithmcore

Katz backoff

Also called Katz smoothing, Katz back-off model.

An n-gram model that uses discounted counts for the n-grams it has seen and backs off to the shorter history, scaled by a weight alpha(h), for the ones it has not.

Time
Θ(n N) worst
Space
Θ(n N) extra
Where
N = the number of training tokens; n = the order of the model
Properties
deterministicexactofflinerecursive
Origin
Slava M. Katz, 1987

Katz backoff turns the counts of an n-gram language model into probabilities that are never zero. If the n-gram was seen in training, the model uses its count, made a little smaller by a Good-Turing discount. If it was not seen, the model drops the oldest word of the history and asks the shorter model, and it scales that answer by a weight α(h)\alpha(h) so that the probabilities after each history still sum to 1. It is a backoff method: unlike Witten-Bell smoothing or deleted interpolation, it uses the lower order only for the words not seen after the history, and unlike absolute discounting it takes its discounts from the counts of counts.

In plain words

To guess the next word after "the red", look at what followed "the red" in the training text. If the word you ask about followed it, use how often it did, but trust the count a little less than it says, because small counts are lucky. The small amount you took away from these words is put aside.

If the word never followed "the red", forget "the" and ask how likely the word is after "red" alone, and if needed after nothing at all. Then share the amount put aside among all the words that never followed "the red", in proportion to these simpler guesses. Every word gets a chance, and the chances still add up to one.

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 is the set of predicted tokens, which holds </s> and, after rare words are mapped to it, <unk>. 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 and c(h)=∑wc(hw)c(h) = \sum_w c(h w). Write h′h' for hh without its first token and ϵ\epsilon for the empty history, with c(ϵ)=Nc(\epsilon) = N. The task is a distribution P(w∣h)P(w \mid h) over VV for every history, with positive values for the seen n-grams.

The algorithm

For each order m≥2m \ge 2, let NrN_r be the number of m-grams seen exactly rr times. Katz keeps the counts above a cut-off kk (he used k=5k = 5) and discounts the counts 1≤r≤k1 \le r \le k by the ratio

dr=r∗/r−μ1−μ,r∗=(r+1)Nr+1Nr,μ=(k+1)Nk+1N1.d_r = \frac{r^*/r - \mu}{1 - \mu}, \qquad r^* = (r+1) \frac{N_{r+1}}{N_r}, \qquad \mu = \frac{(k+1) N_{k+1}}{N_1}.

These ratios are the Good-Turing ratios r∗/rr^*/r, changed so that the counts above kk are not discounted and the total mass taken away is still N1N_1, the Good-Turing mass of the unseen m-grams. For r>kr > k, dr=1d_r = 1. The unigrams use the maximum likelihood estimate c(w)/Nc(w)/N.

  1. P-KATZ(w, h) ▷ c and the d_r counted once on the training text
  2. 1if h = ε then return c(w) / N
  3. 2if c(h) = 0 then return P-KATZ(w, h')
  4. 3if c(h w) > 0 then
  5. 4return d_{c(h w)} c(h w) / c(h)
  6. 5β(h) ← 1 - Σ_{v : c(h v) > 0} d_{c(h v)} c(h v) / c(h) ▷ the mass taken from the seen words
  7. 6γ(h) ← 1 - Σ_{v : c(h v) > 0} P-KATZ(v, h') ▷ the lower-order mass of the unseen words
  8. 7α(h) ← β(h) / γ(h)
  9. 8return α(h) P-KATZ(w, h')

Line L4 is the discounted estimate of a seen n-gram. Lines L5 to L7 compute the backoff weight, which depends only on hh and is stored once per history. Line L8 gives an unseen word its lower-order probability, scaled so that the unseen words of hh share exactly β(h)\beta(h).

Example

Train a bigram model on the four sentences "a a b", "a b c", "a" and "c a", with k=2k = 2. There are N=13N = 13 predicted tokens: a 5 times, </s> 4 times, b and c twice each. The nine bigram types have the counts <s> a 3, a b 2, a </s> 2, and 1 for each of <s> c, a a, b c, b </s>, c a and c </s>. So N1=6N_1 = 6, N2=2N_2 = 2, N3=1N_3 = 1, and

μ=3⋅16=12,r1∗=2⋅26=23,r2∗=3⋅12=32,d1=2/3−1/21/2=13,d2=3/4−1/21/2=12.\mu = \frac{3 \cdot 1}{6} = \frac12, \quad r^*_1 = \frac{2 \cdot 2}{6} = \frac23, \quad r^*_2 = \frac{3 \cdot 1}{2} = \frac32, \quad d_1 = \frac{2/3 - 1/2}{1/2} = \frac13, \quad d_2 = \frac{3/4 - 1/2}{1/2} = \frac12.

The discounts take away 6⋅1⋅23+2⋅2⋅12=6=N16 \cdot 1 \cdot \tfrac23 + 2 \cdot 2 \cdot \tfrac12 = 6 = N_1 counts in all. After the history a, seen 5 times, the seen words get a 13⋅15=115\tfrac13 \cdot \tfrac15 = \tfrac1{15}, b 12⋅25=15\tfrac12 \cdot \tfrac25 = \tfrac15 and </s> 15\tfrac15. So β(a)=8/15\beta(a) = 8/15. The only unseen word is c, with unigram probability 2/132/13, so γ(a)=2/13\gamma(a) = 2/13, α(a)=52/15\alpha(a) = 52/15 and P(c∣a)=8/15P(c \mid a) = 8/15.

history hh c(h)c(h) α(h)\alpha(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> 4 13/36 1/9 3/4 1/18 1/12
a 5 52/15 1/5 1/15 1/5 8/15
b 2 26/21 1/6 10/21 4/21 1/6
c 2 13/6 1/6 1/6 1/3 1/3

The count 3 of <s> a is above kk, so it is not discounted: P(a∣⟨s⟩)=3/4P(a \mid \langle s \rangle) = 3/4. Each row sums to 1. The sentence "a b" gets 34⋅15⋅16=1/40\tfrac34 \cdot \tfrac15 \cdot \tfrac16 = 1/40. Note that α(h)\alpha(h) is not a probability; it can be larger than 1.

Correctness

Every row is a distribution. If some word is unseen after hh and γ(h)>0\gamma(h) > 0, the seen words get 1−β(h)1 - \beta(h) by line L5, and the unseen words get α(h)∑unseenP(w∣h′)=α(h)γ(h)=β(h)\alpha(h) \sum_{\text{unseen}} P(w \mid h') = \alpha(h) \gamma(h) = \beta(h), by induction on the length of hh (the lower row sums to 1). So the row sums to 1. If every word of VV was seen after hh, there is nothing to back off to, and the implementation keeps the undiscounted estimates c(hw)/c(h)c(h w)/c(h) for that history.

The discounted mass is N1N_1. When the ratios are valid, ∑r=1kNr r(1−dr)=N1\sum_{r=1}^{k} N_r \, r (1 - d_r) = N_1. This is the Good-Turing estimate of the total count of the unseen m-grams, so Katz gives the unseen events the same total as Good-Turing, but takes it only from the counts 11 to kk.

Proof: Katz backoff gives every history a distribution over the vocabulary, and its discounts take away exactly N_1 countsfull

Fix the padded training text and the vocabulary VV, the set of predicted training tokens. For a history hh, 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), S(h)={w:c(hw)>0}S(h) = \{w : c(h w) > 0\}, and h′h' is hh without its first token. For an order mm and 1≤r1 \le r, dr∈(0,1]d_r \in (0, 1] is the discount ratio of the m-grams seen rr times, with dr=1d_r = 1 for r>kr > k or when the order is left undiscounted. If S(h)=VS(h) = V, the history keeps its undiscounted estimates: we then write d=1d = 1 for all its words and α(h)=0\alpha(h) = 0, as the implementation does.

Lemma 1 (the discounted mass). Let NrN_r be the number of m-grams seen rr times, with N1>0N_1 > 0 and μ=(k+1)Nk+1/N1<1\mu = (k+1) N_{k+1}/N_1 < 1. For each 1≤r≤k1 \le r \le k with Nr>0N_r > 0 let r∗=(r+1)Nr+1/Nrr^* = (r+1) N_{r+1}/N_r and dr=(r∗/r−μ)/(1−μ)d_r = (r^*/r - \mu)/(1 - \mu), and assume that all these drd_r lie in (0,1](0, 1], which is the test that the implementation makes before it uses them. Then Nr>0N_r > 0 for every 1≤r≤k+11 \le r \le k + 1, and

∑r=1kNr r (1−dr)=N1.\sum_{r=1}^{k} N_r \, r \, (1 - d_r) = N_1 .

Proof. First, the counts of counts have no gap up to k+1k + 1. Suppose Nr>0N_r > 0 for some r≤kr \le k. If Nr+1=0N_{r+1} = 0, then r∗=0r^* = 0 and dr=−μ/(1−μ)≤0d_r = -\mu/(1 - \mu) \le 0, which is not in (0,1](0, 1]. So Nr+1>0N_{r+1} > 0. Since N1>0N_1 > 0, induction on rr gives Nr>0N_r > 0 for r=1,2,…,k+1r = 1, 2, \ldots, k + 1.

Next, 1−dr=(1−r∗/r)/(1−μ)1 - d_r = (1 - r^*/r)/(1 - \mu), so

Nr r (1−dr)=rNr−Nrr∗1−μ=rNr−(r+1)Nr+11−μ.N_r \, r \, (1 - d_r) = \frac{r N_r - N_r r^*}{1 - \mu} = \frac{r N_r - (r+1) N_{r+1}}{1 - \mu}.

Summed over r=1,…,kr = 1, \ldots, k, the numerators telescope to N1−(k+1)Nk+1=N1(1−μ)N_1 - (k+1) N_{k+1} = N_1 (1 - \mu), and dividing by 1−μ1 - \mu gives N1N_1. □\square

Theorem 2 (a proper distribution). For every history hh, PK(w∣h)≥0P_{K}(w \mid h) \ge 0 for w∈Vw \in V and ∑w∈VPK(w∣h)=1\sum_{w \in V} P_K(w \mid h) = 1. If c(hw)>0c(h w) > 0, then PK(w∣h)>0P_K(w \mid h) > 0.

Proof. By induction on the length of hh.

Length 0. Line L1 gives c(w)/N≥0c(w)/N \ge 0, and ∑w∈Vc(w)=N\sum_{w \in V} c(w) = N because VV is the set of predicted tokens. If c(w)>0c(w) > 0 the value is positive.

Length ℓ≥1\ell \ge 1, c(h)=0c(h) = 0. Line L2 returns the row of h′h', which has the properties by the induction hypothesis. No ww has c(hw)>0c(h w) > 0.

Length ℓ≥1\ell \ge 1, c(h)>0c(h) > 0, S(h)=VS(h) = V. Every word gets c(hw)/c(h)c(h w)/c(h), and these sum to 1.

Length ℓ≥1\ell \ge 1, c(h)>0c(h) > 0, S(h)≠VS(h) \ne V. For w∈S(h)w \in S(h), line L4 gives dc(hw)c(hw)/c(h)>0d_{c(h w)} c(h w)/c(h) > 0, since d>0d > 0. Line L5 gives β(h)=1−∑v∈S(h)dc(hv)c(hv)/c(h)≥1−∑v∈S(h)c(hv)/c(h)=0\beta(h) = 1 - \sum_{v \in S(h)} d_{c(h v)} c(h v)/c(h) \ge 1 - \sum_{v \in S(h)} c(h v)/c(h) = 0, since d≤1d \le 1. Line L6 gives γ(h)=1−∑v∈S(h)PK(v∣h′)=∑w∉S(h)PK(w∣h′)\gamma(h) = 1 - \sum_{v \in S(h)} P_K(v \mid h') = \sum_{w \notin S(h)} P_K(w \mid h'), by the induction hypothesis for h′h'. If γ(h)>0\gamma(h) > 0, line L7 gives α(h)=β(h)/γ(h)≥0\alpha(h) = \beta(h)/\gamma(h) \ge 0 and

∑w∈VPK(w∣h)=(1−β(h))+α(h)∑w∉S(h)PK(w∣h′)=1−β(h)+β(h)γ(h)γ(h)=1.\sum_{w \in V} P_K(w \mid h) = (1 - \beta(h)) + \alpha(h) \sum_{w \notin S(h)} P_K(w \mid h') = 1 - \beta(h) + \frac{\beta(h)}{\gamma(h)} \gamma(h) = 1.

If γ(h)=0\gamma(h) = 0, the lower order gives all its mass to the words of S(h)S(h), and the implementation treats hh as in the case S(h)=VS(h) = V, with the undiscounted estimates, whose sum over S(h)S(h) is 1, and with 0 for the other words. ■\blacksquare

Remark. The weight α(h)\alpha(h) can exceed 1, since γ(h)\gamma(h) can be smaller than β(h)\beta(h). It is a scale factor, not a probability. Lemma 1 shows that, per order, the counts taken away sum to the Good-Turing estimate N1N_1 of the total count of the unseen m-grams; Theorem 2 shows that the backoff weights then pass exactly the mass β(h)\beta(h) of each history to its unseen words.

Complexity

One pass over the training text with a hash table or a trie counts all m-grams for m≤nm \le n in Θ(nN)\Theta(n N) expected time and Θ(nN)\Theta(n N) space. The counts of counts and the drd_r take time linear in the number of n-gram types. The weight α(h)\alpha(h) sums over the words seen after hh, so all weights together take time linear in the number of n-gram types times nn. After that, one query takes Θ(n)\Theta(n) expected time. Models are usually stored in the ARPA format, which holds log⁡10P\log_{10} P for each seen n-gram and log⁡10α(h)\log_{10} \alpha(h) for each history.

Properties

  • Backoff, not interpolation. A seen n-gram uses only its own discounted count; the lower order is used only for unseen words.
  • Large counts are trusted. Counts above kk are kept, since the Good-Turing ratio r∗/rr^*/r is close to 1 there and the NrN_r are noisy.
  • Same unseen mass as Good-Turing. The discounts take away exactly N1N_1 counts per order.
  • Not monotone. The ratios drd_r come from the noisy NrN_r, so a larger count can get a larger discount.
  • Can raise unseen words above seen ones. In the example, the unseen bigram a c gets 8/158/15 while the seen a a gets 1/151/15, because c is frequent after other histories.

Variants and improvements

  • Smoothed counts of counts. Compute the r∗r^* with simple Good-Turing instead of the raw formula.
  • Absolute discounting with backoff replaces drd_r by a fixed discount, r−Dr - D.
  • Kneser-Ney smoothing backs off to a continuation distribution, which counts in how many contexts a word occurs, not how often. Chen and Goodman (1999) found it better than Katz.
  • Stupid backoff drops the normalization: it backs off with a fixed factor such as 0.4 and gives scores that do not sum to 1, which is enough for very large corpora.
  • Pruning. Entropy-based pruning removes n-grams from a backoff model and recomputes the α(h)\alpha(h).

When to use it

Use it for a word n-gram model when you want a normalized backoff model in the ARPA format, for example for a speech recognizer or for lattice rescoring. On most data modified Kneser-Ney smoothing gives a lower perplexity, but Katz models are simple and well understood. For small vocabularies, such as characters or DNA, where almost every n-gram is seen, the discounts matter less and a simple interpolated model is enough.

Pitfalls

  • Invalid discounts. The formula needs N1>0N_1 > 0, μ<1\mu < 1, and every drd_r in (0,1](0, 1]. On small or filtered data this fails. The implementation then leaves that order undiscounted.
  • k=1k = 1 deletes the singletons. With k=1k = 1, r1∗=2N2/N1=μr^*_1 = 2 N_2 / N_1 = \mu, so d1=0d_1 = 0 and every n-gram seen once gets probability 0 from its own count. Use k≥2k \ge 2.
  • No unseen words. If every word of VV follows hh, then γ(h)=0\gamma(h) = 0 and α(h)\alpha(h) is undefined. Keep the undiscounted estimates for such a history.
  • Discounts per order. The NrN_r and the drd_r are computed separately for each order mm.
  • <s> and </s>. <s> is never predicted and is not counted in NN; </s> is predicted and counted. A history that holds only <s> is seen once per sentence.

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.

katz_backoff.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/katz-backoff/. The authors are listed in prov/99DA92.jsonl.

"""Katz backoff for 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 vocabulary is the set of predicted training tokens: map rare
or unknown words to "<unk>" before training. The unigram level is the
maximum likelihood estimate c(w) / N.

For an order m >= 2, an m-gram seen r times gets the discount ratio

    d_r = (r* / r - mu) / (1 - mu),  r* = (r + 1) N_(r+1) / N_r,  mu = (k + 1) N_(k+1) / N_1

for 1 <= r <= k, and d_r = 1 for r > k, where N_r counts the m-gram types
seen r times (Katz 1987). If these values are not all in (0, 1], the order
is left undiscounted (d_r = 1 for every r).
"""

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

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


def count_ngrams(corpus: Iterable[Sequence[str]], n: int):
    """Return (c, ch, follow): m-gram counts for m = 1 to n, history counts, and the words seen after each history."""
    c: Counter = Counter()
    ch: Counter = Counter()
    follow: dict[tuple, set] = {}
    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
                follow.setdefault(g[:-1], set()).add(g[-1])
    return c, ch, follow


def katz_discounts(nr: dict[int, int], k: int) -> dict[int, Fraction]:
    """Return {r: d_r} for 1 <= r <= k, or {} when the Katz discounts are not valid."""
    if k < 1 or nr.get(1, 0) == 0:
        return {}
    mu = Fraction((k + 1) * nr.get(k + 1, 0), nr[1])
    if mu >= 1:
        return {}
    d = {}
    for r in range(1, k + 1):
        if nr.get(r, 0) == 0:
            continue
        rstar = Fraction((r + 1) * nr.get(r + 1, 0), nr[r])
        d[r] = (rstar / r - mu) / (1 - mu)
        if not 0 < d[r] <= 1:
            return {}
    return d


class KatzLM:
    """A Katz backoff n-gram model with Good-Turing discounts for the counts 1 to k."""

    def __init__(self, corpus: Iterable[Sequence[str]], n: int, k: int = 5):
        if n < 1:
            raise ValueError("the order n must be at least 1")
        self.n, self.k = n, k
        self.c, self.ch, self.follow = count_ngrams([list(s) for s in corpus], n)
        self.vocab = {g[0] for g in self.c if len(g) == 1}
        self.total = self.ch[()]
        self.d: dict[int, dict[int, Fraction]] = {}
        for m in range(2, n + 1):
            nr = Counter(v for g, v in self.c.items() if len(g) == m)
            self.d[m] = katz_discounts(dict(nr), k)
        self._alpha: dict[tuple, Fraction] = {}
        self._ml: set[tuple] = set()

    def discounted(self, h: tuple, w: str) -> Fraction:
        """The discounted estimate d_r r / c(h) of a seen m-gram h w."""
        r = self.c[h + (w,)]
        d = 1 if h in self._ml else self.d[len(h) + 1].get(r, 1)
        return d * Fraction(r, self.ch[h])

    def alpha(self, h: tuple) -> Fraction:
        """The backoff weight of the history h, with c(h) > 0."""
        if h not in self._alpha:
            seen = self.follow[h]
            beta = 1 - sum(self.discounted(h, w) for w in seen)  # @line L5
            low = 1 - sum(self._prob(w, h[1:]) for w in seen)  # @line L6
            if low == 0:
                self._ml.add(h)  # nothing to back off to: keep the undiscounted estimates
                self._alpha[h] = Fraction(0)
            else:
                self._alpha[h] = beta / low  # @line L7
        return self._alpha[h]

    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 not h:  # @line L1
            return Fraction(self.c[(w,)], self.total)
        if self.ch[h] == 0:  # @line L2
            return self._prob(w, h[1:])
        a = self.alpha(h)
        if self.c[h + (w,)] > 0:  # @line L3
            return self.discounted(h, w)  # @line L4
        return a * self._prob(w, h[1:])  # @line L8

    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_katz_backoff.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/katz-backoff/. The authors are listed in prov/99DA92.jsonl.

import itertools
import random
from collections import Counter
from fractions import Fraction as F

import pytest

from katz_backoff import BOS, EOS, KatzLM, katz_discounts

TOY = [s.split() for s in ["a a b", "a b c", "a", "c a"]]


def test_toy_values() -> None:
    m = KatzLM(TOY, 2, k=2)
    assert m.total == 13
    assert m.d[2] == {1: F(1, 3), 2: F(1, 2)}
    assert m.distribution((BOS,)) == {EOS: F(1, 9), "a": F(3, 4), "b": F(1, 18), "c": F(1, 12)}
    assert m.distribution(("a",)) == {EOS: F(1, 5), "a": F(1, 15), "b": F(1, 5), "c": F(8, 15)}
    assert m.distribution(("b",)) == {EOS: F(1, 6), "a": F(10, 21), "b": F(4, 21), "c": F(1, 6)}
    assert m.distribution(("c",)) == {EOS: F(1, 6), "a": F(1, 6), "b": F(1, 3), "c": F(1, 3)}
    assert m.alpha(("a",)) == F(52, 15)
    assert m.sentence_prob(["a", "b"]) == F(1, 40)


def test_discount_values() -> None:
    # N_1 = 6, N_2 = 2, N_3 = 1, k = 2: mu = 1/2, r*(1) = 2/3, r*(2) = 3/2
    assert katz_discounts({1: 6, 2: 2, 3: 1}, 2) == {1: F(1, 3), 2: F(1, 2)}
    assert katz_discounts({2: 3}, 2) == {}  # no singletons
    assert katz_discounts({1: 2, 2: 5, 3: 4}, 2) == {}  # mu >= 1
    assert katz_discounts({1: 4, 3: 1}, 1) == {}  # d_1 = 0


def test_k_one_is_degenerate() -> None:
    # with k = 1, r*(1) = mu, so d_1 = 0 and the discounts are rejected
    rng = random.Random(1)
    for _ in range(50):
        nr = {r: rng.randrange(1, 20) for r in range(1, 6)}
        assert katz_discounts(nr, 1) == {}


def test_discounted_mass_is_n1() -> None:
    """When the discounts are valid, the counts 1 to k give up exactly N_1."""
    rng = random.Random(2)
    found = 0
    for _ in range(400):
        k = rng.randrange(2, 7)
        nr = {r: int(rng.uniform(0.5, 1.5) * 300 / r**2) for r in range(1, 10)}
        nr = {r: v for r, v in nr.items() if v > 0}
        d = katz_discounts(nr, k)
        if not d:
            continue
        found += 1
        assert sum(nr[r] * r * (1 - d[r]) for r in d) == nr[1]
        assert all(0 < x <= 1 for x in d.values())
    assert found > 20


def direct_bigram(corpus, k):
    """The bigram Katz 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)
    vocab = set(toks)
    pc = Counter(pairs)
    nr = Counter(pc.values())
    d = katz_discounts(dict(nr), k)

    def uni(w):
        return F(toks.count(w), n)

    def bi(w, v):
        cv = sum(c for (a, _), c in pc.items() if a == v)
        if cv == 0:
            return uni(w)
        seen = {b for (a, b) in pc if a == v}
        if seen == vocab:
            return F(pc[(v, w)], cv)
        if w in seen:
            return d.get(pc[(v, w)], 1) * F(pc[(v, w)], cv)
        beta = 1 - sum(d.get(pc[(v, x)], 1) * F(pc[(v, x)], cv) for x in seen)
        return beta * uni(w) / (1 - sum(uni(x) for x in seen))

    return bi, vocab


def test_against_direct_formula() -> None:
    rng = random.Random(4)
    for _ in range(60):
        words = ["a", "b", "c", "d", "e"][: rng.randrange(2, 6)]
        corpus = [[rng.choice(words) for _ in range(rng.randrange(0, 6))] for _ in range(rng.randrange(1, 7))]
        k = rng.randrange(1, 4)
        m = KatzLM(corpus, 2, k=k)
        bi, vocab = direct_bigram(corpus, k)
        assert m.vocab == 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(80):
        n = rng.randrange(1, 4)
        words = ["a", "b", "c", "d"]
        corpus = [[rng.choice(words) for _ in range(rng.randrange(0, 7))] for _ in range(rng.randrange(1, 7))]
        m = KatzLM(corpus, n, k=rng.randrange(2, 5))
        for h in itertools.product([BOS] + words, repeat=n - 1):
            d = m.distribution(h)
            assert sum(d.values()) == 1
            assert all(p >= 0 for p in d.values())


def test_errors() -> None:
    m = KatzLM(TOY, 2, k=2)
    with pytest.raises(KeyError):
        m.prob("z", ["a"])
    with pytest.raises(KeyError):
        m.prob(BOS, ["a"])
    with pytest.raises(ValueError):
        KatzLM(TOY, 0)

History

Slava Katz published the method in 1987 in a two-page correspondence in the IEEE Transactions on Acoustics, Speech, and Signal Processing, for the language model of a speech recognizer. He combined two ideas: the Good-Turing estimate of the unseen mass, and the use of a shorter context when the longer one has no data, with a normalization that keeps the model a distribution. The backoff model and its file format became standard in speech recognition toolkits. Chen and Goodman (1999) compared it with the other classical methods and found it behind Kneser-Ney smoothing.

References

  1. Slava M. Katz, Estimation of probabilities from sparse data for the language model component of a speech recognizer, IEEE Transactions on Acoustics, Speech, and Signal Processing 35(3), 1987, pages 400 to 401, the backoff recursion, the Good-Turing discounts for the counts up to k with their renormalization, and the choice k = 5
  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, Katz smoothing, its discount ratios d_r, and its performance against the other methods
  3. Christopher D. Manning and Hinrich Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999, Chapter 6, Section 6.3 (combining estimators, with Katz's backing-off)
  4. I. J. Good, The population frequencies of species and the estimation of population parameters, Biometrika 40(3-4), 1953, pages 237 to 264, the adjusted count (r+1) N_(r+1) / N_r and the unseen mass N_1 / N

Where this leads

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