Reservoir Sampling
A random sample is the most flexible summary there is: any statistic of the sample estimates the same statistic of the data, and questions nobody thought of in advance can still be asked of it. Drawing items uniformly from an array is easy when its length is known. In a stream the length is not known until the end, and the sample must be ready at every moment. Reservoir sampling solves this with words of memory and one random number per item, and a refinement needs only random numbers in total.
Algorithm R
The method is usually called Algorithm R; Vitter (1985) analysed it and attributed it to Alan Waterman.
Reservoir sampling (Algorithm R): a uniform k-subset of a stream of unknown length
1 R ← the first k items
2 for t ← k+1, k+2, ... (item a_t arrives):
3 j ← uniform random integer in {1, ..., t}
4 if j ≤ k: R[j] ← a_t (a_t replaces a uniformly chosen member)
5 at any time: report RTheorem. After items, is a uniformly random -subset of the positions : every one of the subsets has probability .
Proof. By induction on . For the reservoir is the only -subset. Suppose the claim holds after items, and fix a -subset of .
- If , the reservoir equals after step exactly when it equalled before and was rejected: probability .
- If , the reservoir equals when, before step , it held plus one other position (there are choices of ), and was accepted () and replaced exactly (probability for the specific slot): .
Both equal , using .
In particular every item is in the sample with probability , but the theorem says more: the joint distribution is that of sampling without replacement, so any estimator designed for a simple random sample is valid. A sample with replacement is independent reservoirs of size 1.
The program verifies the theorem exactly for and : it enumerates every possible sequence of random choices (each equally likely) and counts the reservoirs they produce.
from fractions import Fraction
from itertools import product
from collections import Counter
def reservoir_R(stream, k, choices):
"""Algorithm R with 0-based positions; choices[t] is the index j drawn from {0, ..., t}."""
R = list(stream[:k])
for t in range(k, len(stream)):
j = choices[t]
if j < k:
R[j] = stream[t]
return frozenset(R)
m, k = 6, 2
stream = "abcdef"
dist = Counter()
total = 0
for js in product(*[range(t + 1) for t in range(k, m)]): # j uniform in {0, ..., t}
dist[reservoir_R(stream, k, dict(zip(range(k, m), js)))] += 1
total += 1
print(f"{total} equally likely choice sequences; {len(dist)} different reservoirs")
print(" ".join(f"{''.join(sorted(S))} {Fraction(dist[S], total)}" for S in sorted(dist, key=sorted)))
print("all equal to 1/C(6,2) = 1/15:", set(Fraction(c, total) for c in dist.values()) == {Fraction(1, 15)})360 equally likely choice sequences; 15 different reservoirs
ab 1/15 ac 1/15 ad 1/15 ae 1/15 af 1/15 bc 1/15 bd 1/15 be 1/15 bf 1/15 cd 1/15 ce 1/15 cf 1/15 de 1/15 df 1/15 ef 1/15
all equal to 1/C(6,2) = 1/15: True
Skipping: Algorithm L
Algorithm R draws a random number for every item, although after a while almost all items are rejected: the expected number of replacements is . A different view of the same distribution lets the algorithm jump straight to the next replacement.
Give each item an independent key uniform in , and keep the items with the smallest keys. By symmetry this is a uniform -subset. Let be the largest key in the reservoir. The next item enters exactly when its key is below , so the number of items until the next replacement is geometric with success probability and can be drawn with one random number: . Given that a key entered, the new is the maximum of keys uniform on , which is distributed as . The algorithm never stores keys, only :
Algorithm L (Li, 1994)
1 R ← the first k items; W ← U^(1/k) (U uniform in (0,1), fresh each time)
2 i ← k
3 loop:
4 i ← i + ⌊ln U / ln(1 − W)⌋ + 1 (skip the rejected items)
5 if the stream ended before item i: stop
6 R[uniform slot in 1..k] ← a_i
7 W ← W · U^(1/k)Each replacement costs three random numbers, so about in total, and the skipped items cost no work at all if the source can seek (a file on disk, for example). The program compares both algorithms on a stream of positions with , and checks that Algorithm L still samples every part of the stream equally often.
import math, random
def algorithm_R(m, k, rng):
R, draws = list(range(k)), 0
for t in range(k, m):
j = rng.randrange(t + 1)
draws += 1
if j < k:
R[j] = t
return R, draws
def algorithm_L(m, k, rng):
R, draws = list(range(k)), 1
W = math.exp(math.log(1.0 - rng.random()) / k)
i = k - 1
while True:
i += int(math.log(1.0 - rng.random()) / math.log1p(-W)) + 1 # skip a geometric number of items
draws += 1
if i >= m:
return R, draws
R[rng.randrange(k)] = i
W *= math.exp(math.log(1.0 - rng.random()) / k)
draws += 2
rng = random.Random(1985)
m, k = 10000, 10
for name, alg, runs in [("R", algorithm_R, 100), ("L", algorithm_L, 8000)]:
hits, draws = [0] * 10, 0
for _ in range(runs):
R, d = alg(m, k, rng)
draws += d
for x in R:
hits[x * 10 // m] += 1
print(f"Algorithm {name}, {runs} runs: {draws / runs:7.1f} random numbers per run")
print(f" sample members per tenth of the stream (expected {runs * k // 10} each): {hits}")
print(f"3 k ln(m/k) = {3 * k * math.log(m / k):.1f}")Algorithm R, 100 runs: 9990.0 random numbers per run
sample members per tenth of the stream (expected 100 each): [101, 95, 102, 112, 94, 114, 94, 100, 92, 96]
Algorithm L, 8000 runs: 207.5 random numbers per run
sample members per tenth of the stream (expected 8000 each): [8234, 7926, 7941, 8035, 7885, 7895, 7955, 7998, 7979, 8152]
3 k ln(m/k) = 207.2
Algorithm L needed about 2% of the random numbers of Algorithm R, matching , and the counts per tenth of the stream are within three standard deviations () of the expected 8000.
In C++
Algorithm R as a reusable class template. The random index uses Lemire's multiply-shift reduction of a 64-bit random word, whose bias is below and negligible here. The test runs 100 000 reservoirs of size 3 over a 20-item stream (each position should appear times) and then samples 8 items from a million.
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
template <class T>
class Reservoir {
std::size_t k, seen = 0;
std::vector<T> R;
std::mt19937_64& rng;
std::uint64_t below(std::uint64_t n) { // uniform in [0, n), Lemire's reduction
return static_cast<std::uint64_t>((static_cast<unsigned __int128>(rng()) * n) >> 64);
}
public:
Reservoir(std::size_t k, std::mt19937_64& rng) : k(k), rng(rng) { R.reserve(k); }
void add(const T& x) {
++seen;
if (R.size() < k) { R.push_back(x); return; }
std::uint64_t j = below(seen); // j in {0, ..., seen - 1}
if (j < k) R[j] = x;
}
const std::vector<T>& sample() const { return R; }
};
int main() {
std::mt19937_64 rng(1985);
std::vector<int> hits(20, 0);
for (int run = 0; run < 100000; ++run) {
Reservoir<int> r(3, rng);
for (int x = 0; x < 20; ++x) r.add(x);
for (int x : r.sample()) ++hits[x];
}
int lo = hits[0], hi = hits[0];
for (int h : hits) { lo = h < lo ? h : lo; hi = h > hi ? h : hi; }
std::printf("position counts over 100000 runs: min %d, max %d (expected 15000)\n", lo, hi);
Reservoir<long> big(8, rng);
for (long x = 0; x < 1000000; ++x) big.add(x);
std::printf("8 of 1000000:");
for (long x : big.sample()) std::printf(" %ld", x);
std::printf("\n");
}position counts over 100000 runs: min 14730, max 15285 (expected 15000)
8 of 1000000: 655977 861978 171620 934300 394814 532486 622754 803589
Uses and variants
- Distributed sampling. Several machines each keep a reservoir; to merge them, keep the keys of the "smallest keys" view and take the smallest overall. This is exactly why the key view is useful beyond speed.
- Weighted sampling, where item should be chosen with probability proportional to a weight , uses keys too: the next lesson shows how.
- Deletions break reservoir sampling: once an item has been replaced it cannot be brought back. Sampling in turnstile streams needs linear sketches (-sampling).
- Sampling distinct items (each distinct value with the same probability, regardless of its frequency) is not what a reservoir does: a reservoir favours frequent values. Hashing the value and keeping the smallest hashes does it, which is the k minimum values sketch.
Test yourself
In Algorithm R, with what probability is the -th item () put into the reservoir when it arrives?
- , with the final length
What does the inductive proof establish beyond 'each item is sampled with probability '?
- Nothing more
- That every -subset of the first positions is equally likely, so the sample is a simple random sample without replacement
- That the sample is sorted
- That the sample has no duplicates of values
How many random numbers does Algorithm L use, in expectation, for a stream of length ?
- , a constant number per replacement
Why can reservoir sampling not support deletions?
- It uses too much memory
- An item replaced earlier is gone, so when a sampled item is deleted there is nothing to put back that keeps the sample uniform
- Random numbers cannot be negative
- Deletions change