Reservoir sampling
Reservoir sampling is a family of randomized online algorithms for choosing a simple random sample, without replacement, of items from a population of unknown size in a single pass over the items. The size of the population is not known to the algorithm and is typically too large for all items to fit into main memory. The population is revealed to the algorithm over time, and the algorithm cannot look back at previous items. At any point, the current state of the algorithm must permit extraction of a simple random sample without replacement of size over the part of the population seen so far. Source: e01 Encyclopedia. Licence: CC BY-SA 4.0.
Reservoir sampling is a family of randomized online algorithms for choosing a simple random sample, without replacement, of items from a population of unknown size in a single pass over the items. The size of the population is not known to the algorithm and is typically too large for all items to fit into main memory. The population is revealed to the algorithm over time, and the algorithm cannot look back at previous items. At any point, the current state of the algorithm must permit extraction of a simple random sample without replacement of size over the part of the population seen so far. The proof is by induction on the number of items n . If there is 1 item we always choose it and we are done. If there are already n items, then the probability of one of the items already in the store remaining the store becomes \frac{n}{n + 1} \times \frac{1}{n} = \frac{1}{n + 1} so the probability of any of the n + 1 items remaining in the sample is now \frac{1}{n + 1}. The proof of correctness for the general algorithm where we have an arbitrary number of slots is an extension of this argument. For each new input x_i , generate a random number uniformly in \{1, ..., i\} . If j \in \{1,..., k\} , then set R[j] := x_i. Otherwise, discard x_i . Return R after all inputs are processed. For each new u_{i+1} , compare it with u_{w_i} . If u_{i+1} , then discard u_{w_i} , store u_{i+1} , and set w_{i+1} to be the index of the largest among them. Otherwise, discard u_{i+1} , and set w_{i+1} = w_i . Now couple this with the stream of inputs x_1, ..., x_n . Every time some u_i is accepted, store the corresponding x_i . Every time some u_i is discarded, discard the corresponding x_i . This algorithm still needs O(n) random numbers, thus taking O(n) time. However, it can be improved by observing that after each step, the number of following items which will be skipped by the algorithm follows a geometric distribution with parameter u_{w_i} . Thus, the sampling algorithm can simply generate a sample from this distribution to determine how many items to skip over, rather than examining them one at a time. A further simplification is to store only the maximum value u_{w_i} at each point, and avoid storing u_1, \ldots, u_i . This results in Algorithm L, which is implemented as follows: // S has items to sample, R will contain the result ReservoirSample(S[1..n], R[1..k]) // fill the reservoir array with the first k items for i = 1 to k R[i] := S[i] end // random() generates a uniform (0,1) random number W := exp(log(random())/k) while i This algorithm computes three random numbers for each item that becomes part of the reservoir, and does not spend any time on items that do not. Its expected running time is O(k (1+\log(n/k))) , which is optimal. n' = \left\lfloor \frac{n}{q} \right\rfloor + 1. This gives a particularly simple algorithm: if stream is empty return no sample sample := first item n := 1 loop q := random() // uniform in (0,1) n := floor(n / q) + 1 advance stream to 1-based item n if stream is exhausted break sample := item n return sample Here denotes a uniform random value strictly between 0 and 1. An implementation whose random-number generator can return an endpoint must exclude or resample such values. The variable is the absolute 1-based position in the stream, rather than a count of items to skip. The algorithm therefore generates replacement positions directly instead of making a random replacement decision for every input item. For a reservoir of size one, each new replacement position requires only one random variate. By comparison, Algorithm L normally uses three. When Algorithm L is specialized to , choosing the reservoir slot requires no randomness, leaving two nontrivial random variates per replacement. A weighted generalization was later given by Meligrana and Fazzone. For a single-item weighted reservoir with current cumulative weight , the cumulative-weight threshold for the next replacement is \frac{W}{q}, where is uniform on . The stream is scanned until its cumulative weight reaches that threshold. (* S is a stream of items to sample S.Current returns current item in stream S.Next advances stream to next position min-priority-queue supports: Count -> number of items in priority queue Minimum -> returns minimum key value of all items Extract-Min() -> Remove the item with minimum key Insert(key, Item) -> Adds item with specified key *) ReservoirSample(S[1..?]) H := new min-priority-queue while S has data r := random() // uniformly random between 0 and 1, exclusive if H.Count H.Minimum H.Extract-Min() H.Insert(r, S.Current) end S.Next end return items in H end The expected running time of this algorithm is O(n + k \log k \log(n/k)) and it is relevant mainly because it can easily be extended to items with weights. The probability of each item to be included in the random sample is proportional to its relative weight, i.e., w_i / W . It is not achievable when k=n , since each item is then included with probability 1. The following algorithm was given by Efraimidis and Spirakis that uses interpretation 1: (* S is a stream of items to sample S.Current returns current item in stream S.Weight returns weight of current item in stream S.Next advances stream to next position The power operator is represented by ^ min-priority-queue supports: Count -> number of items in priority queue Minimum() -> returns minimum key value of all items Extract-Min() -> Remove the item with minimum key Insert(key, Item) -> Adds item with specified key *) ReservoirSample(S[1..?]) H := new min-priority-queue while S has data r := random() ^ (1/S.Weight) // random() produces a uniformly random number in (0,1) if H.Count H.Minimum H.Extract-Min() H.Insert(r, S.Current) end end S.Next end return items in H end This algorithm is identical to the algorithm given in Reservoir Sampling with Random Sort except for the generation of the items' keys. The algorithm is equivalent to assigning each item a key r^{1/w_i} where is the random number and then selecting the items with the largest keys. Equivalently, a more numerically stable formulation of this algorithm computes the keys as -\ln(r)/w_i and select the items with the smallest keys. (* S is a stream of items to sample S.Current returns current item in stream S.Weight returns weight of current item in stream S.Next advances stream to next position The power operator is represented by ^ min-priority-queue supports: Count -> number of items in the priority queue Minimum -> minimum key of any item in the priority queue Extract-Min() -> Remove the item with minimum key Insert(Key, Item) -> Adds item with specified key *) ReservoirSampleWithJumps(S[1..?]) H := new min-priority-queue while S has data and H.Count This algorithm follows the same mathematical properties that are used in A-Res, but instead of calculating the key for each item and checking whether that item should be inserted or not, it calculates an exponential jump to the next item which will be inserted. This avoids having to create random variates for each item, which may be expensive. The number of random variates required is reduced from O(n) to O(k \log (n/k)) in expectation, where k is the reservoir size, and n is the number of items in the stream. Following algorithm was given by M. T. Chao uses interpretation 2: and Tillé (2006). (* S has items to sample, R will contain the result S[i].Weight contains weight for each item *) WeightedReservoir-Chao(S[1..n], R[1..k]) WSum := 0 // fill the reservoir array for i := 1 to k R[i] := S[i] WSum := WSum + S[i].Weight end for i := k+1 to n WSum := WSum + S[i].Weight p := S[i].Weight / WSum // probability for this item j := random(); // uniformly random between 0 and 1 if j For each item, its relative weight is calculated and used to randomly decide if the item will be added into the reservoir. If the item is selected, then one of the existing items of the reservoir is uniformly selected and replaced with the new item. The trick here is that, if the probabilities of all items in the reservoir are already proportional to their weights, then by selecting uniformly which item to replace, the probabilities of all items remain proportional to their weight after the replacement. Note that Chao doesn't specify how to sample the first k elements. He simple assumes we have some other way of picking them in proportion to their weight. Chao: "Assume that we have a sampling plan of fixed size with respect to S_k at time A; such that its first-order inclusion probability of X_t is π(k; i)". (* S has items to sample, R will contain the result S[i].Weight contains weight for each item *) WeightedReservoir-Chao(S[1..n], R[1..k]) WSum := 0 // fill the reservoir array for i := 1 to k R[i] := S[i] WSum := WSum + S[i].Weight end j := random() // uniformly random between 0 and 1 pNone := 1 // probability that no item has been selected so far (in this jump) for i := k+1 to n WSum := WSum + S[i].Weight p := S[i].Weight / WSum // probability for this item j -= p * pNone pNone := pNone * (1 - p) if j KLRS(Stream, BufferSize M, TargetDistribution) Input: * Stream (data points (x, y) arriving sequentially) * BufferSize M * TargetDistribution (desired class distribution in the buffer) Output: Updated buffer maintaining the target distribution Initialize buffer M with the first M data points from the stream. For t = M+1 to ∞: - Update stream counters to compute n_{t+1}. - Compute target distribution p_{t+1}. - For each class k in the buffer: - Simulate removing one instance of class k and adding (x_t, y_t). - Compute KL divergence v_k between p_{t+1} and the modified buffer distribution. - Select the class k* with the minimum v_k. - If k* = y_t: - Generate random number r in [1, n_{t+1}, y_t]. - If r ≤ m_{t, y_t}, - replace a random instance of class y_t in the buffer with (x_t, y_t). - Else, replace a random instance of the selected class k* in the buffer with (x_t, y_t). - Update buffer counters m_{t+1]. - Update class set C_{t+1} := unique(C_t ∪ {y_t}). Reservoir sampling makes the assumption that the desired sample fits into main memory, often implying that is a constant independent of . In applications where we would like to select a large subset of the input list (say a third, i.e. k=n/3 ), other methods need to be adopted. Distributed implementations for this problem have been proposed. ==References==
Cite this
"Reservoir sampling". 1790397066. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1376791008 JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy