Sub topic 3
Common Bugs, Faster Variants, and Practical Use
This chapter assumes you have already implemented Algorithm R and understand its proof by induction. You should also be comfortable with Python's heapq and random modules.
Common Bugs: Off-by-One Ranges, Modulo Bias, and Seeding
Most broken samplers come from three mistakes:
| Bug | Symptom | Fix |
|---|---|---|
| `randint(0, i - 1)` instead of `randint(0, i)` | Late items are over-sampled | Remember that `randint` includes both ends, while `randrange` excludes the upper end |
| `getrandbits(32) % (i + 1)` | Small indices are favored slightly | Use `randrange`, which rejects out-of-range values |
| Reseeding inside the loop, or giving every partition the same seed | The samples repeat or are correlated | Create one `random.Random(seed)` per independent stream |
Algorithm L: Skipping Ahead with Geometric Jumps
Algorithm R draws one random number per item. Algorithm L instead draws the number of items to skip before the next replacement from a geometric distribution. That cuts the expected number of random draws to O(k(1 + log(n/k))). It is worth using when items are cheap to skip, for example when you can seek within a file.
Sampling by Random Keys: Keep the k Best
Give each item an independent uniform key and keep the k items with the smallest keys. The result is a uniform sample. Because the keys are stored with the items, this method extends to weighted sampling and to merging.
Weighted Reservoir Sampling with A-Res
The A-Res algorithm (Efraimidis and Spirakis) gives each item the key u^(1/w), where u is uniform on (0, 1) and w is the item's weight. It keeps the k largest keys in a min-heap.
import heapq
import random
def weighted_reservoir(stream, k, rng=random):
heap = [] # min-heap of (key, index, item)
for idx, (item, weight) in enumerate(stream):
if weight <= 0:
continue
key = rng.random() ** (1.0 / weight)
if len(heap) < k:
heapq.heappush(heap, (key, idx, item))
elif key > heap[0][0]:
heapq.heapreplace(heap, (key, idx, item))
return [item for _, _, item in heap]
def merge_reservoirs(a, b, k):
# a and b hold (key, item) pairs built with uniform keys, smallest kept
return heapq.nsmallest(k, a + b, key=lambda pair: pair[0])
rng = random.Random(42)
print(weighted_reservoir([("a", 1), ("b", 5), ("c", 10)], 2, rng))The index in each heap tuple breaks ties between equal keys, so Python never has to compare the items themselves.
Merging Reservoirs Across Partitions
Each worker builds a keyed reservoir from its own partition, using its own seed. To combine them, take the k smallest keys from the union of the reservoirs. The result is a uniform sample of the whole stream. Plain Algorithm R reservoirs cannot be merged this way, because they do not store keys.
Where Reservoir Sampling Fits in Practice
Reservoir sampling fits these cases:
- Log and event sampling.
- Picking A/B test subjects from live traffic.
- Taking samples of query results in a database.
- Picking a random line from a file of unknown size.
If you know n in advance and have random access to the data, random.sample is simpler.
Exercise
A colleague writes j = rng.randint(0, i - 1) in Algorithm R, where i is the 0-based index. Which items are favored, and why?
Show answer
For i ≥ k, item i is kept with probability k/i instead of k/(i+1). That ratio is larger, so every later item is over-represented, and the effect is strongest for items just after the first k. Early items are pushed out more often than they should be.
Exercise
Why can't you merge two Algorithm R reservoirs by randomly picking k items from their union?
Show answer
The two partitions can have different sizes. A uniform merge must weight each reservoir by the size of its partition. Keyed reservoirs handle this automatically, because the k smallest keys of the union are uniform over all items in both partitions.