News for hackers. Stuff that matters.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eridius on Friday March 06, 2015 @01:25PM (#9158576)
This algorithm was introduced with the premise

> "I have a database table with #{17.kajillion} records, and I want to take a random sample of #{X} of them. How can I do this efficently?"

And goes on to say that something like `YourBigTable.all.sample(X)` is bad in time and space. And the link that explains why doing `ORDER BY RANDOM()` is bad lists one reason being that generation of random numbers is relatively expensive.

But these problems aren't solved by reservoir sampling. Reservoir sampling is still O(N), and it requires generating a random number for every element. It still beats `ORDER BY RANDOM()` because it doesn't have to sort the numbers (or even keep them all in memory at the same time). But that doesn't make it a good choice.

More generally, reservoir sampling is appropriate when you don't know the size of the set beforehand. But in the premise, we do know the size of the set. And if you know the size of the set (and have some way to address arbitrary elements), then randomly generating a set of X indices is going to be much simpler and faster. Yeah, you have to deal with duplicate indices, but that's an easy problem to solve.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by cperciva on Saturday March 07, 2015 @12:10AM (#9161072)
one reason being that generation of random numbers is relatively expensive

Say again? My laptop can read from /dev/urandom at over 1 Gbps. If you're running in userland on modern hardware you can easily hit 10 Gbps.

Seeding is hard, but once you've done that, generating random numbers is insanely cheap.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eridius on Saturday March 07, 2015 @01:04AM (#9161182)
Yeah, I dunno why it says generating random numbers is expensive. I was just quoting his linked source.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by jamiesonbecker on Saturday March 07, 2015 @10:06AM (#9161932)
> Seeding is hard, but once you've done that, generating random numbers is insanely cheap.

Depends on your use case. Generating random numbers is indeed relatively expensive:

    $ time dd if=/dev/zero of=/dev/null bs=1024 count=1M
    1073741824 bytes (1.1 GB) copied, 0.348118 s, 3.1 GB/s
    real    0m0.350s
    user    0m0.092s
    sys     0m0.260s

    $ time dd if=/dev/urandom of=/dev/null bs=1024 count=1M
    1073741824 bytes (1.1 GB) copied, 102.332 s, 10.5 MB/s
    real    1m42.334s
    user    0m0.152s
    sys     1m41.994s
(I7, 3.2.0-4-amd64)
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by IgorPartola on Saturday March 07, 2015 @02:11PM (#9162737)
You are comparing doing nearly nothing vs an PRNG. Presumably, you would spend your computation cycles doing something more useful than generating zeros, at which point I am not certain the difference would be quite so drastic.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by cperciva on Saturday March 07, 2015 @06:42PM (#9163619)
Your /dev/urandom is astonishingly slow. Is this normal for Linux?
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by SamReidHughes on Sunday March 08, 2015 @10:47AM (#9165711)
Yes. For example, if you choose the encrypted hard drive option when installing Debian, it'll take forever, like, hours and hours, two digit numbers of hours, because it's reading from some /dev/urandom (I presume) to initialize the drive with random data. You can skip that step though. It's way better to do it beforehand using some script that uses something other than /dev/urandom. And maybe, don't put a 1 TB hard drive in a netbook or an older machine.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by jamiesonbecker on Tuesday March 10, 2015 @02:41PM (#9179703)
btw, your sly remark wasn't lost .. ;)

(fyi, Dr. Colin Percival is an eminent security developer for FreeBSD, author and CEO of the trusted Tarsnap, and developer of the AWS AMI's for FreeBSD; when he takes a whack at Linux's PRNG, he's got some standing to do it from :).)

But, yep, this is normal for Linux.. although, frankly, I'm just glad that we, like FreeBSD, are not taking rdrand at face value (thx Ted T'so!) Perhaps post-seed performance will improve down the road.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by cperciva on Tuesday March 10, 2015 @06:05PM (#9180993)
I wasn't talking about RDRAND. I can't remember what throughput it gives, and it's a pain to use "live" in that it's allowed to fail and return all zeroes.

The inner loop of a PRNG microbenchmark should be identical to the inner loop of an AES-CTR microbenchmark (or your favourite block cipher or MAC if you prefer a different one) and those are fast these days.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by detrino on Friday March 06, 2015 @01:48PM (#9158706)
> But these problems aren't solved by reservoir sampling. Reservoir sampling is still O(N), and it requires generating a random number for every element.

I had the same thought reading this. This solution is only really suitable if the number of elements to select is within some constant of the total number of elements.

> More generally, reservoir sampling is appropriate when you don't know the size of the set beforehand. But in the premise, we do know the size of the set. And if you know the size of the set (and have some way to address arbitrary elements), then randomly generating a set of X indices is going to be much simpler and faster. Yeah, you have to deal with duplicate indices, but that's an easy problem to solve.

Last time I had to solve this, I came up with the following solution[1] which doesn't generate any duplicates and runs in O(k) where k is the size of result set.

[1] http://ideone.com/CAwuxW

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by timr on Friday March 06, 2015 @02:01PM (#9158802)
As I said on another comment in this thread: if you have the addresses (i.e. database ID values) for all of your records in memory, then sure, sampling directly from that set is faster than iterating over every record in a table.

There are lots of cases where this assumption doesn't hold: if you're sampling from a join, or from a table with non-contiguous ID values, for example.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by azernik on Saturday March 07, 2015 @02:34AM (#9161322)
Or, even better, if you're sampling from a data set as it's being generated. For example, let's say you want to grab 1,000 random tweets out of the output of Twitter's firehose for the next 2 hours - when you decide whether to keep tweet #1,329, you have no idea how many tweets are going to come in after that one, because they haven't been written yet!
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by joe_the_user on Friday March 06, 2015 @02:31PM (#9159013)
Another way to put it is that reservoir sampling only makes sense if you have to iterate over the entire table regardless. That means, no keys, row numbers or unique values that can chosen at random and found more quickly.

It seems less, not more, likely that this kind of situation would exist in a huge table - what use would such a table be if you could only process it sequentially?

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by defen on Friday March 06, 2015 @02:46PM (#9159114)
Ignore the database part - that's just a single concrete example. More abstractly, say you're receiving a continuous stream of events, and you don't know when it will end, and you want to take n samples from that. For example, maybe you have a web service that is receiving click event logs as a stream, and you want to sample 1000 of those, randomly, without storing every single one as it comes in.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by skybrian on Friday March 06, 2015 @05:51PM (#9160105)
On the other hand, you're likely to be taking a sample of rows that match a query. It's unlikely that the database already keeps track of the count of how many rows will match an arbitrary query, unless you set it up in advance. So you'd need to load the row ids of the matching rows, then sample from them.

A sufficiently smart database might understand "order by rand() limit n" and do reservoir sampling on row id's behind the scenes. I wouldn't count on it, though.

If you set it up in advance, you could also use reservoir sampling to avoid even storing all the data in the first place, while still saving a random sample.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by twic on Saturday March 07, 2015 @09:47AM (#9161897)
Once-through sequential processing is a pretty common paradigm for large datasets. That's basically what Hadoop and column stores are about.

In fact, i think this is the underlying meme of 'big data' - that it's now plausible and useful to do analysis over all of a large dataset, so you might as well build everything around iterating over the entire table regardless.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by detrino on Friday March 06, 2015 @02:14PM (#9158903)
You can still use this approach as long as you know the total size upfront, just sort the generated index array and use it to skip elements from your input stream, this will save you from having to generate random numbers for every element.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by bosie on Friday March 06, 2015 @06:49PM (#9160302)
Could you please expand on your linked code, not really a C++ programmer and line 22/25 confuse me a bit?

Unfortunately I don't understand how each element has the same probability of being chosen. I.e. the first element seems to have a probability of 1/n, while the second has 1/n + 1/(n-1) etc. Am i wrong about this?

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by sebleblanc on Friday March 06, 2015 @09:45PM (#9160751)
Regarding the C++ code:

    /* This is standard modern C++ random number generation.
       It means, using the random generator "engine", return 
       a number according to distribution "dist". In this
       "dist" is a uniform distribution from "i" to "max-min".
       "auto" is the new way to type variables in C++: it
       infers the type of the variable from the type of the
       expression */
    22: auto index = dist(engine);

    /* The following lines are a bit more complex, as they
       contain a nested expression. Let us focus on the inner
       expression:
           (index < size ) ? array[index]
              : map.insert({index, min + index}).first->second

       This is in the form:
           test-expr ? when-true-expr
              : when-false-expr

       This expression is a ternary condition. What it means
       is that the expression before the question mark is
       computed (index < size), and if it evaluates to true,
       the overall expression will resolve to the result of
       the expression between the question mark and the colon,
       otherwise it resolves to what is after the colon.

       Here, it means that if "index" is smaller than "size",
       use "array[index]", otherwise insert a new entry in the
       map, with key "index" and value "min+index", then reuse
       the result of the operation by accessing member "second"
       of the member "first". I am not familiar with STL maps;
       here is an explanation of the map::insert method from
       cplusplus.com:

           The single element versions (1) return a pair, with
           its member pair::first set to an iterator pointing 
           to either the newly inserted element or to the 
           element with an equivalent key in the map. The 
           pair::second element in the pair is set to true if 
           a new element was inserted or false if an equivalent
           key already existed.
    */

    23: std::swap(array[i], index < size
    24:                         ? array[index]
    25:                         : map.insert({index, min + index}).first->second);

    /* Then, the std::swap operation simply swaps the two indicated
       values in the array. */
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by detrino on Friday March 06, 2015 @10:46PM (#9160904)
> Could you please expand on your linked code, not really a C++ programmer and line 22/25 confuse me a bit?

I've annotated the program here: http://ideone.com/gmaBri

> Unfortunately I don't understand how each element has the same probability of being chosen. I.e. the first element seems to have a probability of 1/n, while the second has 1/n + 1/(n-1) etc. Am i wrong about this?

This is just a partial Fisher-Yates shuffle[1] using a sparse sequence instead of an array. Keep in mind that if an element is not chosen it is swapped with the chosen element and will be considered again. I think the best way to think about it is that you are choosing a random element from the set and then "removing" it from the set with the swap and then repeating.

[1] http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Th...

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by timr on Friday March 06, 2015 @01:31PM (#9158613)
Author here.

Yes, reservoir sampling is O(N), but my point there was that it doesn't require instantiating every record at once. Also, the cost of the random number generation isn't the big deal in an ORDER BY RANDOM() implementation -- it's that even the smart implementations end up doing multiple table scans. So even at O(n) this probably beats most implementations of that approach, in practice.

Reservoir sampling is appropriate with more than just a set of unknown size -- you very frequently know the size of a set, but it's still too big to sample directly. But yes, if your sets are small, you have a lot of options.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by Retric on Friday March 06, 2015 @01:58PM (#9158774)
While good in theory, it's often really slow in practice as even small sample sets can trash your cache and it still needs a random number for every element.

You can make a better approach using a much longer list, but then the math is far less elegant. EX: Add the first X * N elements to the list. Then remove 1/X of them. Then 1/X of the times add an element to the list until it’s full. Cull 1/X of them and then add new elements (1/X)^2 of the time. Repeat until you run out of elements at which point you cull the list back to X elements.

Downside is your generating ~N log N random numbers so scanning the list and then sorting a random set may be faster.

If you have an approximate number elements AND want a small percentage of them then randomly generate X * N element list which is then culled to an N element list.

Finally, if N happens to be close to the full number of elements you’re better off creating an exclusion list.

PS: Reservoir Sampling is only good if your memory constrained, need a constant time algorithm, and generating random numbers is expensive.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eridius on Friday March 06, 2015 @02:38PM (#9159064)
If you know the size of the set, then you can generate a random set of (non-duplicate) indices, and use those to fetch data.

Offhand I'm not sure how to do that in SQL, since data isn't usually fetched by index (unless the row has an explicit index key). Worst-case you could iterate over the rows just as you do with reservoir sampling, and it would still be faster (since you aren't generating tons of random numbers and doing a lot of array manipulation). Or you could do one query fetching just the primary key, record the keys of the indices you're interested in, and then do a second query to fetch that set. Or maybe SQL does have some way to fetch by index after all.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by dlubarov on Friday March 06, 2015 @04:06PM (#9159568)
Yeah - unfortunately there isn't a great way to select n random rows in standard SQL.

If you have an integral primary key, you could select its max and generate random numbers up to that. Continuity isn't guaranteed so you would need to check for nonexistent primary keys in addition to checking for duplicates.

If there's no integral primary key, then there's no standard SQL solution faster than O(n).

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eridius on Friday March 06, 2015 @04:31PM (#9159685)
If N is sufficiently larger than k, it might actually be faster to do something like

  let count = query("SELECT COUNT() FROM table")
  let indices = computeIndices(count, k)
  for index in indices {
    results.append(query("SELECT * FROM table LIMIT 1 OFFSET ?", index))
  }
Yeah, you're doing a bunch of queries, but you're removing all of copying all the data from all the rows.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by dbenhur on Saturday March 07, 2015 @02:36AM (#9161324)
OFFSET j is O(j) in most RDMSes. You made an o(N/2 * k) algorithm given j is a random number in [0,N).
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eridius on Saturday March 07, 2015 @08:02PM (#9163935)
Depending on the size of k compared to N, and how much data is in each row, it's still probably better than iterating over the entire contents of the table.

Also, do you have any citation for OFFSET j being O(j)? I can believe that's the case, but it also seems fairly obvious to optimize OFFSET for the case of a non-filtered unordered SELECT (or one ordered in a way that matches an index).

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by detrino on Saturday March 07, 2015 @09:06PM (#9164147)
Assuming that the DB is backed by some kind of tree, it would need to maintain extra metadata in the branches in order to achieve even O(log n) offsetting. For this reason I could understand it being a linear operation.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by seivan on Friday March 06, 2015 @04:20PM (#9159633)
My first solution would have been getting a count, maybe a cached count and just doing random between 0 and that count, fetching by index? Or if you want more than one, just get a slice? Probably not the best, but at the top of my head.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by colefichter on Friday March 06, 2015 @05:18PM (#9159954)
I might be misunderstanding something, but this seems much more complex than systematic sampling, which is well understood even in the case where the number of records (read: population size) is unknown (this situation occurs in quality control on an assembly line).

Can anyone comment on why this reservoir method would be a better choice than the old fashioned systematic sample? (which, BTW, only requires the generation of one random number to determine the starting record).

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by dthal on Friday March 06, 2015 @01:55PM (#9158757)
>>Reservoir sampling is appropriate with more than just a set of unknown size -- you very frequently know the size of a set, but it's still too big to sample directly.

I'm not sure that I buy this...Do you have an example? Still, it is a neat algorithm. And it is a true stream query algorithm, that is, if you have an open-ended stream, it maintains a random sample at all times.

[deleted]
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by timr on Friday March 06, 2015 @01:56PM (#9158760)
If you have N locations with known addresses and you can select a sample of k from those addresses randomly with uniform probability, then sure, do that.

But there are lots of situations where you don't have that: say, you're sampling from a database join, or you're just using a table that has non-contiguous id values (e.g. a table with deletions). Or, in the case of truly "Big Data", you have the data spread over multiple machines. In these cases, you need an approach suitable for when you don't know the size of the stream, you can't load it all into memory and/or you can't select randomly from an address pool.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by detrino on Friday March 06, 2015 @02:16PM (#9158917)
Sorry, I deleted this comment immediately after posting but you managed to respond to it too quickly, it originally said:

>Having a large input set of known size (and your result set is not large) is not a time when you would want to use reservoir sampling. Such a problem can be solved in O(k) where k is the size of the result set, while reservoir sampling is O(n) where n is the size of the input set.

and I have responded here: https://news.ycombinator.com/item?id=9158903

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by keithgabryelski on Friday March 06, 2015 @01:52PM (#9158730)
doesn't your implementation require you to fetch all data into the client process for ruby to iterate over?

isn't the movement of such data -- when you have billions of rows simply impossible in reasonable time?

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by timr on Friday March 06, 2015 @01:59PM (#9158781)
This implementation is useful at some scales, but not all: it uses find_each to iterate over the ActiveRecord scope, which is going to be slower than doing it all in the database (if that's possible), but still way better than instantiating every record in a large table.

(find_each instantiates a few records at a time, then throws them away)

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by keithgabryelski on Friday March 06, 2015 @02:22PM (#9158956)
it will, in general, instantiate N-n/N records (even distribution, right - N=total records, n=sample size) that is still too much data to fetch to the client for any large data set.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by timr on Friday March 06, 2015 @04:10PM (#9159587)
You don't have to instantiate the records; that's just the way I did it here. For example, you could do two passes: one to randomly select IDs, and one to fetch a small number of records for the sample set. That's O(2N), but still better than what most databases will do for an ORDER BY RANDOM() query.

There's also another, less-known variant of this algorithm that I'll go into in a future post that alleviates the concern.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by MrBuddyCasino on Friday March 06, 2015 @01:41PM (#9158665)
Thanks for the clarification, thats exactly what I was wondering about. I have two questions:

- is it a common problem to have, not knowing the set size?

- is it O(N), or rather O(n)? My intuition tells me it depends on whether or not I have to retrieve every record in the set or not, because I/O should still be much more expensive than random number generation.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by bradleyjg on Friday March 06, 2015 @02:23PM (#9158963)
Imagine you are writing software to sit on a router to:

1) collect data for some length of time, and

2) thereafter have available for querying the (maybe approximate) 25th, 50th, 95th, and 99th percentile TCP connection bandwidth thresholds, and

3) signal when a connection grows beyond the 95th percentile.

You only have a fairly limited amount of memory.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by x0x0 on Friday March 06, 2015 @10:09PM (#9160828)
While it's great for medians, reservoir sampling for calculating high or low percentiles, particularly with high dynamic range data, will probably have very high error.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by csl on Friday March 06, 2015 @01:54PM (#9158747)
> is it a common problem to have, not knowing the set size?

Yes. It could be as simple as receiving values from a Python generator (or equivalent mechanism in your favourite language), where you don't know the number of items beforehand (and querying for the length is either impossible or expensive).

In such a cases, using reservoir sampling is an elegant solution, because you're probably in a situation where you'll be iterating through all values anyway.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by bo1024 on Friday March 06, 2015 @01:48PM (#9158705)
> - is it a common problem to have, not knowing the set size?

One motivating case is when the items arrive over time, like you have a website and you want to sample uniformly from your visitors over the course of the next hour. You don't need to know how many people will arrive.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eru on Saturday March 07, 2015 @08:01AM (#9161730)
> Reservoir sampling is still O(N), and it requires generating a random number for every element.

I agree with your comment in general. Only: you can do better than generate a random number for each element. (Generate a random number to tell you how many elements in the steam to skip.)

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by alok-g on Saturday March 07, 2015 @11:25AM (#9162158)
Can you show that this will still maintain a uniform probability distribution?
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by shoegumfoot on Sunday March 08, 2015 @02:52PM (#9166654)
> Can you show that [generating a number of records to skip instead of a yes/no for each record] will still maintain a uniform probability distribution?

That should work if you pull the skip count from the appropriate distribution (negative binomial, I think).

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eru on Monday March 09, 2015 @08:28PM (#9175110)
Yes, you have to work out the right distribution, and how to sample from it (at all, and perhaps how to sample from it efficiently).
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by eru on Sunday March 08, 2015 @12:25AM (#9164677)
Yes.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by edc117 on Friday March 06, 2015 @01:39PM (#9158651)
Do you have to make sure to address the scenario where a generated index may possibly not exist in a table (deletion, whatever)? It says nothing about the index being contiguous. This can potentially end up with your algorithm returning less than #{X} if your generated indices don't exist.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by Veedrac on Friday March 06, 2015 @01:44PM (#9158684)
Just re-sample the ones that "miss". It won't affect the distribution.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by gearoidoc on Friday March 06, 2015 @01:42PM (#9158674)
You still have to loop over your returned records to verify uniqueness so wouldn't this automatically be solved?
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by gearoidoc on Friday March 06, 2015 @01:32PM (#9158617)
Nicely put, sir/ma'am!
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by gearoidoc on Friday March 06, 2015 @01:43PM (#9158677)
Downvoted for a compliment. Way to go HN, way to go.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by kbenson on Friday March 06, 2015 @02:01PM (#9158799)
You didn't add anything to the conversation. It's fine to compliment someone, but add to the conversation otherwise the comment is just noise. If all you have to say is that, just upvote.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by gearoidoc on Friday March 06, 2015 @01:50PM (#9158714)
Awesome.

Let's keep this going.

Re:Algorithms Every Programmer Should Know: Reservoir Sampling by barking on Friday March 06, 2015 @01:56PM (#9158762)
It's just the way that you're signalled not to make these kind of posts. It's not personal even if it feels like it.
Re:Algorithms Every Programmer Should Know: Reservoir Sampling by cnlwsu on Friday March 06, 2015 @01:59PM (#9158791)
https://news.ycombinator.com/newsguidelines.html

Resist commenting about being downvoted. It never does any good, and it makes boring reading.

Please don't bait other users by inviting them to downvote you.