{"id":248,"date":"2026-11-13T12:35:50","date_gmt":"2026-11-13T04:35:50","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-reservoir-sampling-keeps-a-uniform-subset\/"},"modified":"2026-11-13T21:53:39","modified_gmt":"2026-11-13T13:53:39","slug":"how-reservoir-sampling-keeps-a-uniform-subset","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-reservoir-sampling-keeps-a-uniform-subset\/","title":{"rendered":"How reservoir sampling keeps a uniform subset"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Reservoir sampling<\/strong> draws k items uniformly from a stream of unknown length. The first k items fill the reservoir. When item i arrives, with i counted from 1, it replaces a random reservoir slot with probability <strong>k\/i<\/strong>. Algorithm R uses one random number per item and <strong>O(k)<\/strong> memory. At every prefix of the stream, the reservoir is a uniformly random subset of the items seen so far.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">If the stream length n were known, each item could be kept with an inclusion decision in a combination. The length is not known, and the stream may not be rewound. The invariant that saves the algorithm is stronger than the final distribution: after i items, every subset of size k is equally likely. The replacement probability k\/i is exactly what maintains that invariant when item i is considered.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A naive policy that keeps each item with probability k\/n cannot be run without n. A policy that always keeps the first k items ignores the tail.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">After n items the reservoir is equally likely to be any k-subset, provided each random test is independent and uniform. Time is \u0398(n) and memory is \u0398(k), which does not grow with n. The algorithm sees each item once. Weighted reservoir sampling, where items have unequal probabilities, is a different formula. Algorithm R is the unweighted subset.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The index arithmetic is the usual off-by-one hazard. If i starts at 0, the probability k\/i is nonsense on the first item. Count i from 1, or use the equivalent test with a zero-based count of items already seen.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Put the first k items into the reservoir. If the stream ends earlier, the reservoir is the whole stream.<\/li>\n<li>For each later item, let i be its 1-based index. With probability k\/i, replace a uniformly chosen reservoir slot by this item. Otherwise discard it.<\/li>\n<li>Continue until the stream ends. Do not rewind.<\/li>\n<li>The proof invariant is that every k-subset of the first i items is equally likely. The probability k\/i is the one that preserves it.<\/li>\n<li>For a sample of size 1, the rule reduces to replacing the stored item with probability 1\/i.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">Uniformity is over subsets of the items seen so far, unweighted. A weighted stream, a sliding window, or a sample that must be stable under deletions needs a different algorithm. Fisher-Yates permutes an array that is already in memory and can then take a prefix. The reservoir is what remains when the array does not fit or has not ended.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when every new item replaces a slot with probability k over n<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Use probability k\/n before the stream ends<\/td>\n<td>n is unknown. Using the current length is the algorithm. Using a guessed n biases the sample toward the head or the tail.<\/td>\n<\/tr>\n<tr>\n<td>Always replace a random slot<\/td>\n<td>Late items then dominate. The replacement probability has to fall as 1\/i.<\/td>\n<\/tr>\n<tr>\n<td>Keep the first k items and ignore the rest<\/td>\n<td>The sample is deterministic and misses every subset that intersects the tail.<\/td>\n<\/tr>\n<tr>\n<td>Count i from 0 and divide by i<\/td>\n<td>The first probability is undefined. The 1-based index, or an equivalent formulation, is part of the invariant.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A uniform permutation of a finite array is Fisher-Yates. A weighted sample is a different reservoir formula. Algorithm R is the unweighted stream subset of size k.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment keeps a reservoir of size 2. At 1-based index i an arriving item replaces one stored item with probability 2\/i. The seeded sample is a 2-subset. A second loop checks that, across trials, no item is starved. It prints the one sample <code>2 4<\/code>.<\/p>\n\n<pre><code class=\"language-python\">import random\n\ndef sample(rng, stream, k):\n    reservoir = []\n    for i, item in enumerate(stream, 1):\n        if len(reservoir) &lt; k:\n            reservoir.append(item)\n        elif rng.randrange(i) &lt; k:\n            reservoir[rng.randrange(k)] = item\n    return reservoir\n\none = sample(random.Random(1), [0, 1, 2, 3, 4], 2)\nassert len(one) == 2 and len(set(one)) == 2\ncounts = [0] * 5\nfor t in range(3000):\n    for item in sample(random.Random(t), [0, 1, 2, 3, 4], 2):\n        counts[item] += 1\nassert all(abs(c - 1200) &lt; 200 for c in counts)\nprint(*one)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Reservoir sampling keeps a uniform sample of a log or a query stream in one pass, when the length is not known in advance. Spark-style stream samples use that reservoir. A sample that first counts the records needs a second pass.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop a two-pass method when the stream cannot be rewound. Keep algorithm R, with probability k\/i at the i-th item.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for reservoir sampling returns the replacement probability k\/i and the invariant that every prefix stays uniform. <strong>Reservoir sampling keeps a uniform k-subset of a stream by replacing a stored item with probability k\/i when the i-th item arrives.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Reservoir sampling draws k items uniformly from a stream of unknown length. The first k items fill the reservoir. When item i arrives, with i counted from 1, it replaces a random reservoir slot with probability k\/i. Algorithm R uses one random number per item and O(k)&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,52],"tags":[],"class_list":["post-248","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-randomization"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/248","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=248"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/248\/revisions"}],"predecessor-version":[{"id":647,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/248\/revisions\/647"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=248"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=248"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=248"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}