Algorithm Search⌘K

Algorithmadvanced

Simple Good-Turing

Also called Gale-Sampson smoothing, SGT.

Good-Turing with smoothed counts of counts: fit log N_r against log r by a line, and use it in place of the raw N_r once the two estimates no longer differ significantly.

Time
Θ(T + m) worst
Space
Θ(T) extra
Where
T = the number of distinct seen types; m = the number of distinct counts
Properties
deterministicnot exactofflineiterative
Origin
William A. Gale, Geoffrey Sampson, 1995

Simple Good-Turing is a version of Good-Turing estimation that works on real data without hand tuning. Raw Good-Turing uses the counts of counts NrN_r (how many types were seen exactly rr times) directly, and for larger rr these numbers are noisy and often zero. William Gale and Geoffrey Sampson (1995) replaced them by a straight line fitted to log⁡Nr\log N_r against log⁡r\log r, and used the line only from the first count where it agrees with the raw estimate. The result is a smooth set of discounts for every count, which Katz backoff and other n-gram methods can use, and it does not need the fixed cut-off of raw Good-Turing.

In plain words

Good-Turing estimates how much to trust a count by looking at how many things were seen once, twice, three times, and so on. For small counts these numbers are large and reliable. For large counts they jump around: there may be four things seen ten times, none seen eleven times and three seen twelve times. Using such numbers directly gives silly answers.

The fix is to draw one smooth curve through all these numbers and read the values from the curve. On the right scale the curve is close to a straight line, so a simple line fit does it. For the smallest counts the raw numbers are better than the line, so the method keeps them until the two answers are close, and from there on it uses the line.

The problem

The input is a sample of NN tokens with the count c(x)=r≥1c(x) = r \ge 1 of each seen type xx. The output is a probability for each seen type and the total probability P0P_0 of the unseen types, with P0+∑xp(x)=1P_0 + \sum_x p(x) = 1. As in Good-Turing, P0=N1/NP_0 = N_1 / N, and a type seen rr times gets probability proportional to an adjusted count r∗r^*. The task is to compute r∗r^* for every rr that occurs, also where Nr+1=0N_{r+1} = 0.

The algorithm

Let r1<r2<⋯<rmr_1 < r_2 < \cdots < r_m be the counts that occur. Where the counts become sparse, a count rjr_j stands for a range of counts with N=0N = 0, so the method first spreads each NrjN_{r_j} over the gap around it:

Zrj=2Nrjrj+1−rj−1,r0=0,rm+1=2rm−rm−1.Z_{r_j} = \frac{2 N_{r_j}}{r_{j+1} - r_{j-1}}, \qquad r_0 = 0, \quad r_{m+1} = 2 r_m - r_{m-1}.

It then fits log⁡Zr=a+blog⁡r\log Z_r = a + b \log r by least squares and writes S(r)=earbS(r) = e^{a} r^{b} for the smoothed counts of counts. For each rr there are two estimates: the Turing estimate xr=(r+1)Nr+1/Nrx_r = (r+1) N_{r+1} / N_r and the smoothed estimate yr=(r+1)S(r+1)/S(r)y_r = (r+1) S(r+1) / S(r). The Turing estimate has the approximate variance

σr2=(r+1)2 Nr+1Nr2(1+Nr+1Nr).\sigma_r^2 = (r+1)^2 \, \frac{N_{r+1}}{N_r^2} \Bigl(1 + \frac{N_{r+1}}{N_r}\Bigr).
  1. SIMPLE-GOOD-TURING(c)
  2. 1N ← Σ_x c(x); N_r ← the number of types with c(x) = r; r_1 < ... < r_m the counts that occur
  3. 2P_0 ← N_1 / N
  4. 3for j ← 1 to m do Z_{r_j} ← 2 N_{r_j} / (r_{j+1} - r_{j-1}) ▷ r_0 = 0, r_{m+1} = 2 r_m - r_{m-1}
  5. 4fit log Z_r = a + b log r by least squares over r_1 .. r_m
  6. 5S(r) ← exp(a + b log r)
  7. 6smoothed ← false
  8. 7for j ← 1 to m do (r ← r_j)
  9. 8y ← (r + 1) S(r + 1) / S(r)
  10. 9if not smoothed and (N_{r+1} = 0 or |x_r - y| ≤ 1.96 σ_r) then smoothed ← true
  11. 10if smoothed then r* ← y else r* ← x_r
  12. 11N' ← Σ_r N_r r*
  13. 12for each seen type x do p(x) ← (1 - P_0) r*_{c(x)} / N'
  14. 13return p, P_0

Line L9 is the switch. The Turing estimate is used while it differs from the line by more than 1.96 standard deviations, which is the 95 percent level of a normal test. Once the line is used, it is used for every larger count. Lines L11 and L12 scale the seen probabilities so that they sum to 1−P01 - P_0. The smoothed estimate has the closed form yr=r(1+1/r)b+1y_r = r (1 + 1/r)^{b+1}, and the method needs a slope b<−1b < -1: then yr<ry_r < r for every rr.

Example

Take a sample of N=1442N = 1442 tokens over 568568 seen types, with these counts of counts:

rr 1 2 3 4 5 6 7 8 9 10 12 15 20 31
NrN_r 268 112 70 41 24 14 15 7 6 4 3 2 1 1
ZrZ_r 268 112 70 41 24 14 15 7 6 2.667 1.2 0.5 0.125 0.091

For r≤9r \le 9 the neighbours are r−1r - 1 and r+1r + 1, so Zr=NrZ_r = N_r. For r=10r = 10 the neighbours are 9 and 12, so Z10=8/3Z_{10} = 8/3. The last count uses rm+1=2⋅31−20=42r_{m+1} = 2 \cdot 31 - 20 = 42, so Z31=2/22Z_{31} = 2/22. The unseen mass is P0=268/1442=0.1859P_0 = 268/1442 = 0.1859. The line fit gives a=6.8139a = 6.8139 and b=−2.5767b = -2.5767.

rr xrx_r (Turing) yry_r (line) 1.96σr1.96 \sigma_r r∗r^* used pp of one type r/Nr / N
1 0.8358 0.3352 0.1843 0.8358 0.000588 0.000693
2 1.8750 1.0553 0.5599 1.8750 0.001319 0.001387
3 2.3429 1.9060 0.9031 1.9060 0.001341 0.002080
4 2.9268 2.8136 1.4744 2.8136 0.001979 0.002774
31 none 29.4864 29.4864 0.020744 0.021498

For r=1r = 1 and r=2r = 2 the difference ∣xr−yr∣|x_r - y_r| is larger than 1.96σr1.96 \sigma_r, so the Turing estimate stays. At r=3r = 3 the difference 0.43690.4369 is below 0.90310.9031, so the method switches to the line for r≥3r \ge 3. The sum N′=∑rNrr∗N' = \sum_r N_r r^* is 1157.241157.24, and each type gets (1−P0)r∗/N′(1 - P_0) r^* / N'. Note that the line puts r=3r = 3 only just above r=2r = 2: the switch can make neighbouring counts almost tie.

Correctness

A proper distribution. Every r∗r^* is positive: xrx_r is used only while Nr+1>0N_{r+1} > 0, and yry_r is a ratio of exponentials. So N′>0N' > 0, every p(x)>0p(x) > 0, and ∑xp(x)=(1−P0)∑rNrr∗/N′=1−P0\sum_x p(x) = (1 - P_0) \sum_r N_r r^* / N' = 1 - P_0.

One switch. The flag of line L9 is never reset, so there is a count ss with r∗=xrr^* = x_r for r<sr < s and r∗=yrr^* = y_r for r≥sr \ge s. Every r<sr < s has Nr+1>0N_{r+1} > 0, so xrx_r is defined wherever it is used. The switch always happens, at the latest at rmr_m, because Nrm+1=0N_{r_m + 1} = 0.

The shape of the smoothed counts. From S(r)=earbS(r) = e^a r^b, yr=(r+1)((r+1)/r)b=r(1+1/r)b+1y_r = (r+1)((r+1)/r)^{b} = r (1 + 1/r)^{b+1}. If b<−1b < -1, write c=−(b+1)>0c = -(b+1) > 0. Then yr<ry_r < r, log⁡yr=log⁡r−clog⁡(1+1/r)\log y_r = \log r - c \log(1 + 1/r) grows with rr, and r−yr→cr - y_r \to c as r→∞r \to \infty. So the smoothed counts are discounted, they keep the order of the raw counts, and for large counts they subtract nearly the same amount. In the example c=1.58c = 1.58, and 31−y31=1.5131 - y_{31} = 1.51.

Proof: Simple Good-Turing gives a proper distribution, switches once, and discounts every count when the slope is below -1full

We write c(x)≥1c(x) \ge 1 for the count of a seen type xx, N=∑xc(x)N = \sum_x c(x), NrN_r for the number of seen types with c(x)=rc(x) = r, and r1<r2<⋯<rmr_1 < r_2 < \cdots < r_m for the counts with Nr>0N_r > 0. We assume m≥2m \ge 2, which the implementation requires.

Lemma 1 (the fit is defined). The least squares line of line L4 exists and is unique.

Proof. Each Zrj>0Z_{r_j} > 0: we have Nrj≥1N_{r_j} \ge 1 and rj+1−rj−1>0r_{j+1} - r_{j-1} > 0, since r0=0<r1r_0 = 0 < r_1, the rjr_j increase, and rm+1=2rm−rm−1>rmr_{m+1} = 2 r_m - r_{m-1} > r_m because rm>rm−1r_m > r_{m-1}. So every log⁡Zrj\log Z_{r_j} is defined. The points log⁡r1<⋯<log⁡rm\log r_1 < \cdots < \log r_m are distinct and m≥2m \ge 2, so ∑j(log⁡rj−log⁡r‾)2>0\sum_j (\log r_j - \overline{\log r})^2 > 0, and the normal equations have the single solution b=∑j(log⁡rj−log⁡r‾)(log⁡Zrj−log⁡Z‾)/∑j(log⁡rj−log⁡r‾)2b = \sum_j (\log r_j - \overline{\log r})(\log Z_{r_j} - \overline{\log Z}) / \sum_j (\log r_j - \overline{\log r})^2, a=log⁡Z‾−b log⁡r‾a = \overline{\log Z} - b \, \overline{\log r}. □\square

Lemma 2 (one switch). There is an index ss with 1≤s≤m1 \le s \le m such that line L10 sets r∗=xrj=(rj+1)Nrj+1/Nrjr^* = x_{r_j} = (r_j + 1) N_{r_j + 1} / N_{r_j} for j<sj < s and r∗=yrjr^* = y_{r_j} for j≥sj \ge s. For every j<sj < s, Nrj+1>0N_{r_j + 1} > 0.

Proof. The flag smoothed starts false in line L6. Line L9 can set it to true and nothing sets it back. Let ss be the first index at which line L9 sets it, if any. For j<sj < s the flag is false at line L10, and for j≥sj \ge s it is true, which gives the two cases. For j<sj < s, the test of line L9 failed, so Nrj+1≠0N_{r_j + 1} \ne 0, and xrjx_{r_j} is defined and positive. The index ss exists: if the flag is still false at j=mj = m, then Nrm+1=0N_{r_m + 1} = 0 because rmr_m is the largest count, so line L9 sets it at j=mj = m. □\square

Theorem 3 (a proper distribution). The output satisfies 0≤P0≤10 \le P_0 \le 1, p(x)>0p(x) > 0 for every seen type when P0<1P_0 < 1, and P0+∑xp(x)=1P_0 + \sum_x p(x) = 1.

Proof. P0=N1/N∈[0,1]P_0 = N_1 / N \in [0, 1]. By Lemma 2 every r∗r^* is either a positive xrx_r or yr=(r+1)S(r+1)/S(r)y_r = (r+1) S(r+1) / S(r), a ratio of two values of the exponential function, which is positive. So N′=∑rNrr∗>0N' = \sum_r N_r r^* > 0 in line L11 and p(x)=(1−P0)rc(x)∗/N′>0p(x) = (1 - P_0) r^*_{c(x)} / N' > 0 when P0<1P_0 < 1. Grouping the types by count, ∑xp(x)=(1−P0)∑rNrr∗/N′=1−P0\sum_x p(x) = (1 - P_0) \sum_r N_r r^* / N' = 1 - P_0. □\square

Theorem 4 (the smoothed counts). For every r>0r > 0, yr=r(1+1/r)b+1y_r = r (1 + 1/r)^{b+1}. If b<−1b < -1, then with c=−(b+1)>0c = -(b+1) > 0:

  1. yr<ry_r < r;
  2. yry_r is strictly increasing in rr;
  3. r−yr→cr - y_r \to c as r→∞r \to \infty, and r−yr<cr - y_r < c for every rr.

Proof. S(r)=earbS(r) = e^{a} r^{b}, so yr=(r+1)((r+1)/r)b=r((r+1)/r)b+1=r(1+1/r)b+1y_r = (r+1) \bigl((r+1)/r\bigr)^b = r \bigl((r+1)/r\bigr)^{b+1} = r (1 + 1/r)^{b+1}.

(1) 1+1/r>11 + 1/r > 1 and b+1<0b + 1 < 0, so (1+1/r)b+1<1(1 + 1/r)^{b+1} < 1.

(2) log⁡yr=log⁡r−clog⁡(1+1/r)\log y_r = \log r - c \log(1 + 1/r). Its derivative in rr is 1/r+c/(r(r+1))>01/r + c / (r(r+1)) > 0.

(3) Let u=1/ru = 1/r. Then r−yr=(1−(1+u)−c)/ur - y_r = \bigl(1 - (1+u)^{-c}\bigr)/u. The function g(u)=1−(1+u)−cg(u) = 1 - (1+u)^{-c} is concave on u>0u > 0 with g(0)=0g(0) = 0 and g′(0)=cg'(0) = c, so g(u)<cug(u) < c u for u>0u > 0, which gives r−yr<cr - y_r < c. As u→0u \to 0, g(u)/u→g′(0)=cg(u)/u \to g'(0) = c. ■\blacksquare

So when the fitted slope is below −1-1, every count from the switch on is discounted, the order of the counts is kept, and the discount grows toward the constant −(b+1)-(b+1). Below the switch the Turing estimates are used, and the method makes no claim about their order. If b≥−1b \ge -1, statement (1) fails, which is why the method assumes b<−1b < -1.

Complexity

Counting the tokens takes Θ(N)\Theta(N) expected time with a hash table. The table of the NrN_r takes Θ(T)\Theta(T) time. Lines L3 to L11 work on the mm distinct counts, in Θ(m)\Theta(m) arithmetic operations, and m≤2Nm \le \sqrt{2N}. Line L12 takes Θ(T)\Theta(T). The extra space is Θ(T)\Theta(T) for the output and Θ(m)\Theta(m) for the tables. The method uses floating point for the logarithms and the fit, so the result is not exact; the error is at the level of rounding.

Properties

  • No cut-off to choose. Every count gets an adjusted count. The only fixed constant is the 1.96 of the switch.
  • Monotone above the switch. With b<−1b < -1 the smoothed counts grow with rr. Below the switch the raw Turing estimates are used, and they need not be monotone.
  • The unseen mass is still N1/NN_1 / N. The smoothing changes only how the remaining mass is split among the seen types.
  • A constant discount in the limit. For large rr the discount r−r∗r - r^* tends to −(b+1)-(b+1), which is the idea behind absolute discounting.
  • A power law fit. The line in log-log scale is a power law Nr∝rbN_r \propto r^b, which matches the Zipf shape of word counts. For data far from a power law the fit can be poor.

Variants and improvements

  • Good's own smoothing. Good (1953) already said that the NrN_r need smoothing and discussed ways to do it. Simple Good-Turing picks one simple smoother and adds a rule for when to use it.
  • Other confidence levels. The 1.96 can be changed. A larger value keeps the Turing estimates for more counts.
  • Katz backoff uses discounts only for r≤kr \le k and renormalizes them so that the discounted mass equals N1N_1. Simple Good-Turing discounts every count and renormalizes at the end.
  • Per-history use. In an n-gram model the method can be applied to all the n-grams of one order, and the discounts then shared by all histories, as Katz does.

When to use it

Use it when you want Good-Turing estimates for every count of a large sample, such as word or n-gram frequencies, species counts or k-mer counts, and the data have a heavy tail. It needs at least two distinct counts, and it works best with many types seen once or twice. For small samples, or when the fitted slope is not below −1-1, use plain Laplace smoothing or a held-out method such as deleted interpolation.

Pitfalls

  • The slope must be below −1-1. If b≥−1b \ge -1 the smoothed counts are not below the raw counts, and the estimates are not discounts. Check bb and fall back to another method.
  • Fit ZrZ_r, not NrN_r. Fitting the raw NrN_r ignores the zero counts in the gaps and gives a slope that is too flat.
  • The switch is one way. Do not go back to the Turing estimate after the first agreement, even if a later count disagrees again.
  • Near ties at the switch. At the switch the adjusted count can drop to the line, so a type seen rr times can get almost the same probability as a type seen r−1r - 1 times.
  • Renormalize. The r∗r^* do not sum to N−N1N - N_1 on their own; without line L12 the result is not a distribution.

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.

simple_good_turing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simple-good-turing/. The authors are listed in prov/P5RKY6.jsonl.

"""Simple Good-Turing estimation (Gale and Sampson 1995), in floating point.

The input is the table of counts of counts {r: N_r} of a sample, with r >= 1
and N_r >= 1. The method averages each N_r over the gap to its neighbours
(Z_r = 2 N_r / (t - q)), fits the line log Z_r = a + b log r by least
squares, and uses the smoothed counts r* = (r + 1) S(r + 1) / S(r) with
S(r) = exp(a + b log r) once the raw Turing estimate is no longer
significantly different (1.96 standard deviations). The seen probabilities
are scaled to sum to 1 - N_1 / N.
"""

import math
from typing import Hashable, Mapping

CONFIDENCE = 1.96


def averaged_counts(nr: Mapping[int, int]) -> dict[int, float]:
    """Return {r: Z_r} with Z_r = 2 N_r / (t - q) for the neighbours q < r < t."""
    rs = sorted(nr)
    z = {}
    for j, r in enumerate(rs):
        q = rs[j - 1] if j > 0 else 0
        t = rs[j + 1] if j + 1 < len(rs) else 2 * r - q
        z[r] = 2.0 * nr[r] / (t - q)
    return z


def fit_line(xs: list[float], ys: list[float]) -> tuple[float, float]:
    """Least squares fit of y = a + b x; return (a, b)."""
    m = len(xs)
    mx, my = sum(xs) / m, sum(ys) / m
    sxx = sum((x - mx) ** 2 for x in xs)
    sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
    b = sxy / sxx
    return my - b * mx, b


def simple_good_turing_counts(nr: Mapping[int, int], confidence: float = CONFIDENCE):
    """Return (rstar, a, b, switch).

    rstar maps each r to its adjusted count, (a, b) is the fitted line of
    log Z_r against log r, and switch is the smallest r that uses the
    smoothed estimate. Raises ValueError with fewer than two distinct counts.
    """
    rs = sorted(nr)
    if len(rs) < 2:
        raise ValueError("the fit needs at least two distinct counts")
    if rs[0] < 1 or any(nr[r] < 1 for r in rs):
        raise ValueError("counts and counts of counts must be at least 1")
    z = averaged_counts(nr)  # @line L3
    a, b = fit_line([math.log(r) for r in rs], [math.log(z[r]) for r in rs])  # @line L4

    def smooth(r: float) -> float:
        return math.exp(a + b * math.log(r))  # @line L5

    rstar, use_line, switch = {}, False, None  # @line L6
    for r in rs:  # @line L7
        y = (r + 1) * smooth(r + 1) / smooth(r)  # @line L8
        if not use_line:  # @line L9
            n1 = nr.get(r + 1, 0)
            if n1 == 0:
                use_line = True
            else:
                x = (r + 1) * n1 / nr[r]
                sd = math.sqrt((r + 1) ** 2 * n1 / nr[r] ** 2 * (1 + n1 / nr[r]))
                if abs(x - y) <= confidence * sd:
                    use_line = True
        if use_line:
            if switch is None:
                switch = r
            rstar[r] = y  # @line L10
        else:
            rstar[r] = x  # @line L10
    return rstar, a, b, switch


def simple_good_turing(counts: Mapping[Hashable, int], confidence: float = CONFIDENCE):
    """Return (p, p0, rstar, b) for a mapping from each seen type to its count.

    p maps each seen type to its probability, p0 = N_1 / N is the total mass
    of the unseen types, and b is the fitted slope (the method assumes b < -1).
    """
    n = sum(counts.values())  # @line L1
    nr: dict[int, int] = {}
    for r in counts.values():
        nr[r] = nr.get(r, 0) + 1
    p0 = nr.get(1, 0) / n  # @line L2
    rstar, _, b, _ = simple_good_turing_counts(nr, confidence)
    total = sum(nr[r] * rstar[r] for r in nr)  # @line L11
    p = {x: (1 - p0) * rstar[r] / total for x, r in counts.items()}  # @line L12
    return p, p0, rstar, b  # @line L13
test_simple_good_turing.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simple-good-turing/. The authors are listed in prov/P5RKY6.jsonl.

import math
import random

import pytest

from simple_good_turing import averaged_counts, fit_line, simple_good_turing, simple_good_turing_counts

TABLE = {1: 268, 2: 112, 3: 70, 4: 41, 5: 24, 6: 14, 7: 15, 8: 7, 9: 6, 10: 4, 12: 3, 15: 2, 20: 1, 31: 1}


def counts_from_table(nr: dict[int, int]) -> dict[str, int]:
    out, i = {}, 0
    for r, n in nr.items():
        for _ in range(n):
            out[f"t{i}"] = r
            i += 1
    return out


def test_averaged_counts() -> None:
    z = averaged_counts({1: 10, 2: 4, 4: 2, 7: 1})
    # q = 0, t = 2; q = 1, t = 4; q = 2, t = 7; q = 4, t = 2 * 7 - 4 = 10
    assert z == {1: 10.0, 2: 8 / 3, 4: 4 / 5, 7: 2 / 6}


def test_fit_line_exact() -> None:
    a, b = fit_line([0.0, 1.0, 2.0, 3.0], [5.0, 3.0, 1.0, -1.0])
    assert math.isclose(a, 5.0) and math.isclose(b, -2.0)


def test_worked_example() -> None:
    rstar, a, b, switch = simple_good_turing_counts(TABLE)
    assert switch == 3
    assert math.isclose(a, 6.813929, abs_tol=1e-6)
    assert math.isclose(b, -2.576710, abs_tol=1e-6)
    assert math.isclose(rstar[1], 2 * 112 / 268)  # the Turing estimate
    assert math.isclose(rstar[2], 3 * 70 / 112)
    assert math.isclose(rstar[3], 3 * (4 / 3) ** (b + 1))  # the smoothed estimate
    assert math.isclose(rstar[3], 1.906027, abs_tol=1e-6)
    p, p0, _, _ = simple_good_turing(counts_from_table(TABLE))
    assert math.isclose(p0, 268 / 1442)
    assert math.isclose(p0 + sum(p.values()), 1.0, abs_tol=1e-12)


def test_smoothed_count_closed_form() -> None:
    """With S(r) = exp(a) r^b, the smoothed count is r (1 + 1/r)^(b + 1)."""
    rstar, _, b, switch = simple_good_turing_counts(TABLE)
    for r in TABLE:
        if r >= switch:
            assert math.isclose(rstar[r], r * (1 + 1 / r) ** (b + 1), rel_tol=1e-12)


def test_once_smoothed_always_smoothed() -> None:
    rng = random.Random(5)
    for _ in range(200):
        nr = {}
        for r in range(1, 25):
            v = int(rng.uniform(0.3, 1.7) * 400 / r ** 2)
            if v > 0:
                nr[r] = v
        if len(nr) < 2:
            continue
        rstar, _, b, switch = simple_good_turing_counts(nr)
        rs = sorted(nr)
        assert switch is not None
        for r in rs:
            n1 = nr.get(r + 1, 0)
            if r < switch:
                assert rstar[r] == (r + 1) * n1 / nr[r]
            else:
                assert math.isclose(rstar[r], r * (1 + 1 / r) ** (b + 1), rel_tol=1e-12)
        # the switch is at the first r without N_(r+1) or with a small difference
        for r in rs:
            if r == switch:
                break
            assert nr.get(r + 1, 0) > 0


def test_zipf_samples_are_proper() -> None:
    rng = random.Random(3)
    weights = [1 / (i + 1) for i in range(300)]
    for _ in range(20):
        tokens = rng.choices(range(300), weights=weights, k=2000)
        counts: dict[int, int] = {}
        for t in tokens:
            counts[t] = counts.get(t, 0) + 1
        p, p0, rstar, b = simple_good_turing(counts)
        assert b < -1
        assert math.isclose(p0 + sum(p.values()), 1.0, abs_tol=1e-12)
        assert all(0 < v < 1 for v in p.values())
        n = len(tokens)
        assert math.isclose(p0, sum(1 for r in counts.values() if r == 1) / n)
        # for large counts the smoothed estimate is close to the raw count
        top = max(counts.values())
        assert abs(rstar[top] / top - 1) < 0.05


def test_errors() -> None:
    with pytest.raises(ValueError):
        simple_good_turing_counts({1: 5})
    with pytest.raises(ValueError):
        simple_good_turing({"a": 1, "b": 1})

History

Good (1953) gave the Turing estimate and pointed out that the counts of counts must be smoothed, but left the choice of smoother to the user. Church and Gale (1991) compared Good-Turing estimates of English bigram probabilities with held-out counts. Gale and Sampson (1995) wrote the simple method down in full, with the averaging transform, the log-log line and the switching rule, so that a researcher without a background in statistics could use Good-Turing estimation on any frequency table.

References

  1. William A. Gale and Geoffrey Sampson, Good-Turing frequency estimation without tears, Journal of Quantitative Linguistics 2(3), 1995, pages 217 to 237, the averaging transform Z_r, the line fit of log Z_r against log r, the rule that switches from the Turing to the smoothed estimate at 1.96 standard deviations, and the final renormalization
  2. 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 and the need to smooth the counts of counts
  3. Christopher D. Manning and Hinrich Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999, Chapter 6, Section 6.2 (Good-Turing estimation and the smoothing of the counts of counts)

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