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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 (how many types were seen exactly times) directly, and for larger these numbers are noisy and often zero. William Gale and Geoffrey Sampson (1995) replaced them by a straight line fitted to against , 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 tokens with the count of each seen type . The output is a probability for each seen type and the total probability of the unseen types, with . As in Good-Turing, , and a type seen times gets probability proportional to an adjusted count . The task is to compute for every that occurs, also where .
The algorithm
Let be the counts that occur. Where the counts become sparse, a count stands for a range of counts with , so the method first spreads each over the gap around it:
It then fits by least squares and writes for the smoothed counts of counts. For each there are two estimates: the Turing estimate and the smoothed estimate . The Turing estimate has the approximate variance
SIMPLE-GOOD-TURING(c)- 1
N ← Σ_x c(x); N_r ← the number of types with c(x) = r; r_1 < ... < r_m the counts that occur - 2
P_0 ← N_1 / N - 3
for 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} - 4
fit log Z_r = a + b log r by least squares over r_1 .. r_m - 5
S(r) ← exp(a + b log r) - 6
smoothed ← false - 7
for j ← 1 to m do (r ← r_j) - 8
y ← (r + 1) S(r + 1) / S(r) - 9
if not smoothed and (N_{r+1} = 0 or |x_r - y| ≤ 1.96 σ_r) then smoothed ← true - 10
if smoothed then r* ← y else r* ← x_r - 11
N' ← Σ_r N_r r* - 12
for each seen type x do p(x) ← (1 - P_0) r*_{c(x)} / N' - 13
return 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 . The smoothed estimate has the closed form , and the method needs a slope : then for every .
Example
Take a sample of tokens over seen types, with these counts of counts:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 12 | 15 | 20 | 31 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 268 | 112 | 70 | 41 | 24 | 14 | 15 | 7 | 6 | 4 | 3 | 2 | 1 | 1 | |
| 268 | 112 | 70 | 41 | 24 | 14 | 15 | 7 | 6 | 2.667 | 1.2 | 0.5 | 0.125 | 0.091 |
For the neighbours are and , so . For the neighbours are 9 and 12, so . The last count uses , so . The unseen mass is . The line fit gives and .
| (Turing) | (line) | used | of one type | |||
|---|---|---|---|---|---|---|
| 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 and the difference is larger than , so the Turing estimate stays. At the difference is below , so the method switches to the line for . The sum is , and each type gets . Note that the line puts only just above : the switch can make neighbouring counts almost tie.
Correctness
A proper distribution. Every is positive: is used only while , and is a ratio of exponentials. So , every , and .
One switch. The flag of line L9 is never reset, so there is a count with for and for . Every has , so is defined wherever it is used. The switch always happens, at the latest at , because .
The shape of the smoothed counts. From , . If , write . Then , grows with , and as . 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 , and .
Proof: Simple Good-Turing gives a proper distribution, switches once, and discounts every count when the slope is below -1full
We write for the count of a seen type , , for the number of seen types with , and for the counts with . We assume , which the implementation requires.
Lemma 1 (the fit is defined). The least squares line of line L4 exists and is unique.
Proof. Each : we have and , since , the increase, and because . So every is defined. The points are distinct and , so , and the normal equations have the single solution , .
Lemma 2 (one switch). There is an index with such that line L10 sets for and for . For every , .
Proof. The flag smoothed starts false in line L6. Line L9 can set it to true and nothing sets it back. Let be the first index at which line L9 sets it, if any. For the flag is false at line L10, and for it is true, which gives the two cases. For , the test of line L9 failed, so , and is defined and positive. The index exists: if the flag is still false at , then because is the largest count, so line L9 sets it at .
Theorem 3 (a proper distribution). The output satisfies , for every seen type when , and .
Proof. . By Lemma 2 every is either a positive or , a ratio of two values of the exponential function, which is positive. So in line L11 and when . Grouping the types by count, .
Theorem 4 (the smoothed counts). For every , . If , then with :
- ;
- is strictly increasing in ;
- as , and for every .
Proof. , so .
(1) and , so .
(2) . Its derivative in is .
(3) Let . Then . The function is concave on with and , so for , which gives . As , .
So when the fitted slope is below , every count from the switch on is discounted, the order of the counts is kept, and the discount grows toward the constant . Below the switch the Turing estimates are used, and the method makes no claim about their order. If , statement (1) fails, which is why the method assumes .
Complexity
Counting the tokens takes expected time with a hash table. The table of the takes time. Lines L3 to L11 work on the distinct counts, in arithmetic operations, and . Line L12 takes . The extra space is for the output and 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 the smoothed counts grow with . Below the switch the raw Turing estimates are used, and they need not be monotone.
- The unseen mass is still . The smoothing changes only how the remaining mass is split among the seen types.
- A constant discount in the limit. For large the discount tends to , which is the idea behind absolute discounting.
- A power law fit. The line in log-log scale is a power law , 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 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 and renormalizes them so that the discounted mass equals . 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 , use plain Laplace smoothing or a held-out method such as deleted interpolation.
Pitfalls
- The slope must be below . If the smoothed counts are not below the raw counts, and the estimates are not discounts. Check and fall back to another method.
- Fit , not . Fitting the raw 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 times can get almost the same probability as a type seen times.
- Renormalize. The do not sum to 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.
# 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
- 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
- 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
- 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.
| 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 P5RKY6 Edit this page History Report an error Markdown