Algorithmadvanced
Guaranteed-error estimator
Also called GEE distinct value estimator.
Estimate the number of distinct values in a column from r random rows of n. Its bias is at most a factor 1 + sqrt(n/r), the order of the lower bound for every estimator that reads r rows.
- Time
- O(r) expected
- Space
- O(r) extra
- Where
- n = the number of rows in the column; r = the number of rows in the sample
- Model
- Real RAM
- Properties
- randomizednot exactrandomizediterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Moses Charikar, Surajit Chaudhuri, Rajeev Motwani, Vivek Narasayya, 2000
The guaranteed-error estimator (GEE) estimates the number of distinct values in a column of rows from a uniform random sample of rows. If values occur exactly times in the sample, it returns . Charikar, Chaudhuri, Motwani and Narasayya gave it in 2000 together with a lower bound: every estimator that reads only of the rows has, on some column, a ratio error of order with constant probability. GEE never overestimates by more than the factor , and its expected value is at least , so it reaches that order. This page is about one statistic that cardinality estimation needs, the number of distinct values, which the selectivity formulas of the optimizer divide by. It is also about one setting, a sample. Sketches such as HyperLogLog and the KMV sketch solve the distinct elements problem with small relative error, but they read every row.
In plain words
To count the different values in a large column, read a random part and count there. The values that show up two or more times in the part are probably common in the whole column, so each one counts once. A value that shows up only once is a sign of rare values: for each rare value the sample caught, there are probably many that it missed. GEE counts each value seen once as several values, and the number of copies grows with the ratio of the column size to the sample size.
No method can do much better from a sample. A column where one value fills almost every row looks the same in a small sample as a column that also holds many rare values. Any guess is then far off for one of the two columns. GEE stays within a constant factor of this limit.
The problem
The input is a column of rows and a sample size with . The column has distinct values, and the goal is an estimate of . The algorithm may read only the values of rows. The measure is the ratio error , which is 1 for an exact answer and treats an estimate that is 10 times too high like one that is 10 times too low. It is the q-error of the optimizer literature for this one number.
The algorithm
GEE(column of n rows, sample size r)- 1
S ← r rows of the column, drawn uniformly at random without replacement - 2
count the number of times each value occurs in S - 3
for each j ≥ 1, f_j ← the number of values that occur exactly j times in S - 4
return sqrt(n/r) · f_1 + (the sum of f_j over j ≥ 2)
The vector is the frequency profile of the sample. With , the number of distinct values in the sample, the result is : the sample count, plus extra values for each value seen once. The code takes the profile from any sampler, so it also works on a sample that the system already keeps, for example a reservoir sample of a table.
Example
A column of rows holds the value a in 8 rows, b in 4 rows, and c, d, e and f in one row each, so . Take , so . The sample a, a, b, e has (b and e) and (a). GEE returns , a ratio error of .
The 1820 possible samples of 4 rows give these estimates:
| estimate | 1 | 2 | 3 | 5 | 8 |
|---|---|---|---|---|---|
| samples | 71 | 168 | 496 | 844 | 241 |
The estimate 1 comes from the 70 samples that hold only a and the one sample that holds only b. The mean is , which is above the bound of the correctness section. The largest estimate, 8, is below . The mean ratio error over all samples is about 1.79, and the worst is 6, on the samples that see only one value.
Correctness
The proof file proves two facts. First, for every sample, , because . Second, . The key step is a property of sampling without replacement: for a value with rows, the probability that the sample misses it is at most times the probability that the sample holds it exactly once. So the expected number of missed values is at most , and the extra weight that GEE puts on covers it within the factor .
The proof file also proves the lower bound. For , let . A column of one value and a column with extra singletons give the same sample with probability at least , so an estimator that sees only that sample is off by at least on one of them. With and , this is a ratio error of at least 5.86. The proof here gives probability for randomized estimators; Charikar et al. state probability .
A guarantee on the expected estimate is not a guarantee on each run. On a column of one common value and singletons, the sample misses all singletons with probability near , and then GEE returns 1 for a true value of .
Proof: GEE stays within a factor sqrt(n/r) above and 1 + sqrt(n/r) below the number of distinct values, and no sampling estimator can do better than order sqrt(n/r)full
Setting. A column has rows and distinct values. A value occurs in rows, so . The sample is a set of rows, , drawn uniformly at random without replacement (line L1). For , is the number of values that occur exactly times in (lines L2 and L3), and is the number of distinct values in . Write . Line L4 returns
The ratio error of an estimate is .
Lemma 1 (deterministic range). For every sample, .
Proof. because . Also , so . Each value of the sample is a value of the column, so .
So never overestimates by more than the factor , on any sample. If , then , the sample is the whole column, and .
Lemma 2 (a missed value is rarer than a value seen once). Let be a value with rows. Then .
Proof. There are equally likely samples. The sample misses in of them, and contains exactly one row of in of them. If , the left side is 0 and there is nothing to prove. Otherwise , and
because and .
Lemma 3 (expected underestimate). .
Proof. The number of values that the sample misses is . By linearity of expectation and Lemma 2, summed over all values,
So . Also , because . Then
where the middle step uses .
Theorem (correctness of GEE). For every column and every sample size , on every sample, and . So .
Proof. Lemma 1 gives for every sample, so . Lemma 3 gives .
A single estimate can be worse. The theorem bounds the expected estimate, not the ratio error of each run. Take (an integer) and a column with one value in rows and other values in one row each, so . The sample misses all singletons with probability , which tends to when is fixed and grows (it is above for and ). On those samples , and , so the ratio error is . The test file checks this case.
Theorem (lower bound for every estimator). Let and , and let . Let be any estimator that reads the values of at most rows, chosen in any adaptive way and with any random choices, and then outputs . Then there is a column of rows on which has ratio error at least with probability at least . If is deterministic, the probability is 1.
Proof. Let . Because , , so . Column A has the same value 0 in all rows, so . A column of type B has the value 0 in rows and distinct other values in the other rows, so . Let ; then .
Run on column A with its random choices . It reads only zeros, so the rows it reads are a set of at most positions fixed by , and it outputs . Its ratio error on A is if . Let on A.
Now put the singletons of B at a set of positions chosen uniformly at random, independently of . If misses , then with choices reads the same zeros on B as on A, so it reads the same rows and outputs the same . For each fixed , misses the at most positions of with probability at least
Let . Then , and because . On , : the function is 0 at , concave, and positive at . So .
If and misses , the ratio error on B is at least . So, over and , the probability of ratio error at least on B is at least . This is an average over the choice of , so some fixed placement gives a column B with at least this probability. On A the probability is . If , column A is the bad input. Otherwise , and column B with is the bad input.
If is deterministic, is fixed and is 0 or 1. If , column A has ratio error at least always. If , put the singletons at positions outside , which exist because ; then outputs on B always.
Comparison with the paper. Charikar et al. state the lower bound with probability at least for each . The proof above uses the same pair of inputs and gives for randomized estimators, which is enough for the order of the bound: with a constant, every estimator has ratio error of order with constant probability on some input. GEE matches this order in the sense of the first theorem: its expected estimate is within a factor of .
Work. Line L1 draws rows. Lines L2 and L3 count the values with a hash table, in expected time and space. Line L4 sums over the at most entries of the profile.
Complexity
The work is in the sample. Lines L2 and L3 use a hash table on the values of the sample, so they take expected time and space, and line L4 adds up at most numbers. Drawing the sample takes time when rows can be read by position. On disk it can cost up to page reads, and a block sample (all rows of some pages) is cheaper but is not a uniform row sample. GEE never reads the other rows; that is the point of the method.
Properties
- Never far too high. The estimate is at most times the true count on every sample. This is a theorem.
- Bounded bias downward. Its expected value is at least . This is a theorem.
- Optimal order. Every estimator that reads of rows has ratio error of order on some column with constant probability, so no estimator gains more than a constant factor on the worst column. This is the lower bound of Charikar et al.
- Exact on the whole column. With , it returns the true count.
- Uses only the profile. It needs and the sample count , nothing else.
Variants and improvements
- AE. The same paper gives the adaptive estimator AE, which fits the number of rare values to the low part of the profile (, , and so on). It is often more accurate on real data, without the worst-case guarantee of GEE.
- Classic sampling estimators. Haas, Naughton, Seshadri and Stokes (1995) compared the Shlosser estimator, jackknife estimators and a hybrid that picks one by a test of skew. These estimators can be better on many columns and much worse on some.
- Species estimators. Statistics has the same problem as the number of species in a population. The Chao1 estimator uses and in a similar way.
- Sketches over all the data. If the system can read every row once, for example while it builds a histogram, a HyperLogLog or KMV sketch gives a small relative error in small space, and the lower bound of this page does not apply.
When to use it
Use it when the number of distinct values of a column is needed and only a sample can be read: statistics collection on a large table, or a quick estimate during optimization. Use it when a safe worst-case error matters more than the best average accuracy. If a full scan is possible, a sketch is far more accurate. If the column is known to have few values, the sample count is often already exact.
Pitfalls
- Expecting a small error from a small sample. With a 1 percent sample, every estimator can be off by a factor of about 6 on some columns. The lower bound is about the problem, not about GEE.
- Reading the guarantee as a bound per run. The theorem bounds the expected estimate. One estimate can be much worse, as the example with singletons shows.
- A sample that is not uniform. Block samples, or the first rows of a table, break the analysis. Rows that are sorted or clustered on the column make too small.
- Sampling with or without replacement. The proof here uses a sample without replacement. With replacement, the same row can be drawn twice and looks like a repeated value, which lowers ; use the row identifier to remove repeats first.
- Integer arithmetic. is not an integer in general; compute the estimate in floating point and round only at the end.
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/guaranteed-error-estimator/. The authors are listed in prov/32XY8A.jsonl.
"""The guaranteed-error estimator (GEE) of Charikar, Chaudhuri, Motwani and Narasayya (PODS 2000).
The input is a column of n rows. GEE reads a uniform random sample of r
rows and estimates the number D of distinct values in the column. Let f_j
be the number of values that occur exactly j times in the sample. Then
GEE = sqrt(n / r) * f_1 + sum over j >= 2 of f_j.
A value seen two or more times is counted once. A value seen once stands
for itself and for sqrt(n / r) - 1 values that the sample missed. The
estimate always lies between d, the number of distinct values in the
sample, and sqrt(n / r) * d.
"""
import math
from collections import Counter
from random import Random
from typing import Dict, Hashable, List, Sequence
def frequency_profile(sample: Sequence[Hashable]) -> Dict[int, int]:
"""Return {j: f_j}, where f_j is the number of values seen exactly j times."""
counts = Counter(sample) # @line L2
profile: Dict[int, int] = {}
for j in counts.values(): # @line L3
profile[j] = profile.get(j, 0) + 1
return profile
def gee_from_profile(profile: Dict[int, int], n: int, r: int) -> float:
"""GEE for a sample of r rows from n rows with frequency profile `profile`."""
if not 1 <= r <= n:
raise ValueError("the sample size r must satisfy 1 <= r <= n")
if sum(j * f for j, f in profile.items()) != r:
raise ValueError("the profile does not describe r rows")
scale = math.sqrt(n / r)
f1 = profile.get(1, 0)
rest = sum(f for j, f in profile.items() if j >= 2)
return scale * f1 + rest # @line L4
def gee(sample: Sequence[Hashable], n: int) -> float:
"""GEE for a sample (a list of values) drawn from a column of n rows."""
return gee_from_profile(frequency_profile(sample), n, len(sample))
def draw_sample(column: Sequence[Hashable], r: int, rng: Random) -> List[Hashable]:
"""A uniform random sample of r rows, without replacement."""
return rng.sample(list(column), r) # @line L1
def estimate_distinct(column: Sequence[Hashable], r: int, rng: Random) -> float:
"""Draw r rows of the column at random and return the GEE estimate."""
return gee(draw_sample(column, r, rng), len(column))
def ratio_error(estimate: float, true: float) -> float:
"""max(estimate / true, true / estimate), for positive values."""
if estimate <= 0 or true <= 0:
raise ValueError("the ratio error needs positive values")
return max(estimate / true, true / estimate)
def lower_bound(n: int, r: int, gamma: float) -> float:
"""The ratio error sqrt((n - r) / (2 r) * ln(1 / gamma)) of the lower bound.
Charikar et al. show that every estimator that examines at most r of n
rows has at least this ratio error on some input, with probability at
least gamma, for each gamma > e^(-r).
"""
if not (math.exp(-r) < gamma < 1):
raise ValueError("gamma must satisfy e^(-r) < gamma < 1")
return math.sqrt((n - r) / (2 * r) * math.log(1 / gamma))
test_guaranteed_error_estimator.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/guaranteed-error-estimator/. The authors are listed in prov/32XY8A.jsonl.
import itertools
import math
import unittest
from fractions import Fraction
from random import Random
from guaranteed_error_estimator import (
draw_sample,
estimate_distinct,
frequency_profile,
gee,
gee_from_profile,
lower_bound,
ratio_error,
)
def exact_estimates(column, r):
"""GEE on every r-subset of the rows of the column."""
n = len(column)
return [gee([column[i] for i in s], n) for s in itertools.combinations(range(n), r)]
class TestGEE(unittest.TestCase):
def test_page_example(self):
sample = ["a", "a", "b", "e"]
self.assertEqual(frequency_profile(sample), {1: 2, 2: 1})
self.assertEqual(gee(sample, 16), 5.0)
def test_page_example_all_samples(self):
column = ["a"] * 8 + ["b"] * 4 + ["c", "d", "e", "f"]
values = exact_estimates(column, 4)
self.assertEqual(len(values), 1820)
counts = {}
for v in values:
counts[v] = counts.get(v, 0) + 1
self.assertEqual(counts, {1.0: 71, 2.0: 168, 3.0: 496, 5.0: 844, 8.0: 241})
mean = sum(values) / len(values)
self.assertAlmostEqual(mean, 8043 / 1820)
self.assertGreaterEqual(mean, 6 / (1 + 2))
def test_bounds_on_every_sample(self):
rng = Random(7)
for _ in range(40):
n = rng.randint(2, 9)
column = [rng.randrange(rng.randint(1, n)) for _ in range(n)]
D = len(set(column))
for r in range(1, n + 1):
c = math.sqrt(n / r)
values = []
for s in itertools.combinations(range(n), r):
sample = [column[i] for i in s]
d = len(set(sample))
g = gee(sample, n)
self.assertLessEqual(d - 1e-9, g)
self.assertLessEqual(g, c * d + 1e-9)
self.assertLessEqual(g, c * D + 1e-9)
values.append(g)
mean = sum(values) / len(values)
self.assertGreaterEqual(mean, D / (1 + c) - 1e-9)
def test_full_sample_is_exact(self):
rng = Random(3)
for _ in range(20):
column = [rng.randrange(30) for _ in range(rng.randint(1, 60))]
self.assertEqual(gee(column, len(column)), len(set(column)))
def test_expected_estimate_monte_carlo(self):
rng = Random(11)
n, r = 3000, 100
c = math.sqrt(n / r)
columns = [
[rng.randrange(300) for _ in range(n)],
[int(1 / (1 - rng.random())) for _ in range(n)],
list(range(n)),
[0] * (n - 150) + list(range(1, 151)),
]
for column in columns:
D = len(set(column))
runs = [estimate_distinct(column, r, rng) for _ in range(150)]
mean = sum(runs) / len(runs)
self.assertLessEqual(max(runs), c * D + 1e-9)
# E[GEE] >= D / (1 + c); the sample mean is checked with a margin of 20 percent.
self.assertGreaterEqual(mean, 0.8 * D / (1 + c))
self.assertLessEqual(ratio_error(mean, D), 1 + c)
def test_single_estimate_can_be_far_off(self):
# n / r singletons in a column of one common value: with probability
# about 1/e the sample misses every singleton and GEE returns 1.
n, r = 400, 20
k = n // r
column = [0] * (n - k) + list(range(1, k + 1))
miss = Fraction(math.comb(n - k, r), math.comb(n, r))
self.assertGreater(miss, Fraction(1, 3))
self.assertEqual(gee([0] * r, n), 1.0)
self.assertEqual(ratio_error(1.0, k + 1), k + 1)
self.assertGreater(k + 1, 4 * math.sqrt(n / r))
rng = Random(5)
hits = sum(1 for _ in range(600) if estimate_distinct(column, r, rng) == 1.0)
self.assertLess(abs(hits / 600 - float(miss)), 0.07)
def test_lower_bound_pair(self):
# Input A has one value. Input B has k singletons as well. On samples
# that see only the common value, every estimator must give one answer,
# and that answer has ratio error at least sqrt(k + 1) on A or on B.
for n, r, gamma in [(1000, 10, 0.5), (5000, 50, 0.3), (200, 20, 0.9)]:
K = (n - r) / (2 * r) * math.log(1 / gamma)
k = int(K)
miss = Fraction(math.comb(n - k, r), math.comb(n, r))
self.assertGreaterEqual(float(miss), gamma)
self.assertGreater(math.sqrt(k + 1), lower_bound(n, r, gamma))
g = gee([0] * r, n)
worst = max(ratio_error(g, 1), ratio_error(g, k + 1))
self.assertGreaterEqual(worst, math.sqrt(k + 1))
def test_lower_bound_value(self):
# One percent of the rows, gamma = 1/2: the ratio error is at least about 5.86.
self.assertAlmostEqual(lower_bound(10000, 100, 0.5), 5.8575, places=3)
with self.assertRaises(ValueError):
lower_bound(100, 2, 0.1)
def test_profile_checks(self):
with self.assertRaises(ValueError):
gee_from_profile({1: 3}, 10, 4)
with self.assertRaises(ValueError):
gee_from_profile({1: 3}, 2, 3)
self.assertEqual(len(draw_sample(list(range(10)), 4, Random(1))), 4)
if __name__ == "__main__":
unittest.main()
History
The database literature had several sampling estimators for distinct values by 1995, among them those of Haas, Naughton, Seshadri and Stokes, and no method was good on all columns. In 2000 Moses Charikar, Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya proved that this is not a lack of skill: any estimator that reads a small sample has a large ratio error on some column. They designed GEE so that its error matches the order of this lower bound, and gave AE as a practical companion. Later surveys of distinct-value estimation, such as the one by Gibbons, restate the lower bound as the reason that streaming sketches, which see all rows, are needed for accurate counts.
References
- Towards estimation error guarantees for distinct values, the lower bound on the ratio error of every estimator that examines r of n rows, the estimator GEE and its expected ratio error of order sqrt(n/r), and the adaptive estimator AE
- Distinct-values estimation over data streams, Section 2.1 (sampling-based estimation) and Section 5, Theorem 7 (the lower bound of Charikar et al. restated, with sqrt((n - r)/(2r) ln(1/gamma)) and probability gamma)
- Sampling-based estimation of the number of distinct values of an attribute, the earlier sampling estimators of the number of distinct values (Shlosser, the jackknife estimators and a hybrid of them)
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 32XY8A Edit this page History Report an error Markdown