Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 NrN_r types were seen exactly rr times in NN tokens, the unseen types together get N1/NN_1 / N, and a type seen rr times gets the adjusted count r∗=(r+1)Nr+1/Nrr^* = (r+1) N_{r+1} / N_r in place of rr. 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 NN tokens is drawn from an unknown distribution over a set of types that may be very large. Type xx was seen c(x)=rc(x) = r times. Write NrN_r for the number of types seen exactly rr times, so that N=∑rrNrN = \sum_r r N_r, and T=∑r≥1NrT = \sum_{r \ge 1} N_r 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 P0P_0, so that P0+∑xp(x)=1P_0 + \sum_x p(x) = 1.

The maximum likelihood estimate p(x)=r/Np(x) = r / N gives P0=0P_0 = 0. 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

r∗=(r+1)Nr+1Nr,p(x)=r∗N,P0=N1N.r^* = (r+1) \frac{N_{r+1}}{N_r}, \qquad p(x) = \frac{r^*}{N}, \qquad P_0 = \frac{N_1}{N}.

The formula alone fails where Nr+1=0N_{r+1} = 0: then r∗=0r^* = 0, and in every sample the most frequent type gets probability zero. The usual fix, used here, keeps r∗=rr^* = r where the formula has no data or where rr is above a cut-off kk, and then scales the seen probabilities so that they sum to 1−P01 - P_0.

  1. GOOD-TURING(c, k) ▷ c(x) ≥ 1 for each seen type x; k = ∞ for no cut-off
  2. 1N ← Σ_x c(x); N_r ← the number of types x with c(x) = r
  3. 2P_0 ← N_1 / N ▷ the total probability of all unseen types
  4. 3for each r with N_r > 0 do
  5. 4if r ≤ k and N_{r+1} > 0 then r* ← (r + 1) N_{r+1} / N_r
  6. 5else r* ← r
  7. 6S ← Σ_r N_r r*
  8. 7for each seen type x do p(x) ← (1 - P_0) r*_{c(x)} / S
  9. 8return 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 UU of unseen types is known, for example U=∣V∣−TU = |V| - T for a fixed vocabulary VV, each unseen type gets P0/UP_0 / U. If it is not known, P0P_0 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 N=8N = 8. The type a was seen 3 times, b twice, and c, d and e once each. So N1=3N_1 = 3, N2=1N_2 = 1, N3=1N_3 = 1, and N4=0N_4 = 0.

rr NrN_r r∗r^* by the formula r∗r^* used pp of one type
0 P0=3/8P_0 = 3/8 for all unseen types
1 3 2⋅1/3=2/32 \cdot 1 / 3 = 2/3 2/32/3 5/965/96
2 1 3⋅1/1=33 \cdot 1 / 1 = 3 33 15/6415/64
3 1 4⋅0/1=04 \cdot 0 / 1 = 0 33 15/6415/64

The unseen types get 3/83/8. Then S=3⋅23+3+3=8S = 3 \cdot \tfrac23 + 3 + 3 = 8, and each type gets (5/8)r∗/8(5/8) r^* / 8. The total is 3/8+3⋅5/96+2⋅15/64=13/8 + 3 \cdot 5/96 + 2 \cdot 15/64 = 1. The formula alone gives a the probability 0, b the probability 3/83/8, and each singleton 1/121/12. Both versions show the main weakness of the raw estimate: with so few types the NrN_r are noisy, and b gets as much as a or more. Simple Good-Turing smooths the NrN_r before it uses them.

Correctness

There are two parts.

The output is a distribution. Every r∗r^* is positive, S=∑rNrr∗>0S = \sum_r N_r r^* > 0, and ∑xp(x)=(1−P0)∑rNrr∗/S=1−P0\sum_x p(x) = (1 - P_0) \sum_r N_r r^* / S = 1 - P_0. So P0+∑xp(x)=1P_0 + \sum_x p(x) = 1 exactly.

Why the formula is right. Draw NN tokens independently from a distribution qq. Let MrM_r be the total probability of the types seen exactly rr times. Then

E[Mr]=r+1N+1 E[Nr+1(N+1)],\mathbb{E}[M_r] = \frac{r+1}{N+1} \, \mathbb{E}[N_{r+1}^{(N+1)}],

where Nr+1(N+1)N_{r+1}^{(N+1)} is the number of types seen r+1r+1 times in a sample of N+1N + 1 tokens. For r=0r = 0, the unseen mass has expectation E[N1(N+1)]/(N+1)\mathbb{E}[N_1^{(N+1)}] / (N+1), which N1/NN_1 / N estimates. For r≥1r \ge 1, the NrN_r types seen rr times share E[Mr]\mathbb{E}[M_r], and each gets about (r+1)Nr+1/(NNr)=r∗/N(r+1) N_{r+1} / (N N_r) = r^* / N. The identity follows from (Nr)=r+1N+1(N+1r+1)\binom{N}{r} = \frac{r+1}{N+1} \binom{N+1}{r+1} and holds for every qq, 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 c(x)≥1c(x) \ge 1 for the count of a seen type xx, N=∑xc(x)≥1N = \sum_x c(x) \ge 1, and NrN_r for the number of seen types xx with c(x)=rc(x) = r.

Theorem 1 (a proper distribution). The output of GOOD-TURING satisfies p(x)≥0p(x) \ge 0 for every seen type, 0≤P0≤10 \le P_0 \le 1, and P0+∑xp(x)=1P_0 + \sum_x p(x) = 1. If P0<1P_0 < 1, then p(x)>0p(x) > 0 for every seen type.

Proof. Line L2 gives 0≤P0=N1/N≤10 \le P_0 = N_1 / N \le 1, since N1≤NN_1 \le N. For each rr with Nr>0N_r > 0, line L4 sets r∗=(r+1)Nr+1/Nrr^* = (r+1) N_{r+1} / N_r only when Nr+1>0N_{r+1} > 0, so r∗>0r^* > 0, and line L5 sets r∗=r≥1r^* = r \ge 1. So every r∗r^* is positive. There is at least one seen type, so S=∑rNrr∗>0S = \sum_r N_r r^* > 0 in line L6, and line L7 is defined. Then p(x)=(1−P0)rc(x)∗/S≥0p(x) = (1 - P_0) r^*_{c(x)} / S \ge 0, with p(x)>0p(x) > 0 when P0<1P_0 < 1. Group the seen types by their count:

∑xp(x)=1−P0S∑rNrr∗=1−P0.□\sum_x p(x) = \frac{1 - P_0}{S} \sum_r N_r r^* = 1 - P_0. \qquad \square

Lemma 2 (the mass of the formula alone). Let r~=(r+1)Nr+1/Nr\tilde r = (r+1) N_{r+1} / N_r for every rr with Nr>0N_r > 0, and p~(x)=r~c(x)/N\tilde p(x) = \tilde r_{c(x)} / N. Then

∑xp~(x)=1N∑s≥2,  Ns−1>0sNs.\sum_x \tilde p(x) = \frac{1}{N} \sum_{s \ge 2,\; N_{s-1} > 0} s N_s .

So N1/N+∑xp~(x)=1N_1 / N + \sum_x \tilde p(x) = 1 if and only if Ns−1>0N_{s-1} > 0 for every s≥2s \ge 2 with Ns>0N_s > 0.

Proof. ∑xp~(x)=1N∑r: Nr>0Nrr~=1N∑r: Nr>0(r+1)Nr+1\sum_x \tilde p(x) = \frac1N \sum_{r:\, N_r > 0} N_r \tilde r = \frac1N \sum_{r:\, N_r > 0} (r+1) N_{r+1}. Put s=r+1s = r + 1. The sum runs over the s≥2s \ge 2 with Ns−1>0N_{s-1} > 0, and the terms with Ns=0N_s = 0 are zero. Since N=N1+∑s≥2sNsN = N_1 + \sum_{s \ge 2} s N_s, the total with N1/NN_1 / N is 1 exactly when no term sNs>0s N_s > 0 is left out. □\square

This is why line L5 keeps r∗=rr^* = r and line L7 scales: the formula alone loses the mass of every count ss with Ns−1=0N_{s-1} = 0, and it always gives r~=0\tilde r = 0 to the largest count.

Theorem 3 (Good's identity). Let X1,…,XNX_1, \ldots, X_N be independent draws from a distribution qq on a countable set of types. Let Nr(M)N_r^{(M)} be the number of types seen exactly rr times in the first MM draws, and let

Mr=∑xqx [ x is seen exactly r times in X1,…,XN ]M_r = \sum_x q_x \,[\, x \text{ is seen exactly } r \text{ times in } X_1, \ldots, X_N \,]

be the total probability of the types seen rr times. Then for every r≥0r \ge 0,

E[Mr]=r+1N+1 E[Nr+1(N+1)].\mathbb{E}[M_r] = \frac{r+1}{N+1}\, \mathbb{E}\bigl[N_{r+1}^{(N+1)}\bigr].

Proof. The count of type xx in NN draws has the binomial distribution with parameters NN and qxq_x. By linearity of expectation, and since all terms are nonnegative so that the sums may be reordered,

E[Mr]=∑xqx(Nr)qxr(1−qx)N−r=(Nr)∑xqxr+1(1−qx)N−r.\mathbb{E}[M_r] = \sum_x q_x \binom{N}{r} q_x^{r} (1 - q_x)^{N-r} = \binom{N}{r} \sum_x q_x^{r+1} (1 - q_x)^{N-r}.

In the same way, the count of xx in N+1N + 1 draws is binomial with parameters N+1N + 1 and qxq_x, so

E[Nr+1(N+1)]=(N+1r+1)∑xqxr+1(1−qx)N−r.\mathbb{E}\bigl[N_{r+1}^{(N+1)}\bigr] = \binom{N+1}{r+1} \sum_x q_x^{r+1} (1 - q_x)^{N-r}.

The two sums are the same. The identity follows from

(Nr)=N!r! (N−r)!=r+1N+1⋅(N+1)!(r+1)! (N−r)!=r+1N+1(N+1r+1).■\binom{N}{r} = \frac{N!}{r!\,(N-r)!} = \frac{r+1}{N+1} \cdot \frac{(N+1)!}{(r+1)!\,(N-r)!} = \frac{r+1}{N+1} \binom{N+1}{r+1}. \qquad \blacksquare

What the identity gives. For r=0r = 0, the unseen mass has E[M0]=E[N1(N+1)]/(N+1)\mathbb{E}[M_0] = \mathbb{E}[N_1^{(N+1)}] / (N + 1). The observed N1/NN_1 / N estimates it, and its bias is small. From the binomial sums above,

E[N1(N)]N−E[M0]=∑xqx(1−qx)N−1−∑xqx(1−qx)N=∑xqx2(1−qx)N−1=E[M1]N,\frac{\mathbb{E}[N_1^{(N)}]}{N} - \mathbb{E}[M_0] = \sum_x q_x (1 - q_x)^{N-1} - \sum_x q_x (1 - q_x)^{N} = \sum_x q_x^2 (1 - q_x)^{N-1} = \frac{\mathbb{E}[M_1]}{N},

which lies in [0,1/N][0, 1/N] because 0≤M1≤10 \le M_1 \le 1. For r≥1r \ge 1, replace E[Nr+1(N+1)]/(N+1)\mathbb{E}[N_{r+1}^{(N+1)}] / (N+1) by the observed Nr+1/NN_{r+1} / N and share MrM_r equally among the NrN_r types seen rr times. Each gets (r+1)Nr+1/(NNr)=r∗/N(r+1) N_{r+1} / (N N_r) = r^* / N, which is the estimate of line L4 before the scaling of line L7. The identity holds for every qq, 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 Θ(N)\Theta(N) expected time with a hash table, the table of the NrN_r takes Θ(T)\Theta(T) time, lines L3 to L6 take time linear in the number of distinct counts, and line L7 takes Θ(T)\Theta(T). The number of distinct counts is at most 2N\sqrt{2N}, since distinct counts r1<r2<⋯<rmr_1 < r_2 < \cdots < r_m need N≥1+2+⋯+mN \ge 1 + 2 + \cdots + m. The extra space is Θ(T)\Theta(T) for the output. In exact rational arithmetic each step works on numbers of O(log⁡N)O(\log N) 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 N1/NN_1 / N. It is large when many types are seen once, and zero when no type is seen once.
  • Not monotone. The raw r∗r^* need not grow with rr. In the example, b (seen twice) gets as much as a (seen three times).
  • Lost mass. The formula alone sums to 1−P01 - P_0 over the seen types only when there is no gap: the seen mass is ∑s≥2, Ns−1>0sNs/N\sum_{s \ge 2,\, N_{s-1} > 0} s N_s / N, so every count ss with Ns−1=0N_{s-1} = 0 drops out. The scaling of line L7 corrects this.
  • Small counts only. For large rr the counts of counts are 0 or 1 and the formula is noise. The ratio r∗/rr^*/r is close to 1 there anyway, which is why a cut-off kk, such as Katz's k=5k = 5, loses little.

Variants and improvements

  • Simple Good-Turing (Gale and Sampson 1995) averages the NrN_r over the gaps, fits a line to log⁡Nr\log N_r against log⁡r\log r, and switches from the raw to the smoothed r∗r^* when the two no longer differ significantly.
  • Katz backoff uses Good-Turing discounts for the counts 1 to kk 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 r−r∗r - r^*, which is close to a constant for r≥2r \ge 2 in text, by a fixed discount DD.
  • The Chao1 estimator uses N1N_1 and N2N_2 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 P0P_0 among the words. For small counts use it with smoothed NrN_r (simple Good-Turing), or use it only for r≤kr \le k.

Pitfalls

  • Gaps in the counts of counts. If Nr+1=0N_{r+1} = 0 the formula gives r∗=0r^* = 0. Keep r∗=rr^* = r there, or smooth the NrN_r, and then renormalize.
  • P0P_0 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 N1=0N_1 = 0 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, P0=1P_0 = 1 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.

good_turing_estimation.pyI0RawGitHub
# 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 NrN_r must be smoothed before they are used for larger rr. 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

  1. 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
  2. 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
  3. Church and Gale 1991, Good-Turing estimates of bigram probabilities compared with held-out counts
  4. 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)
  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, 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.

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