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
- Model
- Word RAM
- Properties
- deterministicexactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 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 start markers <s> on the left and one </s> on the right. The vocabulary is the set of predicted tokens, which holds </s> and, after rare words are mapped to it, <unk>. For a history of up to tokens, is the number of times is followed by and . Write for without its first token and for the empty history, with . The task is a distribution over for every history, with positive values for the seen n-grams.
The algorithm
For each order , let be the number of m-grams seen exactly times. Katz keeps the counts above a cut-off (he used ) and discounts the counts by the ratio
These ratios are the Good-Turing ratios , changed so that the counts above are not discounted and the total mass taken away is still , the Good-Turing mass of the unseen m-grams. For , . The unigrams use the maximum likelihood estimate .
P-KATZ(w, h) ▷ c and the d_r counted once on the training text- 1
if h = ε then return c(w) / N - 2
if c(h) = 0 then return P-KATZ(w, h') - 3
if c(h w) > 0 then - 4
return d_{c(h w)} c(h w) / c(h) - 5
β(h) ← 1 - Σ_{v : c(h v) > 0} d_{c(h v)} c(h v) / c(h) ▷ the mass taken from the seen words - 6
γ(h) ← 1 - Σ_{v : c(h v) > 0} P-KATZ(v, h') ▷ the lower-order mass of the unseen words - 7
α(h) ← β(h) / γ(h) - 8
return α(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 and is stored once per history. Line L8 gives an unseen word its lower-order probability, scaled so that the unseen words of share exactly .
Example
Train a bigram model on the four sentences "a a b", "a b c", "a" and "c a", with . There are 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 , , , and
The discounts take away counts in all. After the history a, seen 5 times, the seen words get a , b and </s> . So . The only unseen word is c, with unigram probability , so , and .
| history | ||||||
|---|---|---|---|---|---|---|
<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 , so it is not discounted: . Each row sums to 1. The sentence "a b" gets . Note that is not a probability; it can be larger than 1.
Correctness
Every row is a distribution. If some word is unseen after and , the seen words get by line L5, and the unseen words get , by induction on the length of (the lower row sums to 1). So the row sums to 1. If every word of was seen after , there is nothing to back off to, and the implementation keeps the undiscounted estimates for that history.
The discounted mass is . When the ratios are valid, . 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 to .
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 , the set of predicted training tokens. For a history , is the number of times is followed by , , , and is without its first token. For an order and , is the discount ratio of the m-grams seen times, with for or when the order is left undiscounted. If , the history keeps its undiscounted estimates: we then write for all its words and , as the implementation does.
Lemma 1 (the discounted mass). Let be the number of m-grams seen times, with and . For each with let and , and assume that all these lie in , which is the test that the implementation makes before it uses them. Then for every , and
Proof. First, the counts of counts have no gap up to . Suppose for some . If , then and , which is not in . So . Since , induction on gives for .
Next, , so
Summed over , the numerators telescope to , and dividing by gives .
Theorem 2 (a proper distribution). For every history , for and . If , then .
Proof. By induction on the length of .
Length 0. Line L1 gives , and because is the set of predicted tokens. If the value is positive.
Length , . Line L2 returns the row of , which has the properties by the induction hypothesis. No has .
Length , , . Every word gets , and these sum to 1.
Length , , . For , line L4 gives , since . Line L5 gives , since . Line L6 gives , by the induction hypothesis for . If , line L7 gives and
If , the lower order gives all its mass to the words of , and the implementation treats as in the case , with the undiscounted estimates, whose sum over is 1, and with 0 for the other words.
Remark. The weight can exceed 1, since can be smaller than . It is a scale factor, not a probability. Lemma 1 shows that, per order, the counts taken away sum to the Good-Turing estimate of the total count of the unseen m-grams; Theorem 2 shows that the backoff weights then pass exactly the mass 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 in expected time and space. The counts of counts and the take time linear in the number of n-gram types. The weight sums over the words seen after , so all weights together take time linear in the number of n-gram types times . After that, one query takes expected time. Models are usually stored in the ARPA format, which holds for each seen n-gram and 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 are kept, since the Good-Turing ratio is close to 1 there and the are noisy.
- Same unseen mass as Good-Turing. The discounts take away exactly counts per order.
- Not monotone. The ratios come from the noisy , 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 while the seen a a gets , because c is frequent after other histories.
Variants and improvements
- Smoothed counts of counts. Compute the with simple Good-Turing instead of the raw formula.
- Absolute discounting with backoff replaces by a fixed discount, .
- 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 .
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 , , and every in . On small or filtered data this fails. The implementation then leaves that order undiscounted.
- deletes the singletons. With , , so and every n-gram seen once gets probability 0 from its own count. Use .
- No unseen words. If every word of follows , then and is undefined. Keep the undiscounted estimates for such a history.
- Discounts per order. The and the are computed separately for each order .
<s>and</s>.<s>is never predicted and is not counted in ;</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.
# 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
- 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
- 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
- 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)
- 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.
| 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 99DA92 Edit this page History Report an error Markdown