TExcelTAD

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 kk items uniformly from an array is easy when its length is known. In a stream the length mm is not known until the end, and the sample must be ready at every moment. Reservoir sampling solves this with kk words of memory and one random number per item, and a refinement needs only O(klog⁡(m/k))O(k \log(m/k)) random numbers in total.

Algorithm R

The method is usually called Algorithm R; Vitter (1985) analysed it and attributed it to Alan Waterman.

text
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 R

Theorem. After t≥kt \ge k items, RR is a uniformly random kk-subset of the positions {1,…,t}\{1, \ldots, t\}: every one of the (tk)\binom{t}{k} subsets has probability 1/(tk)1/\binom{t}{k}.

Proof. By induction on tt. For t=kt = k the reservoir is the only kk-subset. Suppose the claim holds after t−1t - 1 items, and fix a kk-subset SS of {1,…,t}\{1, \ldots, t\}.

  • If t∉St \notin S, the reservoir equals SS after step tt exactly when it equalled SS before and ata_t was rejected: probability (t−1k)−1⋅t−kt\binom{t-1}{k}^{-1} \cdot \frac{t-k}{t}.
  • If t∈St \in S, the reservoir equals SS when, before step tt, it held S∖{t}S \setminus \{t\} plus one other position rr (there are t−kt - k choices of rr), and ata_t was accepted (j≤kj \le k) and replaced exactly rr (probability 1t\frac{1}{t} for the specific slot): (t−k)⋅(t−1k)−1⋅1t(t - k) \cdot \binom{t-1}{k}^{-1} \cdot \frac{1}{t}.

Both equal t−kt(t−1k)−1=(tk)−1\frac{t-k}{t} \binom{t-1}{k}^{-1} = \binom{t}{k}^{-1}, using (tk)=tt−k(t−1k)\binom{t}{k} = \frac{t}{t-k}\binom{t-1}{k}. □\square

In particular every item is in the sample with probability k/tk/t, 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 kk independent reservoirs of size 1.

The program verifies the theorem exactly for m=6m = 6 and k=2k = 2: it enumerates every possible sequence of random choices (each equally likely) and counts the reservoirs they produce.

python · try it yourself
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 ∑t=k+1mkt≈kln⁡(m/k)\sum_{t=k+1}^{m} \frac{k}{t} \approx k \ln(m/k). A different view of the same distribution lets the algorithm jump straight to the next replacement.

Give each item an independent key utu_t uniform in (0,1)(0, 1), and keep the kk items with the smallest keys. By symmetry this is a uniform kk-subset. Let WW be the largest key in the reservoir. The next item enters exactly when its key is below WW, so the number of items until the next replacement is geometric with success probability WW and can be drawn with one random number: ⌊ln⁡U/ln⁡(1−W)⌋+1\lfloor \ln U / \ln(1 - W) \rfloor + 1. Given that a key entered, the new WW is the maximum of kk keys uniform on (0,W)(0, W), which is distributed as W⋅U1/kW \cdot U^{1/k}. The algorithm never stores keys, only WW:

text
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 3kln⁡(m/k)3k\ln(m/k) 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 m=10 000m = 10\,000 positions with k=10k = 10, and checks that Algorithm L still samples every part of the stream equally often.

python · try it yourself
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 3kln⁡(m/k)3k \ln(m/k), and the counts per tenth of the stream are within three standard deviations (8000≈89\sqrt{8000} \approx 89) 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 t/264t/2^{64} and negligible here. The test runs 100 000 reservoirs of size 3 over a 20-item stream (each position should appear 100 000⋅3/20=15 000100\,000 \cdot 3/20 = 15\,000 times) and then samples 8 items from a million.

cpp · try it yourself
#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 kk smallest overall. This is exactly why the key view is useful beyond speed.
  • Weighted sampling, where item tt should be chosen with probability proportional to a weight wtw_t, 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 (ℓ0\ell_0-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 tt-th item (t>kt > k) put into the reservoir when it arrives?

  1. 1/t1/t
  2. k/tk/t
  3. 1/k1/k
  4. k/mk/m, with mm the final length

What does the inductive proof establish beyond 'each item is sampled with probability k/tk/t'?

  1. Nothing more
  2. That every kk-subset of the first tt positions is equally likely, so the sample is a simple random sample without replacement
  3. That the sample is sorted
  4. That the sample has no duplicates of values

How many random numbers does Algorithm L use, in expectation, for a stream of length mm?

  1. mm
  2. O(klog⁡(m/k))O(k \log(m/k)), a constant number per replacement
  3. O(k)O(k)
  4. O(m)O(\sqrt{m})

Why can reservoir sampling not support deletions?

  1. It uses too much memory
  2. An item replaced earlier is gone, so when a sampled item is deleted there is nothing to put back that keeps the sample uniform
  3. Random numbers cannot be negative
  4. Deletions change kk