TL;DR
Finding the most similar pairs in a large collection is slow if you compare every pair. Locality-sensitive hashing (LSH) uses hash functions built so that similar items are likely to receive the same hash value, so only items that share a bucket need a full comparison. It gives up a small chance of missing a true match in exchange for a large speedup, and the balance is set by how many hashes you combine.
Builds on: Hash Function, Jaccard Index, Cosine Similarity · Leads to: MinHash, Approximate Nearest Neighbor Search
Where it's used
Removing near-duplicate web pages. A crawler that has fetched billions of pages wants to drop copies that differ only by a banner or a date. Each page is turned into a set of short pieces of text, and MinHash with banding flags candidate duplicates. Only the flagged pairs are then compared in full.
Finding similar items in a catalogue. A shopping or music service may want to answer "items like this one" over millions of products. Each item is represented as a vector, and random-hyperplane LSH puts vectors pointing in similar directions into the same bucket. A query looks in a few buckets instead of scanning the catalogue.
Clustering or deduplicating large text corpora for model training. Training data for language models is filtered for near-duplicates before training, because repeated text can distort what a model learns. LSH is one of the standard tools for doing that at scale, since comparing every document with every other is too costly.
How it works
Start with a question. Suppose we have a million sets of words and want the pairs that overlap a lot. Checking every pair means about half a trillion comparisons. LSH asks a different question: can we arrange the sets so that similar ones tend to meet in the same bucket, and only compare what meets?
The walkthrough below uses four short sets and one hash family, MinHash, which is the LSH family for Jaccard similarity and is covered in its own lesson. Every step can be checked by hand.
- Start with items as sets. Let , and . Check: and share two members, shares none with either.
- Hash each set with a function that prefers agreement. Take the minimum over the members of a random permutation, and call that the hash. Check: the probability that and get the same hash equals the share of their combined members they hold in common, which is here.
- Repeat with several independent hashes. Use four different random permutations, giving each set a signature of four values. Check: and agree in about one in three positions on average, and never agrees with either, because it shares no member with them.
- Split the signature into bands. Cut each signature into two bands of two rows. Two sets are candidates if they agree on every row of at least one band. Check: a pair with high overlap has a good chance of agreeing on a whole band, and a pair with low overlap rarely does.
- Compare only the candidates. Look up the bucket for each band, and compare in full only the pairs that share a bucket. Check: the cost is driven by the number of candidate pairs, not the number of all pairs.
flowchart LR A["Items"] --> B["Hash each item several times with an LSH family"] B --> C["Split each signature into bands"] C --> D["Put items into buckets, one table per band"] D --> E["Items sharing a bucket become candidate pairs"] E --> F["Check candidates exactly and keep matches"]
The key property is in step 2. An ordinary hash table is designed to scatter keys so that similar keys do not collide. An LSH family does the opposite on purpose: the collision probability is high when two items are similar and low when they are not. Step 4 then turns that weak preference into a sharp filter by requiring agreement on several hashes at once.
The math
An LSH family
Let be a family of hash functions and let be a similarity between items in . The family is locality-sensitive for this similarity if, for a random drawn from , the probability that two items collide is
Equality is the ideal. Many useful families only satisfy monotonicity: the collision probability rises with similarity. Two families are relevant here.
For Jaccard similarity, the MinHash family gives exactly , where . Step 2 of the walkthrough uses this fact: .
For cosine similarity, the random-hyperplane family picks a random vector with independent Gaussian entries and sets . If is the angle between two vectors, then
Check: gives , since the hyperplane splits the two vectors half the time, and gives .
Combining hashes: AND, then OR
A single hash is too weak to filter well. The standard fix is to combine hashes in two steps. Use hashes in each band and require all of them to agree (AND). Then use bands and call two items a candidate if at least one band agrees (OR). Let be the collision probability of one hash. Then
- the probability that all hashes in one band agree is ;
- the probability that one band disagrees somewhere is ;
- the probability that every band disagrees is .
So the probability that the pair becomes a candidate is
This is the S-curve. It is close to 0 for well below a threshold near , and close to 1 for well above it. Raising makes the curve steeper but lowers the candidate probability at each similarity, so the threshold moves up. Raising does the reverse: it raises the candidate probability and moves the threshold down. Those two knobs are the tradeoff the method is built around.
Cost
Comparing every pair of items takes comparisons. If a fraction of pairs become candidates, the work is roughly , plus the cost of computing the signatures and bucket lookups. Two costs are not free: a dissimilar pair that lands in the same bucket costs one full comparison, and the signatures take memory. The method pays off when is small.
Worked examples
Take and .
- The intersection is , which has 2 members.
- The union is , which has 6 members.
- So .
- A random MinHash function gives .
- Under a random ordering of the union, the first member to appear is equally likely to be any of the six. The minimums of and coincide exactly when that first member is one of the two shared members, or , so the chance is .
Interpretation: one hash agrees only a third of the time, so a single hash is a noisy test. Combining several hashes makes the test sharper, as the next example shows.
Use and . The candidate probability is , where is the similarity, here equal to the MinHash collision probability.
- For : , so , and the candidate probability is about , or 0.6%.
- For : , so , and the candidate probability is about .
- For : , so , and the candidate probability is about .
Interpretation: pairs with similarity 0.2 are almost never checked, pairs at 0.8 are almost always checked, and the threshold sits near 0.55. The steepness is what lets a small amount of compute separate similar from dissimilar pairs.
Suppose a collection has items.
- All pairs: comparisons.
- Assume the banding is tuned so that only 0.1% of pairs become candidates. That is .
- Candidate comparisons: .
- The saving is a factor of 1000 in comparisons, before counting the cost of building signatures and lookups.
Interpretation: the saving is only as good as the assumption that 0.1% of pairs are candidates. If the data has many near-duplicates, the fraction is higher and the saving is smaller. Measure the candidate rate on real data.
Try it: a banding uses rows and bands. What is the candidate probability for a pair whose MinHash collision probability is ?
Answer: , so , and . The candidate probability is , about 75%.
Common mistakes and tradeoffs
"LSH returns the exact nearest neighbours, just faster." It is tempting to think it is an exact index with a shortcut. In fact it is approximate: a true match can miss every band, and its probability is the complement of the candidate probability. The result is a set of likely matches, which must be checked, and some true matches may be lost.
"Any hash function will do." It is tempting to reuse the hash function already in a hash table. In fact a hash table wants keys scattered so that buckets stay balanced, while LSH wants similar items to collide. Using an ordinary hash gives no similarity signal at all, so the candidate set is essentially random.
"More bands always give better results." Raising raises recall, which is the chance of finding true matches, but it also raises the number of candidate pairs and therefore the cost. The right and depend on the similarity threshold you care about and on how expensive a full comparison is.
When to use LSH: very large collections, a similarity threshold you know in advance, and a tolerance for missing a small share of matches. When not to use it: small collections, where brute force is cheaper, and tasks that need exact answers. For high-dimensional dense vectors, approximate nearest-neighbour indexes based on graphs or quantisation are often a better fit, and they are covered in Approximate Nearest Neighbor Search.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Small collection | Setup and signatures cost more than brute force | Exact pairwise comparison |
| Exact answers required | LSH can miss true matches | Exact index or full comparison |
| Dense high-dimensional vectors | Many hash tables are needed for good recall | Graph-based or quantised approximate search |
| Threshold not known | The S-curve is set at the wrong place | Tune and on labelled pairs first |
History
Broder introduced MinHash in 1997 to measure the resemblance of web documents, and used it to find near-duplicate pages. Indyk and Motwani's 1998 paper on approximate nearest neighbours introduced the idea of a locality-sensitive family and combined hashes to amplify it, which made the framework general. Gionis, Indyk and Motwani followed in 1999 with a practical scheme for similarity search in high dimensions. Charikar's 2002 work on rounding algorithms gave the random-hyperplane family for cosine similarity. The idea caught on because it turned an impossible all-pairs search into a filter that a single machine could run on very large data.
Recap
- LSH uses hash functions where similar items collide more often than dissimilar ones.
- Combining hashes with AND and bands with OR gives the S-curve , which is a sharp filter.
- Only candidate pairs need full comparison, so the saving depends on the candidate fraction.
- Tune and for the similarity threshold you need, and measure recall on labelled pairs.
- Next: MinHash is the family for Jaccard similarity, and Approximate Nearest Neighbor Search covers the wider family of methods for finding close vectors.
Check yourself
QuestionWhy does LSH deliberately make similar items collide, when an ordinary hash table tries to avoid collisions?Show answer
A hash table wants keys spread evenly so that lookups are fast, and collisions are a cost to manage. LSH uses collisions as a similarity signal: a pair that collides is a candidate, so the hash must make similar items collide more often than dissimilar ones. Without that property the candidate set would contain pairs chosen at random.
QuestionA banding uses rows and bands. What is the candidate probability for a pair whose collision probability per hash is ?Show answer
, so . Then , and the candidate probability is , about 76%. This is a lenient setting: many pairs at this similarity become candidates.
QuestionTwo items have Jaccard similarity . Is the candidate probability for this pair under the standard 5-row, 20-band setting likely to be high or low, and why?Show answer
It is low, about 0.6%. With , , so almost every band fails, and across 20 bands the chance that at least one band agrees on all five rows is small. The filter is designed to reject pairs well below the threshold of about 0.55.
QuestionA team runs LSH on 10,000 items and finds it misses some pairs they know are similar. They increase the number of bands and recall improves, but the run takes much longer. Explain the tradeoff and what they should consider.Show answer
Increasing bands raises the candidate probability at every similarity, so more pairs are found, but more pairs become candidates and each one costs a full comparison. The team should measure the candidate fraction on their data, tune the rows and bands for the threshold they care about, and compare against brute force, since at 10,000 items the exact all-pairs comparison may already be fast enough.
Sources
- Wikipedia, Locality-sensitive hashing: https://en.wikipedia.org/wiki/Locality-sensitive_hashing
- Leskovec, Rajaraman, Ullman, Mining of Massive Datasets, Chapter 3: http://www.mmds.org