Algorithm Search⌘K

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
Properties
randomizednot exactrandomizediterative
Origin
Moses Charikar, Surajit Chaudhuri, Rajeev Motwani, Vivek Narasayya, 2000

The guaranteed-error estimator (GEE) estimates the number DD of distinct values in a column of nn rows from a uniform random sample of rr rows. If fjf_j values occur exactly jj times in the sample, it returns n/r f1+∑j≥2fj\sqrt{n/r}\, f_1 + \sum_{j \ge 2} f_j. Charikar, Chaudhuri, Motwani and Narasayya gave it in 2000 together with a lower bound: every estimator that reads only rr of the nn rows has, on some column, a ratio error of order n/r\sqrt{n/r} with constant probability. GEE never overestimates by more than the factor n/r\sqrt{n/r}, and its expected value is at least D/(1+n/r)D/(1 + \sqrt{n/r}), 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 nn rows and a sample size rr with 1≤r≤n1 \le r \le n. The column has DD distinct values, and the goal is an estimate D^\hat D of DD. The algorithm may read only the values of rr rows. The measure is the ratio error max⁡(D^/D, D/D^)\max(\hat D/D,\ D/\hat D), 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

  1. GEE(column of n rows, sample size r)
  2. 1S ← r rows of the column, drawn uniformly at random without replacement
  3. 2count the number of times each value occurs in S
  4. 3for each j ≥ 1, f_j ← the number of values that occur exactly j times in S
  5. 4return sqrt(n/r) · f_1 + (the sum of f_j over j ≥ 2)

The vector (f1,f2,…)(f_1, f_2, \ldots) is the frequency profile of the sample. With d=∑jfjd = \sum_j f_j, the number of distinct values in the sample, the result is d+(n/r−1)f1d + (\sqrt{n/r} - 1) f_1: the sample count, plus n/r−1\sqrt{n/r} - 1 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 n=16n = 16 rows holds the value a in 8 rows, b in 4 rows, and c, d, e and f in one row each, so D=6D = 6. Take r=4r = 4, so n/r=2\sqrt{n/r} = 2. The sample a, a, b, e has f1=2f_1 = 2 (b and e) and f2=1f_2 = 1 (a). GEE returns 2⋅2+1=52 \cdot 2 + 1 = 5, a ratio error of 6/5=1.26/5 = 1.2.

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 8043/1820≈4.428043/1820 \approx 4.42, which is above the bound D/(1+2)=2D/(1 + 2) = 2 of the correctness section. The largest estimate, 8, is below 2D=122D = 12. 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, d≤D^≤n/r d≤n/r Dd \le \hat D \le \sqrt{n/r}\, d \le \sqrt{n/r}\, D, because f1≤d≤Df_1 \le d \le D. Second, E[D^]≥D/(1+n/r)E[\hat D] \ge D/(1 + \sqrt{n/r}). The key step is a property of sampling without replacement: for a value with mm rows, the probability that the sample misses it is at most n/rn/r times the probability that the sample holds it exactly once. So the expected number of missed values is at most (n/r) E[f1](n/r)\,E[f_1], and the extra weight that GEE puts on f1f_1 covers it within the factor 1+n/r1 + \sqrt{n/r}.

The proof file also proves the lower bound. For γ≥e−r\gamma \ge e^{-r}, let K=n−r2rln⁡1γK = \frac{n - r}{2r}\ln\frac{1}{\gamma}. A column of one value and a column with ⌊K⌋\lfloor K \rfloor extra singletons give the same sample with probability at least γ\gamma, so an estimator that sees only that sample is off by at least K\sqrt{K} on one of them. With n/r=100n/r = 100 and γ=1/2\gamma = 1/2, this is a ratio error of at least 5.86. The proof here gives probability γ/(1+γ)\gamma/(1+\gamma) for randomized estimators; Charikar et al. state probability γ\gamma.

A guarantee on the expected estimate is not a guarantee on each run. On a column of one common value and n/rn/r singletons, the sample misses all singletons with probability near 1/e1/e, and then GEE returns 1 for a true value of n/r+1n/r + 1.

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 nn rows and DD distinct values. A value vv occurs in mv≥1m_v \ge 1 rows, so ∑vmv=n\sum_v m_v = n. The sample SS is a set of rr rows, 1≤r≤n1 \le r \le n, drawn uniformly at random without replacement (line L1). For j≥1j \ge 1, fjf_j is the number of values that occur exactly jj times in SS (lines L2 and L3), and d=∑j≥1fjd = \sum_{j \ge 1} f_j is the number of distinct values in SS. Write c=n/r≥1c = \sqrt{n/r} \ge 1. Line L4 returns

G=cf1+∑j≥2fj=d+(c−1)f1.G = c f_1 + \sum_{j \ge 2} f_j = d + (c - 1) f_1 .

The ratio error of an estimate x>0x > 0 is max⁡(x/D,D/x)\max(x/D, D/x).

Lemma 1 (deterministic range). For every sample, d≤G≤c d≤c Dd \le G \le c\,d \le c\,D.

Proof. G−d=(c−1)f1≥0G - d = (c - 1) f_1 \ge 0 because c≥1c \ge 1. Also f1≤df_1 \le d, so G≤d+(c−1)d=c dG \le d + (c - 1) d = c\,d. Each value of the sample is a value of the column, so d≤Dd \le D. □\square

So GG never overestimates by more than the factor cc, on any sample. If r=nr = n, then c=1c = 1, the sample is the whole column, and G=d=DG = d = D.

Lemma 2 (a missed value is rarer than a value seen once). Let vv be a value with m=mvm = m_v rows. Then Pr⁡[v∉S]≤nrPr⁡[v occurs exactly once in S]\Pr[v \notin S] \le \frac{n}{r} \Pr[v \text{ occurs exactly once in } S].

Proof. There are (nr)\binom{n}{r} equally likely samples. The sample misses vv in (n−mr)\binom{n-m}{r} of them, and contains exactly one row of vv in m(n−mr−1)m \binom{n-m}{r-1} of them. If (n−mr)=0\binom{n-m}{r} = 0, the left side is 0 and there is nothing to prove. Otherwise n−m≥rn - m \ge r, and

m(n−mr−1)(n−mr)=m rn−m−r+1≥m rn≥rn,\frac{m \binom{n-m}{r-1}}{\binom{n-m}{r}} = \frac{m\,r}{n - m - r + 1} \ge \frac{m\,r}{n} \ge \frac{r}{n},

because n−m−r+1≤nn - m - r + 1 \le n and m≥1m \ge 1. □\square

Lemma 3 (expected underestimate). E[G]≥D/(1+c)E[G] \ge D / (1 + c).

Proof. The number of values that the sample misses is D−dD - d. By linearity of expectation and Lemma 2, summed over all values,

E[D−d]=∑vPr⁡[v∉S]≤nr∑vPr⁡[v once in S]=c2E[f1].E[D - d] = \sum_v \Pr[v \notin S] \le \frac{n}{r} \sum_v \Pr[v \text{ once in } S] = c^2 E[f_1].

So D≤E[d]+c2E[f1]D \le E[d] + c^2 E[f_1]. Also E[f1]≤E[d]E[f_1] \le E[d], because f1≤df_1 \le d. Then

(1+c)E[G]=(1+c)E[d]+(c2−1)E[f1]=E[d]+c2E[f1]+(c E[d]−E[f1])≥E[d]+c2E[f1]≥D,(1 + c) E[G] = (1 + c) E[d] + (c^2 - 1) E[f_1] = E[d] + c^2 E[f_1] + \big(c\,E[d] - E[f_1]\big) \ge E[d] + c^2 E[f_1] \ge D,

where the middle step uses c E[d]≥E[d]≥E[f1]c\,E[d] \ge E[d] \ge E[f_1]. □\square

Theorem (correctness of GEE). For every column and every sample size rr, G≤n/r DG \le \sqrt{n/r}\,D on every sample, and E[G]≥D/(1+n/r)E[G] \ge D / (1 + \sqrt{n/r}). So max⁡(E[G]/D, D/E[G])≤1+n/r\max(E[G]/D,\ D/E[G]) \le 1 + \sqrt{n/r}.

Proof. Lemma 1 gives G≤cDG \le c D for every sample, so E[G]/D≤cE[G]/D \le c. Lemma 3 gives D/E[G]≤1+cD/E[G] \le 1 + c. ■\blacksquare

A single estimate can be worse. The theorem bounds the expected estimate, not the ratio error of each run. Take k=n/rk = n/r (an integer) and a column with one value in n−kn - k rows and kk other values in one row each, so D=k+1D = k + 1. The sample misses all kk singletons with probability (n−kr)/(nr)\binom{n-k}{r} / \binom{n}{r}, which tends to e−1e^{-1} when n/rn/r is fixed and rr grows (it is above 1/31/3 for n=400n = 400 and r=20r = 20). On those samples f1=0f_1 = 0, d=1d = 1 and G=1G = 1, so the ratio error is k+1=n/r+1=c2+1k + 1 = n/r + 1 = c^2 + 1. The test file checks this case.

Theorem (lower bound for every estimator). Let 1≤r<n1 \le r < n and e−r≤γ<1e^{-r} \le \gamma < 1, and let K=n−r2rln⁡1γK = \frac{n - r}{2r} \ln \frac{1}{\gamma}. Let EE be any estimator that reads the values of at most rr rows, chosen in any adaptive way and with any random choices, and then outputs x>0x > 0. Then there is a column of nn rows on which EE has ratio error at least K\sqrt{K} with probability at least γ/(1+γ)\gamma / (1 + \gamma). If EE is deterministic, the probability is 1.

Proof. Let k=⌊K⌋k = \lfloor K \rfloor. Because ln⁡(1/γ)≤r\ln(1/\gamma) \le r, K≤(n−r)/2K \le (n - r)/2, so k≤n−rk \le n - r. Column A has the same value 0 in all nn rows, so DA=1D_A = 1. A column of type B has the value 0 in n−kn - k rows and kk distinct other values in the other kk rows, so DB=k+1D_B = k + 1. Let s=k+1s = \sqrt{k + 1}; then s>Ks > \sqrt{K}.

Run EE on column A with its random choices ω\omega. It reads only zeros, so the rows it reads are a set P(ω)P(\omega) of at most rr positions fixed by ω\omega, and it outputs x(ω)x(\omega). Its ratio error on A is x(ω)x(\omega) if x(ω)≥1x(\omega) \ge 1. Let p=Pr⁡[x≥s]p = \Pr[x \ge s] on A.

Now put the kk singletons of B at a set QQ of kk positions chosen uniformly at random, independently of ω\omega. If QQ misses P(ω)P(\omega), then EE with choices ω\omega reads the same zeros on B as on A, so it reads the same rows and outputs the same x(ω)x(\omega). For each fixed ω\omega, QQ misses the at most rr positions of P(ω)P(\omega) with probability at least

q=(n−kr)(nr)=∏i=0r−1(1−kn−i)≥(1−kn−r+1)r.q = \frac{\binom{n-k}{r}}{\binom{n}{r}} = \prod_{i=0}^{r-1} \Big(1 - \frac{k}{n - i}\Big) \ge \Big(1 - \frac{k}{n - r + 1}\Big)^r .

Let t=ln⁡(1/γ)/(2r)t = \ln(1/\gamma) / (2r). Then k/(n−r+1)≤K/(n−r)=tk/(n - r + 1) \le K/(n - r) = t, and t≤1/2t \le 1/2 because γ≥e−r\gamma \ge e^{-r}. On [0,1/2][0, 1/2], 1−t≥e−2t1 - t \ge e^{-2t}: the function 1−t−e−2t1 - t - e^{-2t} is 0 at t=0t = 0, concave, and positive at t=1/2t = 1/2. So q≥e−2tr=γq \ge e^{-2tr} = \gamma.

If x(ω)<sx(\omega) < s and QQ misses P(ω)P(\omega), the ratio error on B is at least DB/x(ω)>(k+1)/s=sD_B / x(\omega) > (k + 1)/s = s. So, over ω\omega and QQ, the probability of ratio error at least ss on B is at least q(1−p)≥γ(1−p)q (1 - p) \ge \gamma (1 - p). This is an average over the choice of QQ, so some fixed placement Q0Q_0 gives a column B with at least this probability. On A the probability is pp. If p≥γ/(1+γ)p \ge \gamma/(1+\gamma), column A is the bad input. Otherwise γ(1−p)>γ⋅11+γ\gamma (1 - p) > \gamma \cdot \frac{1}{1 + \gamma}, and column B with Q0Q_0 is the bad input.

If EE is deterministic, ω\omega is fixed and pp is 0 or 1. If p=1p = 1, column A has ratio error at least ss always. If p=0p = 0, put the singletons at kk positions outside PP, which exist because k≤n−rk \le n - r; then EE outputs x<sx < s on B always. ■\blacksquare

Comparison with the paper. Charikar et al. state the lower bound with probability at least γ\gamma for each γ>e−r\gamma > e^{-r}. The proof above uses the same pair of inputs and gives γ/(1+γ)\gamma/(1+\gamma) for randomized estimators, which is enough for the order of the bound: with γ\gamma a constant, every estimator has ratio error of order n/r\sqrt{n/r} with constant probability on some input. GEE matches this order in the sense of the first theorem: its expected estimate is within a factor 1+n/r1 + \sqrt{n/r} of DD.

Work. Line L1 draws rr rows. Lines L2 and L3 count the values with a hash table, in O(r)O(r) expected time and O(r)O(r) space. Line L4 sums over the at most rr 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 O(r)O(r) expected time and O(r)O(r) space, and line L4 adds up at most rr numbers. Drawing the sample takes O(r)O(r) time when rows can be read by position. On disk it can cost up to rr 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 n−rn - r rows; that is the point of the method.

Properties

  • Never far too high. The estimate is at most n/r\sqrt{n/r} times the true count on every sample. This is a theorem.
  • Bounded bias downward. Its expected value is at least D/(1+n/r)D/(1 + \sqrt{n/r}). This is a theorem.
  • Optimal order. Every estimator that reads rr of nn rows has ratio error of order n/r\sqrt{n/r} 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 r=nr = n, it returns the true count.
  • Uses only the profile. It needs f1f_1 and the sample count dd, 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 (f1f_1, f2f_2, 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 f1f_1 and f2f_2 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 dd 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 n/rn/r 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 f1f_1 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 f1f_1; use the row identifier to remove repeats first.
  • Integer arithmetic. n/r\sqrt{n/r} 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.

guaranteed_error_estimator.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • 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