Algorithmcore
Good-Turing estimation
Also called Good-Turing smoothing, Good-Turing discounting.
Estimate the total chance of the unseen types as N_1/N and replace each count r by r* = (r+1) N_(r+1) / N_r, where N_r is the number of types seen r times.
- Time
- Θ(N) worst
- Space
- Θ(T) extra
- Where
- N = the number of tokens in the sample; T = the number of distinct seen types
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alan M. Turing, I. J. Good, 1953
Good-Turing estimation answers a question that comes up whenever we count things in a sample: how much probability should go to the types that we have not seen at all, and how much less should each seen type get than its share in the sample? The answer uses only the counts of counts. If types were seen exactly times in tokens, the unseen types together get , and a type seen times gets the adjusted count in place of . Unlike Laplace smoothing, it adds nothing by hand: the share of the unseen comes from the data, and in language models it is the discount behind Katz backoff. The same idea estimates the number of unseen species in ecology, as in the Chao1 estimator.
In plain words
You count the fish of each kind in a net. Some kinds you saw only once. How likely is it that the next fish is of a kind you have never seen? Good-Turing says: about as likely as it was that the last fish caught was of a kind seen only once, because a kind that is new now would have been seen once after one more catch. So the share of the new kinds is the number of kinds seen once divided by the number of fish.
The same thought moves every count down a little. A kind seen once is treated like the kinds seen twice, scaled to how many there are of each. The share given to the new kinds comes out of the shares of the seen ones, so the total stays one.
The problem
A sample of tokens is drawn from an unknown distribution over a set of types that may be very large. Type was seen times. Write for the number of types seen exactly times, so that , and for the number of seen types. The task is to give each seen type a probability and to give the unseen types, as a group, a total probability , so that .
The maximum likelihood estimate gives . In text this is far too low: by Zipf's law a large part of the types in any sample are seen once, and many more were missed.
The algorithm
The Turing estimate of the adjusted count is
The formula alone fails where : then , and in every sample the most frequent type gets probability zero. The usual fix, used here, keeps where the formula has no data or where is above a cut-off , and then scales the seen probabilities so that they sum to .
GOOD-TURING(c, k) ▷ c(x) ≥ 1 for each seen type x; k = ∞ for no cut-off- 1
N ← Σ_x c(x); N_r ← the number of types x with c(x) = r - 2
P_0 ← N_1 / N ▷ the total probability of all unseen types - 3
for each r with N_r > 0 do - 4
if r ≤ k and N_{r+1} > 0 then r* ← (r + 1) N_{r+1} / N_r - 5
else r* ← r - 6
S ← Σ_r N_r r* - 7
for each seen type x do p(x) ← (1 - P_0) r*_{c(x)} / S - 8
return p, P_0
Line L2 is the share of the unseen. Lines L3 to L5 give the adjusted counts. Lines L6 and L7 scale the seen probabilities to the mass that is left. If the number of unseen types is known, for example for a fixed vocabulary , each unseen type gets . If it is not known, stays a single number, as in the escape probability of a text compressor.
Example
Take the sample "a a a b b c d e", with . The type a was seen 3 times, b twice, and c, d and e once each. So , , , and .
| by the formula | used | of one type | ||
|---|---|---|---|---|
| 0 | for all unseen types | |||
| 1 | 3 | |||
| 2 | 1 | |||
| 3 | 1 |
The unseen types get . Then , and each type gets . The total is . The formula alone gives a the probability 0, b the probability , and each singleton . Both versions show the main weakness of the raw estimate: with so few types the are noisy, and b gets as much as a or more. Simple Good-Turing smooths the before it uses them.
Correctness
There are two parts.
The output is a distribution. Every is positive, , and . So exactly.
Why the formula is right. Draw tokens independently from a distribution . Let be the total probability of the types seen exactly times. Then
where is the number of types seen times in a sample of tokens. For , the unseen mass has expectation , which estimates. For , the types seen times share , and each gets about . The identity follows from and holds for every , with no assumption on the shape of the distribution.
Proof: Good-Turing estimation gives a proper distribution, and the Turing formula is unbiased for the mass of each count classfull
We write for the count of a seen type , , and for the number of seen types with .
Theorem 1 (a proper distribution). The output of GOOD-TURING satisfies for every seen type, , and . If , then for every seen type.
Proof. Line L2 gives , since . For each with , line L4 sets only when , so , and line L5 sets . So every is positive. There is at least one seen type, so in line L6, and line L7 is defined. Then , with when . Group the seen types by their count:
Lemma 2 (the mass of the formula alone). Let for every with , and . Then
So if and only if for every with .
Proof. . Put . The sum runs over the with , and the terms with are zero. Since , the total with is 1 exactly when no term is left out.
This is why line L5 keeps and line L7 scales: the formula alone loses the mass of every count with , and it always gives to the largest count.
Theorem 3 (Good's identity). Let be independent draws from a distribution on a countable set of types. Let be the number of types seen exactly times in the first draws, and let
be the total probability of the types seen times. Then for every ,
Proof. The count of type in draws has the binomial distribution with parameters and . By linearity of expectation, and since all terms are nonnegative so that the sums may be reordered,
In the same way, the count of in draws is binomial with parameters and , so
The two sums are the same. The identity follows from
What the identity gives. For , the unseen mass has . The observed estimates it, and its bias is small. From the binomial sums above,
which lies in because . For , replace by the observed and share equally among the types seen times. Each gets , which is the estimate of line L4 before the scaling of line L7. The identity holds for every , so the estimator makes no assumption on the shape of the distribution, only on the independence of the draws.
Complexity
After the tokens are counted, which takes expected time with a hash table, the table of the takes time, lines L3 to L6 take time linear in the number of distinct counts, and line L7 takes . The number of distinct counts is at most , since distinct counts need . The extra space is for the output. In exact rational arithmetic each step works on numbers of bits before the final scaling.
Properties
- Distribution free. The expectation identity holds for any distribution of the types. The estimator assumes only that the tokens are independent draws.
- The unseen mass is . It is large when many types are seen once, and zero when no type is seen once.
- Not monotone. The raw need not grow with . In the example, b (seen twice) gets as much as a (seen three times).
- Lost mass. The formula alone sums to over the seen types only when there is no gap: the seen mass is , so every count with drops out. The scaling of line L7 corrects this.
- Small counts only. For large the counts of counts are 0 or 1 and the formula is noise. The ratio is close to 1 there anyway, which is why a cut-off , such as Katz's , loses little.
Variants and improvements
- Simple Good-Turing (Gale and Sampson 1995) averages the over the gaps, fits a line to against , and switches from the raw to the smoothed when the two no longer differ significantly.
- Katz backoff uses Good-Turing discounts for the counts 1 to in each order of an n-gram model and gives the unseen mass to the lower order.
- The enhanced Good-Turing method of Church and Gale (1991) splits the bigrams into classes by the counts of their words before it applies the formula.
- Absolute discounting and Kneser-Ney smoothing replace , which is close to a constant for in text, by a fixed discount .
- The Chao1 estimator uses and to estimate how many species were not seen, not how much probability they have.
When to use it
Use it to estimate the share of new types in a sample from a large or open set: new words in text, new species in a survey, new k-mers in a sequencing run, or new values in a database column. On its own it gives the total for the unseen types and not their split, so a language model still needs a second distribution, such as a lower-order model, to share among the words. For small counts use it with smoothed (simple Good-Turing), or use it only for .
Pitfalls
- Gaps in the counts of counts. If the formula gives . Keep there, or smooth the , and then renormalize.
- is a total. It is the mass of all unseen types together. Dividing it by the number of unseen types needs a closed vocabulary.
- No singletons. If the unseen types get nothing. This happens on data where rare items were removed before counting, for example a vocabulary with a frequency cut-off.
- All singletons. If every type is seen once, and the seen types get nothing. The estimate is right in spirit (the sample says almost nothing about the next token) but it is not useful.
- Dependent tokens. The identity assumes independent draws. Words repeat in bursts inside a document, so on text from only a few documents the estimate of the unseen mass can be far off.
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/good-turing-estimation/. The authors are listed in prov/7B0QFN.jsonl.
"""Good-Turing estimation, exact in Fraction.
The input is a mapping from each seen type to its count r >= 1 in a sample
of N tokens. N_r is the number of types seen exactly r times. The adjusted
count of a type seen r times is r* = (r + 1) N_(r+1) / N_r, and the unseen
types get the total mass P_0 = N_1 / N.
Where the formula has no estimate (N_(r+1) = 0, or r > k for a cut-off k),
the code keeps r* = r. It then scales the seen probabilities so that they
sum to 1 - P_0, which makes the result a proper distribution.
"""
from collections import Counter
from fractions import Fraction
from typing import Hashable, Iterable, Mapping
def type_counts(tokens: Iterable[Hashable]) -> dict[Hashable, int]:
"""Count the tokens of a sample."""
return dict(Counter(tokens))
def counts_of_counts(counts: Mapping[Hashable, int]) -> dict[int, int]:
"""Return {r: N_r} for the counts r >= 1 that occur."""
out: Counter = Counter()
for r in counts.values():
if r < 1:
raise ValueError("every count must be at least 1")
out[r] += 1
return dict(out)
def turing_counts(nr: Mapping[int, int], k: int | None = None) -> dict[int, Fraction]:
"""Return {r: r*}: r* = (r + 1) N_(r+1) / N_r where N_(r+1) > 0 and r <= k, else r* = r."""
rstar = {}
for r in sorted(nr): # @line L3
if (k is None or r <= k) and nr.get(r + 1, 0) > 0:
rstar[r] = Fraction((r + 1) * nr[r + 1], nr[r]) # @line L4
else:
rstar[r] = Fraction(r) # @line L5
return rstar
def good_turing(counts: Mapping[Hashable, int], k: int | None = None):
"""Return (p, p0, rstar).
p maps each seen type to its probability (a Fraction), p0 = N_1 / N is
the total probability of all unseen types, and rstar maps r to r*.
The values of p sum to 1 - p0, so p0 + sum(p) = 1 exactly.
Cost: O(T) arithmetic operations for T seen types, after the counting.
"""
if not counts:
raise ValueError("empty sample")
n = sum(counts.values()) # @line L1
nr = counts_of_counts(counts)
p0 = Fraction(nr.get(1, 0), n) # @line L2
rstar = turing_counts(nr, k)
s = sum(nr[r] * rstar[r] for r in nr) # @line L6
p = {x: (1 - p0) * rstar[r] / s for x, r in counts.items()} # @line L7
return p, p0, rstar # @line L8
def raw_good_turing(counts: Mapping[Hashable, int]) -> tuple[dict[Hashable, Fraction], Fraction]:
"""Return (p, p0) with p(x) = r* / N from the formula alone, so r* = 0 where N_(r+1) = 0.
The most frequent type gets 0. With p0 the values sum to 1 exactly when
every count s >= 2 that occurs has N_(s-1) > 0; otherwise mass is lost.
"""
n = sum(counts.values())
nr = counts_of_counts(counts)
p = {x: Fraction((r + 1) * nr.get(r + 1, 0), nr[r] * n) for x, r in counts.items()}
return p, Fraction(nr.get(1, 0), n)
def unseen_type_probability(p0: Fraction, num_unseen: int) -> Fraction:
"""Share the unseen mass equally among num_unseen >= 1 unseen types."""
if num_unseen < 1:
raise ValueError("there is no unseen type to receive the mass N_1 / N")
return p0 / num_unseen
test_good_turing_estimation.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/good-turing-estimation/. The authors are listed in prov/7B0QFN.jsonl.
import itertools
import random
from fractions import Fraction as F
import pytest
from good_turing_estimation import (
counts_of_counts,
good_turing,
raw_good_turing,
turing_counts,
type_counts,
unseen_type_probability,
)
SAMPLE = "a a a b b c d e".split()
def test_check_values() -> None:
c = type_counts(SAMPLE)
assert counts_of_counts(c) == {1: 3, 2: 1, 3: 1}
p, p0, rstar = good_turing(c)
assert p0 == F(3, 8)
assert rstar[1] == F(2, 3)
assert rstar[2] == 3
assert rstar[3] == 3 # N_4 = 0, so the raw count is kept
# S = 3 * 2/3 + 1 * 3 + 1 * 3 = 8, and the seen mass is 5/8
assert p["a"] == p["b"] == F(5, 8) * F(3, 8)
assert p["c"] == F(5, 8) * F(2, 3) / 8
assert p0 + sum(p.values()) == 1
def test_raw_formula() -> None:
p, p0 = raw_good_turing(type_counts(SAMPLE))
assert p == {"a": 0, "b": F(3, 8), "c": F(1, 12), "d": F(1, 12), "e": F(1, 12)}
assert p0 + sum(p.values()) == 1
def test_cut_off() -> None:
c = type_counts(SAMPLE)
p, p0, rstar = good_turing(c, k=1)
assert rstar == {1: F(2, 3), 2: 2, 3: 3}
assert p0 + sum(p.values()) == 1
p, p0, rstar = good_turing(c, k=0)
assert rstar == {1: 1, 2: 2, 3: 3}
assert p["a"] == F(5, 8) * F(3, 8)
def test_all_singletons() -> None:
p, p0, _ = good_turing({"x": 1, "y": 1})
assert p0 == 1
assert all(v == 0 for v in p.values())
def test_errors() -> None:
with pytest.raises(ValueError):
good_turing({})
with pytest.raises(ValueError):
good_turing({"x": 0})
with pytest.raises(ValueError):
unseen_type_probability(F(1, 2), 0)
assert unseen_type_probability(F(3, 8), 3) == F(1, 8)
def test_random_samples_are_proper() -> None:
rng = random.Random(7)
for _ in range(300):
n = rng.randrange(1, 60)
types = rng.randrange(1, 15)
tokens = [rng.randrange(types) for _ in range(n)]
c = type_counts(tokens)
k = rng.choice([None, 1, 2, 5])
p, p0, rstar = good_turing(c, k)
assert p0 + sum(p.values()) == 1
assert all(0 <= v <= 1 for v in p.values())
nr = counts_of_counts(c)
assert rstar == turing_counts(nr, k)
# the raw formula moves the tokens of each count s >= 2 down to the types seen s - 1 times
raw, raw0 = raw_good_turing(c)
kept = sum(s * nr[s] for s in nr if s >= 2 and s - 1 in nr)
assert sum(raw.values()) == F(kept, n)
assert (raw0 + sum(raw.values()) == 1) == all(s - 1 in nr for s in nr if s >= 2)
def test_expected_mass_identity() -> None:
"""E[mass of the types seen r times in N draws] = (r + 1) E[N_(r+1) in N + 1 draws] / (N + 1)."""
dist = [F(1, 2), F(1, 3), F(1, 6)]
for n in range(1, 6):
for r in range(0, n + 1):
lhs = F(0)
for seq in itertools.product(range(3), repeat=n):
w = F(1)
for s in seq:
w *= dist[s]
lhs += w * sum(dist[i] for i in range(3) if seq.count(i) == r)
rhs = F(0)
for seq in itertools.product(range(3), repeat=n + 1):
w = F(1)
for s in seq:
w *= dist[s]
rhs += w * sum(1 for i in range(3) if seq.count(i) == r + 1)
assert lhs == F(r + 1, n + 1) * rhs
def test_unseen_mass_on_zipf_data() -> None:
"""On average over many samples, N_1 / N is close to the true mass of the unseen types."""
rng = random.Random(11)
weights = [1 / (i + 1) for i in range(40)]
z = sum(weights)
probs = [w / z for w in weights]
est, true = 0.0, 0.0
trials, n = 400, 60
for _ in range(trials):
tokens = rng.choices(range(40), weights=probs, k=n)
c = type_counts(tokens)
_, p0, _ = good_turing(c)
est += float(p0)
true += sum(probs[i] for i in range(40) if i not in c)
assert abs(est / trials - true / trials) < 0.02
History
I. J. Good published the method in 1953 and wrote that the key idea was due to Alan Turing. The two had worked together on codebreaking during the Second World War. Good's paper also warned that the must be smoothed before they are used for larger . The estimator came to language modeling through speech recognition: Katz (1987) built his backoff model on it, Church and Gale (1991) tested it on English bigrams, and Gale and Sampson (1995) gave the simple smoothing method that most later software uses.
References
- I. J. Good, The population frequencies of species and the estimation of population parameters, Biometrika 40(3-4), 1953, pages 237 to 264, the estimate (r+1) N_(r+1) / N_r of the frequency of a species seen r times, the estimate N_1/N of the unseen mass, and the need to smooth the N_r
- William A. Gale and Geoffrey Sampson, Good-Turing frequency estimation without tears, Journal of Quantitative Linguistics 2(3), 1995, pages 217 to 237, a plain account of the Turing estimator and of the noise in the counts of counts
- Church and Gale 1991, Good-Turing estimates of bigram probabilities compared with held-out counts
- Christopher D. Manning and Hinrich Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999, Chapter 6, Section 6.2 (statistical estimators, with Good-Turing estimation)
- 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, Good-Turing estimation as the base of Katz smoothing
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 7B0QFN Edit this page History Report an error Markdown