Weighted Sampling: Efraimidis-Spirakis
Often items do not count equally. A network monitor wants to sample flows in proportion to their bytes, a search engine samples queries in proportion to the revenue they bring, and an index samples documents by length. Weighted reservoir sampling draws a sample in one pass where item , arriving with weight , is chosen with probability proportional to . Efraimidis and Spirakis (2006) found a strikingly simple way to do it: give every item a random key that depends on its weight, and keep the items with the largest keys. The same idea, with a different key, gives priority sampling, the standard tool for estimating sums over arbitrary subsets of a weighted stream.
Keys instead of coin flips
The previous lesson showed that a uniform reservoir is the set of items with the smallest (equivalently, largest) uniform random keys. For weights, draw uniform in and use the key
A heavier item raises its uniform number to a smaller power, which pushes the key towards 1.
Weighted reservoir (A-Res, Efraimidis and Spirakis, 2006)
1 H ← empty min-heap of (key, item)
2 for each item x with weight w:
3 κ ← U^(1/w) (U uniform in (0,1), fresh each time)
4 if |H| < k: insert (κ, x) into H
5 else if κ > min key in H: replace the minimum by (κ, x)
6 report the items in HTheorem. For , item ends up as the sample with probability .
Proof. for , so has density . The maximum of the other keys is at most with probability , where . Hence
For , the same calculation applied repeatedly shows that the item with the largest key is distributed proportionally to weight, and conditioned on it, the item with the second largest key is distributed proportionally to weight among the rest, and so on. So the sample has the distribution of successive weighted draws without replacement. Note what this does not say: the inclusion probability of an item is not in general (that can exceed 1), and no simple formula gives it.
In practice the keys are stored as , which preserves the order and avoids underflow when weights are large. The program checks both claims for weights , comparing measured frequencies with the exact probabilities of successive weighted draws.
import heapq, math, random
from collections import Counter
from fractions import Fraction
from itertools import permutations
def es_sample(items, k, rng):
"""Efraimidis-Spirakis A-Res: keep the k largest keys u^(1/w), stored as log(u)/w."""
heap = [] # min-heap of (key, item)
for x, w in items:
key = math.log(1.0 - rng.random()) / w # log of u^(1/w), u in (0, 1]
if len(heap) < k:
heapq.heappush(heap, (key, x))
elif key > heap[0][0]:
heapq.heapreplace(heap, (key, x))
return frozenset(x for _, x in heap)
items = [("a", 1), ("b", 2), ("c", 3), ("d", 4)]
W = {x: w for x, w in items}
def successive(S): # exact: draw without replacement, proportional to weight
total = Fraction(0)
for order in permutations(S):
p, left = Fraction(1), sum(W.values())
for x in order:
p *= Fraction(W[x], left)
left -= W[x]
total += p
return total
rng = random.Random(2006)
runs = 60000
for k in [1, 2]:
cnt = Counter(es_sample(items, k, rng) for _ in range(runs))
print(f"k = {k}: sample measured exact (successive weighted draws)")
for S in sorted(cnt, key=sorted):
print(f" {''.join(sorted(S)):6} {cnt[S] / runs:8.4f} {float(successive(S)):.4f}")k = 1: sample measured exact (successive weighted draws)
a 0.1001 0.1000
b 0.1998 0.2000
c 0.3020 0.3000
d 0.3981 0.4000
k = 2: sample measured exact (successive weighted draws)
ab 0.0471 0.0472
ac 0.0763 0.0762
ad 0.1122 0.1111
bc 0.1582 0.1607
bd 0.2351 0.2333
cd 0.3711 0.3714
With 60 000 runs the measured frequencies agree with the exact ones to within about , the sampling noise.
The algorithm needs words and time per item for the heap. Like Algorithm L for the uniform case, a variant with exponential jumps (A-ExpJ in the same paper) draws how much weight to skip before the next insertion, so random numbers are spent only on insertions, about of them for items of similar weight; the details are in the paper.
In C++
The same sampler with std::priority_queue as the min-heap, keys stored as , used to sample 5 of 10 000 items whose weight is . Each weight class should account for a share of the sample close to its share of the total weight (for much smaller than the number of items, successive draws are nearly independent), which the program measures over 4 000 runs.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <functional>
#include <queue>
#include <random>
#include <utility>
#include <vector>
// Weighted reservoir: keep the k items with the largest keys log(u)/w.
std::vector<int> es_sample(int n, int k, std::mt19937_64& rng) {
using Entry = std::pair<double, int>;
std::priority_queue<Entry, std::vector<Entry>, std::greater<>> heap; // smallest key on top
for (int t = 0; t < n; ++t) {
double w = 1 + t % 10;
double u = (rng() >> 11) * 0x1.0p-53 + 0x1.0p-54; // uniform in (0, 1)
double key = std::log(u) / w;
if ((int)heap.size() < k) heap.emplace(key, t);
else if (key > heap.top().first) { heap.pop(); heap.emplace(key, t); }
}
std::vector<int> out;
while (!heap.empty()) { out.push_back(heap.top().second); heap.pop(); }
return out;
}
int main() {
std::mt19937_64 rng(2006);
const int n = 10000, k = 5, runs = 4000;
std::vector<int> cls(10, 0);
for (int r = 0; r < runs; ++r)
for (int t : es_sample(n, k, rng)) ++cls[t % 10];
std::printf("weight share of the sample share of the weight\n");
for (int c = 0; c < 10; ++c)
std::printf("%6d %19.4f %19.4f\n", c + 1, cls[c] / double(runs * k), (c + 1) / 55.0);
}weight share of the sample share of the weight
1 0.0183 0.0182
2 0.0355 0.0364
3 0.0537 0.0545
4 0.0720 0.0727
5 0.0921 0.0909
6 0.1060 0.1091
7 0.1300 0.1273
8 0.1446 0.1455
9 0.1661 0.1636
10 0.1817 0.1818
Priority sampling: estimating subset sums
A frequent question about a weighted stream is "what is the total weight of the items with property ?", where is chosen after the stream has passed (the bytes sent to one country, the revenue of one product line). A uniform sample estimates such sums badly when weights are heavy-tailed: a few huge items dominate, and a uniform sample usually misses them. Priority sampling (Duffield, Lund and Thorup, 2007) keeps the heavy items for sure and the light ones in proportion to their weight.
- Give item the priority with uniform in , and keep the items of largest priority.
- Let be the -st largest priority. Each of the top items gets the adjusted weight ; all other items get .
Theorem (Duffield, Lund and Thorup, 2007). for every item, so for any subset , is an unbiased estimate of . Moreover the have zero covariance, so the variance of a subset estimate is the sum of the individual variances.
Why it is unbiased (sketch)
Fix item and condition on all the other . Then the -th largest priority among the other items is a fixed number . Item is kept exactly when , that is , and in that case the threshold equals . So . If this is ; otherwise it is . Removing the conditioning gives . The zero-covariance statement needs a longer argument and is stated here.
The program draws 20 000 flows with heavy-tailed sizes (a Pareto-like law with a very long tail), keeps of them, and estimates three subset sums with five independent samples.
import heapq, random
def priority_sample(flows, k, rng):
"""Keep the k+1 largest priorities w/u; the smallest of them is the threshold tau."""
heap = []
for fid, w in flows:
q = w / (1.0 - rng.random())
if len(heap) < k + 1:
heapq.heappush(heap, (q, fid, w))
elif q > heap[0][0]:
heapq.heapreplace(heap, (q, fid, w))
tau = heap[0][0]
return [(fid, max(w, tau)) for q, fid, w in heap[1:]] # k items with adjusted weights
gen = random.Random(42)
flows = [(i, int(100 * (1.0 - gen.random()) ** -1.2)) for i in range(20000)] # heavy-tailed sizes
subsets = {"all flows": lambda i: True, "id % 10 == 3": lambda i: i % 10 == 3,
"id < 500": lambda i: i < 500}
print("k = 200 of 20000 flows; relative errors of 5 independent samples")
for name, pred in subsets.items():
exact = sum(w for i, w in flows if pred(i))
ests = []
for seed in range(5):
S = priority_sample(flows, 200, random.Random(seed))
ests.append(sum(w for i, w in S if pred(i)))
print(f"{name:13} exact {exact:9} estimates " + " ".join(f"{e / exact - 1:+6.1%}" for e in ests))k = 200 of 20000 flows; relative errors of 5 independent samples
all flows exact 54232040 estimates +3.5% +2.3% -1.6% +1.5% -0.9%
id % 10 == 3 exact 3152013 estimates -2.6% +0.6% -10.1% +33.6% -32.4%
id < 500 exact 1635953 estimates +19.6% -11.0% +21.1% +16.7% -13.6%
The total is estimated within a few per cent from 1% of the flows. Smaller subsets are harder, as they must be: a subset holding or of the flows is represented by only a handful of sampled items, so the relative error grows roughly like . The estimates scatter on both sides of the truth, as unbiasedness promises. Szegedy (2006) proved that priority sampling is near-optimal: with samples its total variance is no larger than that of any unbiased scheme with samples.
Test yourself
In the Efraimidis-Spirakis sampler, which key does an item of weight get?
- , and the sample keeps the largest keys
- , and the sample keeps the largest keys
- , and the sample keeps the smallest keys
For , what is the distribution of the Efraimidis-Spirakis sample?
- Each item is included with probability exactly
- That of successive draws without replacement, each proportional to weight among the remaining items
- Uniform over all -subsets
- Independent inclusion with probability
In priority sampling, what adjusted weight does a sampled item of weight get, if is the -st largest priority?