Sub topic 8
Checking Uniformity Empirically
This chapter assumes you have read the Algorithm R chapter and its correctness proof. You should also be comfortable with Python's random module, and with the ideas of mean and standard deviation. The proof says Algorithm R is correct. A test checks that your code is correct, and the two can differ: one wrong range bound in the code can break it while the proof still holds.
Two Levels of Uniformity
A uniform sample of k items from n has two properties you can measure:
| Property | Expected value | What it catches |
|---|---|---|
| Inclusion frequency of each item | k/n | Items favored or ignored by position |
| Frequency of each k-subset | 1 / C(n, k) | Correlations between items, such as items that always appear together |
Inclusion frequency is the cheaper check, but it is weaker. A sampler can give every item probability k/n and still be badly non-uniform over subsets. The subset test is stronger and is practical when C(n, k) is small.
Measuring Deviation Correctly
With T trials, an item's inclusion count follows a binomial distribution with p = k/n. Its observed frequency has standard error sqrt(p(1 − p)/T). For n = 10, k = 3, and T = 100,000, that comes to about 0.00145. A frequency of 0.302 is therefore fine. A frequency of 0.32 is about 14 standard errors away from 0.3 and points to a bug.
For subsets, the counts form a multinomial distribution over C(n, k) outcomes. A chi-square statistic, sum((observed − expected)² / expected), has C(n, k) − 1 degrees of freedom. The chi-square test is valid for subset counts. It is not valid for per-item inclusion counts, because those counts are dependent: every trial contributes exactly k of them.
A Complete Test Harness
The harness below tests the correct sampler and a buggy one. The buggy sampler uses randint(0, i - 1), a common off-by-one mistake.
import random
from collections import Counter
from itertools import combinations
def reservoir_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i)
if j < k:
reservoir[j] = item
return reservoir
def buggy_sample(stream, k, rng=random):
reservoir = []
for i, item in enumerate(stream):
if i < k:
reservoir.append(item)
else:
j = rng.randint(0, i - 1) # bug: excludes i
if j < k:
reservoir[j] = item
return reservoir
def inclusion_z(sampler, n, k, trials, rng):
counts = Counter()
for _ in range(trials):
counts.update(sampler(range(n), k, rng))
p = k / n
se = (p * (1 - p) / trials) ** 0.5
return max(abs(counts[x] / trials - p) / se for x in range(n))
def subset_chi_square(sampler, n, k, trials, rng):
counts = Counter(frozenset(sampler(range(n), k, rng)) for _ in range(trials))
subsets = [frozenset(s) for s in combinations(range(n), k)]
expected = trials / len(subsets)
stat = sum((counts[s] - expected) ** 2 / expected for s in subsets)
return stat, len(subsets) - 1
for name, sampler in [("correct", reservoir_sample), ("buggy", buggy_sample)]:
rng = random.Random(12345)
z = inclusion_z(sampler, 10, 3, 100_000, rng)
stat, df = subset_chi_square(sampler, 5, 2, 100_000, rng)
# 27.88 is the chi-square critical value for df=9 at alpha=0.001
print(f"{name}: max z = {z:.2f}, chi2 = {stat:.1f} (df={df}), "
f"pass = {z < 4.5 and stat < 27.88}")The correct sampler gives a max z below about 3 and a chi-square near 9. The buggy sampler always keeps item k, so both statistics are huge.
Choosing Sizes
Keep n and k small enough that C(n, k) stays in the tens or low hundreds. Then choose T so that each subset's expected count is at least about 50. Small streams also exercise the boundary at i = k, where off-by-one bugs usually show up.
Exercise
Describe a sampler for n = 4, k = 2 that includes every item with probability exactly 1/2 but is not uniform. Which test above detects it?
Show answer
Return {0, 1} or {2, 3}, each with probability 1/2. Every item is included half the time, so the inclusion test passes. Only 2 of the C(4, 2) = 6 subsets ever appear, so the subset chi-square test fails by a wide margin.
Exercise
For n = 20, k = 5, and T = 50,000, what is the standard error of an item's inclusion frequency, and would an observed 0.258 be suspicious?
Show answer
p = 0.25, so SE = sqrt(0.25 × 0.75 / 50,000) ≈ 0.00194. The deviation is 0.008, or about 4.1 standard errors. That is suspicious for a single item, though it sits near a 4.5 threshold applied to the max of 20 items. Rerun with a larger T to decide.