Sub topic 12
Weighted Reservoir Sampling with A-Res
This chapter assumes you know the random-keys view of reservoir sampling from the previous chapter: give each item a random key and keep the k items with the best keys. It also assumes you can use Python's heapq module and that you know the uniform distribution on (0, 1).
The Problem
Sometimes items should not be equally likely. A log line from a busy server might count more than one from an idle server. A search result might carry a relevance score. In both cases you want a sample where an item with weight 2 is favored over an item with weight 1, and you still have only one pass and O(k) memory.
A-Res, from Efraimidis and Spirakis (2006), solves this with a small change to the random-keys method. The key stops being a plain uniform number and starts depending on the item's weight.
The Key Formula
For an item with weight w > 0, draw u uniformly from (0, 1) and compute:
key = u^(1/w)
Then keep the k items with the largest keys. A larger weight makes the exponent 1/w smaller, which pushes the key toward 1. Heavy items therefore tend to win.
This rule gives a specific guarantee. The resulting sample has the same distribution as drawing k items one at a time without replacement, where each draw picks a remaining item with probability equal to its weight divided by the total remaining weight. For k = 1 this means item i is chosen with probability w_i / Σw.
Processing Each Item
A min-heap keeps the smallest retained key at heap[0]. That is the key a newcomer has to beat. Each item costs O(log k) time and the heap uses O(k) space.
Implementation
import heapq
import random
from collections import Counter
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]
# Check with k = 1: picks should match weight shares 0.1, 0.2, 0.7
data = [("a", 1), ("b", 2), ("c", 7)]
trials = 100_000
counts = Counter(weighted_reservoir(data, 1)[0] for _ in range(trials))
for name, _ in data:
print(name, counts[name] / trials)The idx field breaks ties between equal keys. Without it, heapq would fall back to comparing the items themselves, which fails for types such as dicts that do not support ordering.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Using `u ** w` instead of `u ** (1/w)` | Heavy items become *less* likely | Use the exponent 1/w |
| Very small weights | `u ** (1/w)` underflows to 0.0, so many keys tie | Compare `log(u) / w` instead; it orders items the same way |
| Keeping smallest keys | Light items get favored | Keep the largest keys (min-heap, evict minimum) |
| Zero or negative weights | `ZeroDivisionError` or nonsense keys | Skip them or reject them at input |
The log form works because log is increasing, so ranking by log(u)/w gives the same order as ranking by u^(1/w). The log form stays in a safe floating-point range even when w is tiny. Because the keys are stored alongside the items, weighted reservoirs can also be merged across partitions, which the next chapter covers.
Exercise
With weights a=1, b=3 and k=1, what is the probability that A-Res returns b? Then explain why the variant key = u * w (multiply instead of exponentiate) would not give this probability.
Show answer
P(b) = 3 / (1 + 3) = 0.75. With key = u^(1/w), P(key ≤ x) = x^w, so the k=1 winner follows the exact weight-proportional rule. With key = u * w, key a is uniform on (0,1) and key b is uniform on (0,3). b wins whenever its key exceeds 1 (probability 2/3), and otherwise with probability 1/2 of the remaining 1/3, giving 2/3 + 1/6 = 5/6 ≈ 0.833. That is not 0.75, so the multiplicative key is biased.