TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Weighted Sampling: Efraimidis-Spirakis

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 tt, arriving with weight wt>0w_t > 0, is chosen with probability proportional to wtw_t. 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 kk smallest (equivalently, largest) uniform random keys. For weights, draw utu_t uniform in (0,1)(0, 1) and use the key

κt=ut1/wt.\kappa_t = u_t^{1/w_t} .

A heavier item raises its uniform number to a smaller power, which pushes the key towards 1.

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

Theorem. For k=1k = 1, item ii ends up as the sample with probability wi/∑jwjw_i / \sum_j w_j.

Proof. Pr⁡[κi≤x]=Pr⁡[ui≤xwi]=xwi\Pr[\kappa_i \le x] = \Pr[u_i \le x^{w_i}] = x^{w_i} for x∈[0,1]x \in [0, 1], so κi\kappa_i has density wixwi−1w_i x^{w_i - 1}. The maximum of the other keys is at most xx with probability ∏j≠ixwj=xW−wi\prod_{j \ne i} x^{w_j} = x^{W - w_i}, where W=∑jwjW = \sum_j w_j. Hence

Pr⁡[κi is the largest]=∫01wixwi−1⋅xW−wi dx=wi∫01xW−1 dx=wiW.□\Pr[\kappa_i \text{ is the largest}] = \int_0^1 w_i x^{w_i - 1} \cdot x^{W - w_i} \, dx = w_i \int_0^1 x^{W - 1}\, dx = \frac{w_i}{W} . \qquad \square

For k>1k > 1, 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 kk successive weighted draws without replacement. Note what this does not say: the inclusion probability of an item is not kwi/Wk w_i/W in general (that can exceed 1), and no simple formula gives it.

In practice the keys are stored as ln⁡κt=(ln⁡ut)/wt\ln \kappa_t = (\ln u_t)/w_t, which preserves the order and avoids underflow when weights are large. The program checks both claims for weights 1,2,3,41, 2, 3, 4, comparing measured frequencies with the exact probabilities of successive weighted draws.

python · try it yourself
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 ±0.003\pm 0.003, the sampling noise.

The algorithm needs O(k)O(k) words and O(log⁡k)O(\log k) 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 O(klog⁡(n/k))O(k \log(n/k)) of them for nn 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 (ln⁡u)/w(\ln u)/w, used to sample 5 of 10 000 items whose weight is 1+(t mod 10)1 + (t \bmod 10). Each weight class should account for a share of the sample close to its share of the total weight (for kk much smaller than the number of items, successive draws are nearly independent), which the program measures over 4 000 runs.

cpp · try it yourself
#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 PP?", where PP 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 ii the priority qi=wi/uiq_i = w_i / u_i with uiu_i uniform in (0,1](0, 1], and keep the k+1k + 1 items of largest priority.
  • Let τ\tau be the (k+1)(k+1)-st largest priority. Each of the kk top items gets the adjusted weight w^i=max⁡(wi,τ)\hat w_i = \max(w_i, \tau); all other items get w^i=0\hat w_i = 0.

Theorem (Duffield, Lund and Thorup, 2007). E[w^i]=wi\mathbb{E}[\hat w_i] = w_i for every item, so for any subset II, ∑i∈Iw^i\sum_{i \in I} \hat w_i is an unbiased estimate of ∑i∈Iwi\sum_{i \in I} w_i. Moreover the w^i\hat w_i have zero covariance, so the variance of a subset estimate is the sum of the individual variances.

Why it is unbiased (sketch)

Fix item ii and condition on all the other uju_j. Then the kk-th largest priority among the other items is a fixed number τ′\tau'. Item ii is kept exactly when qi>τ′q_i > \tau', that is ui<wi/τ′u_i < w_i/\tau', and in that case the threshold τ\tau equals τ′\tau'. So E[w^i∣others]=Pr⁡[ui<wi/τ′]⋅max⁡(wi,τ′)\mathbb{E}[\hat w_i \mid \text{others}] = \Pr[u_i < w_i/\tau'] \cdot \max(w_i, \tau'). If wi≥τ′w_i \ge \tau' this is 1⋅wi1 \cdot w_i; otherwise it is wiτ′⋅τ′=wi\frac{w_i}{\tau'} \cdot \tau' = w_i. Removing the conditioning gives E[w^i]=wi\mathbb{E}[\hat w_i] = w_i. 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 k=200k = 200 of them, and estimates three subset sums with five independent samples.

python · try it yourself
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 110\frac{1}{10} or 140\frac{1}{40} of the flows is represented by only a handful of sampled items, so the relative error grows roughly like 1/number of sampled members1/\sqrt{\text{number of sampled members}}. The estimates scatter on both sides of the truth, as unbiasedness promises. Szegedy (2006) proved that priority sampling is near-optimal: with k+1k + 1 samples its total variance is no larger than that of any unbiased scheme with kk samples.

Test yourself

In the Efraimidis-Spirakis sampler, which key does an item of weight ww get?

  1. w⋅uw \cdot u
  2. u1/wu^{1/w}, and the sample keeps the largest keys
  3. uwu^w, and the sample keeps the largest keys
  4. w/uw/u, and the sample keeps the smallest keys

For k>1k > 1, what is the distribution of the Efraimidis-Spirakis sample?

  1. Each item is included with probability exactly kwi/Wk w_i/W
  2. That of kk successive draws without replacement, each proportional to weight among the remaining items
  3. Uniform over all kk-subsets
  4. Independent inclusion with probability wi/Ww_i/W

In priority sampling, what adjusted weight does a sampled item of weight wiw_i get, if τ\tau is the (k+1)(k+1)-st largest priority?

  1. wiw_i
  2. τ\tau
  3. max⁡(wi,τ)\max(w_i, \tau)
  4. wi/τw_i/\tau