Sub topic 12
Weighted Reservoir Sampling with A-Res
In earlier chapters every item in the stream had the same chance of being picked. Real streams are often uneven. You might want to sample log lines in proportion to their byte size, users in proportion to their activity, or search queries in proportion to their revenue. This chapter covers A-Res, the weighted reservoir algorithm published by Efraimidis and Spirakis. It keeps a weighted sample of k items in one pass and O(k) memory.
This chapter assumes you know the random-keys idea from the previous chapter (give each item a random key and keep the k best), Python's heapq module, and basic probability with continuous distributions (CDFs and the exponential distribution).
What "Weighted Sample" Means Here
"Weighted sampling" can mean two different things, and they are easy to mix up.
| Interpretation | Definition | Can a stream algorithm with fixed k guarantee it? |
|---|---|---|
| Successive sampling (what A-Res does) | Draw one item with probability w_i / W, remove it, then repeat on the remaining items until k are drawn | Yes |
| Inclusion proportional to weight | Each item appears in the sample with probability exactly k·w_i / W | No, because that value can exceed 1 |
A-Res produces the first kind. It gives the same distribution as this offline procedure: put all items in a bag, draw one with probability proportional to its weight, set it aside, and draw again from what is left.
Here is a small example. Take three items with weights 1, 1, and 8, and k = 2. Item c (weight 8) is left out only if the first two draws are a and b. That happens with probability (1/10)·(1/9) + (1/10)·(1/9) = 2/90. So c is included with probability 88/90 ≈ 0.978. A proportional rule would ask for 2·8/10 = 1.6, which is impossible. Inclusion probabilities always add up to k = 2, so a and b each get (2 − 0.978)/2 ≈ 0.511.
The A-Res Key
For each item with weight w > 0, draw u uniformly from (0, 1) and compute
key = u^(1/w)
Keep the k items with the largest keys. In a stream, that means a min-heap of size k. The heap's root holds the weakest key currently in the reservoir. Each new item either beats the root and replaces it, or it is discarded.
This is the reference implementation:
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]Each heap entry stores idx between the key and the item. If two keys are equal, the tuples are compared by index, so Python never has to compare the items themselves. Without the index, a tie between two dicts would raise TypeError.
Why u^(1/w) Works
Two items
Let K = U^(1/w). For 0 ≤ x ≤ 1, P(K ≤ x) = P(U ≤ x^w) = x^w. So K has CDF x^w and density w·x^(w−1).
For two items with weights w₁ and w₂:
P(K₁ > K₂) = ∫₀¹ P(K₂ < x) · w₁x^(w₁−1) dx = ∫₀¹ w₁ x^(w₁+w₂−1) dx = w₁ / (w₁ + w₂)
The heavier item wins in exact proportion to its weight. The same calculation with n items shows that item i holds the largest key with probability w_i / W.
All k picks: the exponential view
Take logarithms. Define Ei = −ln(Ki) = −ln(Ui) / wi. Since −ln(U) is Exponential(1), Ei is **Exponential with rate wi**. Larger K means smaller E, so "keep the k largest keys" is the same as "keep the k smallest exponentials."
Exponentials have two properties that complete the proof:
- The minimum of independent exponentials with rates wi belongs to item i with probability wi / Σw. That is the first draw of successive sampling.
- The exponential distribution is memoryless. Given which item was the minimum and its value m, the remaining values Ej − m are again independent exponentials with their original rates. So the second-smallest is chosen with probability wj divided by the sum of the remaining weights. That is the second draw.
Repeat this k times and you get exactly the successive-sampling distribution. The order in which items arrive does not matter, because each key depends only on the item's own weight and its own u.
Numerical Failure Modes
The formula rng.random() ** (1.0 / weight) is mathematically correct but can fail in floating point.
| Situation | What goes wrong |
|---|---|
| Very small weight (e.g. 1e-6) | 1/w is huge, so u^(1/w) underflows to 0.0. Many items tie at 0 and the index tie-break decides instead of the weights. |
| Very large weight (e.g. 1e9) | 1/w is tiny, so keys round to 1.0 or pack close to it. Distinct weights produce equal keys. |
| `rng.random()` returns 0.0 | Key is 0. This is rare, but it breaks the log-space fix below. |
| Negative or NaN weight | Meaningless. Silently skipping it hides bad data. |
The fix is to compare log keys: ln(u)/w. Because ln is increasing, the order of the keys is unchanged and the result is identical. The log key lies in (−∞, 0) and stays well scaled across many orders of magnitude of weight.
The block below is self-contained. It runs the log-key version and checks it against exact inclusion probabilities computed by enumerating every possible draw order.
import heapq
import math
import random
from collections import Counter
from itertools import permutations
def _open_unit(rng):
u = 0.0
while u == 0.0:
u = rng.random() # value in (0, 1)
return u
def weighted_reservoir_log(stream, k, rng=random):
heap = [] # min-heap of (log_key, index, item)
for idx, (item, weight) in enumerate(stream):
if math.isnan(weight) or weight < 0:
raise ValueError(f"invalid weight {weight!r} at index {idx}")
if weight == 0:
continue # zero weight: never sampled
log_key = math.log(_open_unit(rng)) / weight # larger is better
if len(heap) < k:
heapq.heappush(heap, (log_key, idx, item))
elif log_key > heap[0][0]:
heapq.heapreplace(heap, (log_key, idx, item))
return [item for _, _, item in heap]
def exact_inclusion(weights, k):
# Sum the probability of every ordered sequence of k successive draws
n = len(weights)
probs = [0.0] * n
for order in permutations(range(n), k):
p, remaining = 1.0, sum(weights)
for i in order:
p *= weights[i] / remaining
remaining -= weights[i]
for i in order:
probs[i] += p
return probs
items = [("a", 1.0), ("b", 1.0), ("c", 8.0), ("d", 1e-7), ("e", 1e7)]
weights = [w for _, w in items]
k, trials = 2, 100_000
rng = random.Random(12345)
counts = Counter()
for _ in range(trials):
for x in weighted_reservoir_log(items, k, rng):
counts[x] += 1
for (name, _), p in zip(items, exact_inclusion(weights, k)):
print(f"{name}: empirical {counts[name] / trials:.4f} exact {p:.4f}")You should see item e at about 1.0. The remaining slot is split among a, b, and c in roughly 1 : 1 : 8 proportion, so c gets about 0.8 and a and b about 0.1 each. Item d is essentially never chosen. The empirical numbers should match the exact column to within about ±0.003.
Cost
- Space: O(k) for the heap.
- Time: one random number and one logarithm per item, plus O(log k) for each heap replacement. The worst case is O(n log k).
- Replacements: For equal weights, A-Res reduces to the random-keys uniform sampler, and the expected number of heap insertions is about k(1 + ln(n/k)), the same as Algorithm R. When heavy items arrive late they cause more replacements. When they arrive early, fewer.
A-Res still draws a random number for every item. The same paper describes A-ExpJ, which plays the role for weighted sampling that Algorithm L plays for uniform sampling. Instead of drawing a key per item, it draws an exponential "weight budget" X = ln(u)/ln(T), where T is the current minimum key. It then skips items while subtracting their weights from X, and only the item that exhausts the budget enters the reservoir. Its new key is drawn from the range (T^w, 1), so it is guaranteed to beat T. This cuts random-number calls to O(k log(n/k)) in expectation. It only pays off when random-number generation, not reading the stream, is your bottleneck.
Gotchas Checklist
- Largest, not smallest. With u^(1/w) you keep the largest keys. Some write-ups use −ln(u)/w and keep the smallest. Both are correct, but mixing them up silently favors light items.
- Do not use u·w or u/w as a key. These look plausible, but they do not give probability w₁/(w₁ + w₂) for pairwise wins.
- Weights are relative. Multiplying all weights by a constant does not change the distribution.
- Fewer than k positive weights. The function returns fewer than k items. Decide whether callers should treat that as an error.
- Seeding. Pass a seeded
random.Randominstance for reproducible tests. Do not reseed the global generator inside library code.
Exercise
Two items have weights 3 and 1, and k = 1. Using the CDF P(K ≤ x) = x^w, compute the probability that the weight-3 item is selected. Then state which key, u·w or u^(1/w), gives this answer.
Show answer
P(K₁ > K₂) = ∫₀¹ x^1 · 3x^2 dx = 3/4, which is w₁/(w₁ + w₂). The key u^(1/w) produces this. With u·w, the weight-1 key is uniform on (0,1) and the weight-3 key is uniform on (0,3). The weight-3 item loses only if its key is below 1 and below the other key, which happens with probability (1/3)(1/2) = 1/6. So it wins with probability 5/6, not 3/4.
Exercise
Weights are 1, 1, 8 and k = 2. A colleague estimates a population total by dividing each sampled value by k·w_i/W. Why is this estimator biased, and what probability should be used instead?
Show answer
The true inclusion probabilities from A-Res are about 0.511, 0.511, and 0.978, not 0.2, 0.2, and 1.6. A value of 1.6 is not even a valid probability. An unbiased Horvitz–Thompson estimate divides each sampled value by its actual inclusion probability, which you can compute exactly (as exact_inclusion does) for small n, or by a priority-sampling style estimator for large n.
Exercise
You run weighted_reservoir (the u^(1/w) version) on weights spanning 1e-9 to 1e9 and see that low-weight items are picked in stream order instead of by weight. Explain the cause and the fix.
Show answer
For tiny weights, 1/w is about 1e9, so u^(1/w) underflows to 0.0. Those items tie, and the tie is broken by index, which follows stream order. The fix is to compare log keys ln(u)/w, with u drawn from the open interval (0,1). The order is the same in theory, but the log values stay finite and distinct.