Sub topic 2
What a Uniform Sample Without Replacement Means
Before building any streaming sampler, you need a precise statement of what it should produce. "Pick k random items" sounds clear, but it can mean several different things. Some of them are weaker than they look. This chapter pins down the target that every later algorithm in this tutorial must hit.
This chapter assumes you know basic Python (loops, sets, iterators), elementary probability (uniform distributions, independence, conditional probability), and binomial coefficients, written C(n, k).
The definition
Suppose a stream contains n items, indexed by position 1 through n. A sample without replacement of size k is a set of k distinct positions. No position can appear twice.
The sample is uniform when every possible set of k positions has the same probability of being chosen. There are C(n, k) such sets, so each one must have probability:
P(S) = 1 / C(n, k) for every subset S of {1, ..., n} with |S| = kThis is the full requirement. Uniformity is a property of the distribution over whole subsets, not of single items one at a time.
Positions, not values
The sample is defined over positions in the stream, not over distinct values. If the stream is ["a", "a", "b"] and k = 1, a uniform sampler returns "a" with probability 2/3 and "b" with probability 1/3. That is the correct behavior: the sample should mirror the stream, duplicates included. If you want a uniform sample of distinct values, that is a different problem. It needs deduplication first, which usually means hashing or a distinct-counting sketch.
The edge case n < k
If the stream ends before k items arrive, no k-subset exists. The standard convention, which the samplers in this tutorial follow, is to return all n items. Treat that as part of the specification so that callers handle short streams on purpose.
What uniformity implies
Two consequences follow directly from the definition. Both are useful for checking a sampler.
Inclusion probability is k/n
Fix one position i. The k-subsets that contain i are formed by choosing the other k − 1 members from the remaining n − 1 positions. So:
P(i in S) = C(n-1, k-1) / C(n, k) = k / nEvery item has the same chance, k/n, of being in the sample. A later chapter proves that Algorithm R achieves exactly this.
Pairs, triples, and beyond
The same counting argument works for any fixed group of positions. For two distinct positions i and j:
P(i in S and j in S) = C(n-2, k-2) / C(n, k) = k(k-1) / (n(n-1))In general, any fixed set of m ≤ k positions is fully included with probability C(n−m, k−m) / C(n, k). Under uniform sampling, no item is favored, and no pair or larger group is favored either.
Equal inclusion probability is not enough
A common mistake is to treat "each item appears with probability k/n" as the definition of a uniform sample. It is a necessary condition but not a sufficient one. Many unfair samplers meet it.
Systematic sampling is a standard counterexample. With n = 6 and k = 2, pick a random start in {0, 1, 2} and take every third position. Only three subsets can ever come out: {0, 3}, {1, 4}, and {2, 5}. Each item still has inclusion probability 1/3 = k/n, but 12 of the 15 possible subsets have probability zero.
The code below computes exact distributions with fractions, so the comparison involves no random noise.
from fractions import Fraction
from itertools import combinations
from math import comb
def uniform_distribution(n, k):
# The target: every k-subset of positions 0..n-1 has probability 1/C(n, k)
p = Fraction(1, comb(n, k))
return {frozenset(c): p for c in combinations(range(n), k)}
def systematic_distribution(n, k):
# Random start in 0..step-1, then every step-th position (assumes k divides n)
step = n // k
dist = {}
for start in range(step):
s = frozenset(range(start, n, step))
dist[s] = dist.get(s, 0) + Fraction(1, step)
return dist
def inclusion(dist, n):
return [sum(p for s, p in dist.items() if i in s) for i in range(n)]
def pair_inclusion(dist, i, j):
return sum(p for s, p in dist.items() if i in s and j in s)
n, k = 6, 2
for name, dist in [("uniform", uniform_distribution(n, k)),
("systematic", systematic_distribution(n, k))]:
print(name)
print(" possible subsets:", sum(1 for p in dist.values() if p > 0),
"of", comb(n, k))
print(" single inclusion:", [str(p) for p in inclusion(dist, n)])
print(" P(0 and 1):", pair_inclusion(dist, 0, 1),
" P(0 and 3):", pair_inclusion(dist, 0, 3))Running it prints:
uniform
possible subsets: 15 of 15
single inclusion: ['1/3', '1/3', '1/3', '1/3', '1/3', '1/3']
P(0 and 1): 1/15 P(0 and 3): 1/15
systematic
possible subsets: 3 of 15
single inclusion: ['1/3', '1/3', '1/3', '1/3', '1/3', '1/3']
P(0 and 1): 0 P(0 and 3): 1/3The single-item inclusion rows match exactly. The pair probabilities show the difference. In practice this matters: if the stream has a period of 3, such as hourly logs from three alternating servers, the systematic sampler could return items from only one server.
Without replacement versus nearby alternatives
Several sampling schemes look similar to this one. The table compares them.
| Scheme | Sample size | Repeats possible | Each k-subset equally likely | Python in-memory equivalent |
|---|---|---|---|---|
| Uniform without replacement | exactly min(k, n) | no | yes | `random.sample(items, k)` |
| Uniform with replacement | exactly k | yes | not applicable (multisets) | `random.choices(items, k=k)` |
| Bernoulli (keep each with prob p) | random, mean pn | no | only conditional on size | `[x for x in items if random.random() < p]` |
| Systematic | exactly k | no | no | random start, fixed step |
With replacement, the same position can be drawn twice. The chance of at least one repeat is 1 − n(n−1)⋯(n−k+1)/n^k, which is large once k approaches √n. For n = 10,000 and k = 100 it is about 39%. If your downstream code assumes distinct items, such as training and test splits or audit sets, with-replacement sampling silently breaks that assumption.
Bernoulli sampling produces a sample whose size varies from run to run. Given its size, the sample is uniform, but you cannot control k, and choosing p requires knowing n. The next chapter covers why that is a problem for streams.
An equivalent sequential view
Uniform sampling without replacement can also be described as a process. Choose the first member uniformly from all n positions, the second uniformly from the remaining n − 1, and so on, k times, then forget the order. Each ordered sequence has probability 1 / (n(n−1)⋯(n−k+1)). Each unordered set corresponds to k! sequences, so it gets probability k!(n−k)!/n! = 1/C(n, k), which matches the definition.
This view also explains what random.sample does internally. A streaming algorithm cannot use it directly, because the first draw already needs n. Reservoir sampling reaches the same distribution without knowing n in advance.
Order inside the sample
The definition covers which items are chosen, not how they are arranged. Reservoir algorithms return a list, and the order of that list is usually not a uniform random permutation. In Algorithm R, for example, if the first item survives it stays in slot 0. Code that takes reservoir[0] as "a random item" is therefore biased toward early stream items.
Using `random.sample` as a reference
When n is small enough to fit in memory, random.sample gives you a trusted reference for the target distribution. The snippet below counts whole subsets, which is the strongest practical check for small n. You can run the same harness against your own streaming sampler later.
import random
from collections import Counter
from math import comb
n, k, trials = 5, 2, 200_000
counts = Counter(frozenset(random.sample(range(n), k)) for _ in range(trials))
expected = trials / comb(n, k)
for subset, c in sorted(counts.items(), key=lambda kv: sorted(kv[0])):
print(sorted(subset), c, f"(expected about {expected:.0f})")
print("distinct subsets seen:", len(counts), "of", comb(n, k))Each of the 10 subsets should appear about 20,000 times. A later chapter shows how to turn "about" into a formal chi-square test.
Exercise
For n = 8 and k = 3, what is the probability that a uniform sample without replacement contains both position 2 and position 5? What is the probability that it contains neither?
Show answer
Both: k(k-1)/(n(n-1)) = 32/(87) = 6/56 = 3/28. Neither: the sample must come entirely from the other 6 positions, so C(6,3)/C(8,3) = 20/56 = 5/14.
Exercise
A sampler for n = 4, k = 2 returns {0,1} or {2,3}, each with probability 1/2. Does every item have inclusion probability k/n? Is the sampler uniform? Name a statistic that exposes the problem.
Show answer
Yes, each item appears with probability 1/2 = 2/4. It is not uniform: only 2 of the C(4,2) = 6 subsets can occur, while a uniform sampler gives each subset probability 1/6. Pair inclusion exposes it: P(0 and 1) = 1/2 instead of 1/6, and P(0 and 2) = 0.
Exercise
A stream is ["x", "y", "x", "x"], and you draw a uniform sample of size 2 over positions. What is the probability that the sample contains the value "y"?
Show answer
"y" occupies one position, so its inclusion probability is k/n = 2/4 = 1/2. Sampling is defined over positions, so duplicate "x" values do not change this.