SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Bloom Filters
  • Cuckoo Filter
  • Skip Lists
  • Count-Min Sketch
  • HyperLogLog
  • Merkle Trees
  • MinHash
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Probabilistic and Other Structures

MinHash

Estimate how similar two big sets are by comparing tiny fingerprints.

โฑ 12 min readAdvancedHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

MinHash shrinks a big set (for example, all the words in a web page) into a tiny signature of a few numbers. By comparing two signatures you can estimate how similar the two sets are, without looking at the sets again.

  • Similarity is measured by the Jaccard index: items in both sets divided by items in either set. 0 means nothing shared, 1 means identical.
  • For each of k hash functions, keep the smallest hash of the set. Those k numbers are the signature.
  • The share of signature positions that match is the estimate of the similarity. A longer signature gives a better estimate.

02Concept: What is it?

Suppose you have millions of documents and you want to find near-duplicates. Comparing every pair, word by word, is far too slow. We need a small fingerprint for each document, where similar documents get similar fingerprints.

First turn each document into a set, for example the set of all overlapping 5-word pieces (called shingles). The similarity of two documents is then the Jaccard index of their sets:

๐Ÿ“Jaccard index
J(A, B) = |A โˆฉ B| / |A โˆช B|. If A and B share 3 items and together have 10 different items, J = 3 / 10 = 0.3.

Now the trick. Take a random-looking hash function h and compute h(x) for every item in a set. Look at the smallest value. For two sets A and B, the smallest hash over A โˆช B belongs to a random item of the union. It is the same for A and B exactly when that item is in both sets. So:

๐Ÿง The key fact
The chance that min h(A) equals min h(B) is exactly J(A, B). One hash function gives one yes/no coin flip with that chance. Use k hash functions, and the share of matches gets close to J.
From a big set to a small signature
๐Ÿ“„Document
โ†’โ†“split into shingles
๐ŸงบSet of itemsthousands
โ†’โ†“k hash functions, keep the min
๐Ÿ”ขSignaturek numbers
โ†’โ†“compare positions
๐Ÿ“ŠSimilarity estimate
Two documents become sets, then k-number signatures. The share of equal positions estimates the Jaccard index.

03Real-Life Example

๐ŸตTwo Shopping Baskets
Two shoppers each fill a basket from a shop with 60 products. You want to know how alike the baskets are, but you may only look at a small card for each basket. Before shopping, you shuffled the shop's products into a secret order (and you do this 16 times, in 16 different secret orders). On each basket's card you write, for every shuffle, which product comes first in that order. When two cards show the same first product in many of the 16 rows, the baskets must share many products.
Baskets
MinHash
A basket
A set of items
How alike two baskets are
The Jaccard index
One secret order of the products
One hash function
The first product from the basket in that order
The min-hash value
The small card
The signature of k numbers
Rows of the cards that match
Matching signature positions
More shuffles
Larger k, better estimate
Why equal minimums mean a shared item
๐Ÿ”€Shuffle all itemsone hash function
โ†’โ†“
๐Ÿฅ‡First item in A's basket
โ†”same item?
๐Ÿฅ‡First item in B's basket
โ†’โ†“
๐ŸŽฒYes with chance Jthe Jaccard index

04Why Do We Need It?

๐Ÿ“ฆTiny fingerprints
A set of millions of items becomes k numbers (often 100 to a few hundred).
โšกFast comparison
Comparing two signatures costs k steps, whatever the size of the original sets.
๐Ÿ”ŽNear-duplicate search
Combined with locality-sensitive hashing (LSH), you find similar items without comparing all pairs.
๐ŸงฉWorks on streams and parts
The signature of a union is the position-wise minimum of the signatures, so sets can be built piece by piece.
๐Ÿ—œ๏ธSaves memory
Store signatures instead of the full documents or sets.
๐ŸŽฏKnown accuracy
The error shrinks as 1 / โˆšk, so you pick k for the accuracy you need.
When sets are too big to compare directly, compare tiny signatures instead. The match rate is an unbiased estimate of the real similarity.

05Where Do We Use It?

๐Ÿ“ฐNear-duplicate web pages
Search engines and crawlers use it to spot pages that are almost the same, so they do not index them twice.
๐Ÿ“Plagiarism and copy detection
Compare documents, code files or essays by their shingle sets.
๐Ÿ›๏ธRecommendations
Find users or products with similar sets of purchases or likes.
๐ŸงฌGenomics
Tools estimate how similar DNA sequences are by comparing small sketches of their pieces.
๐Ÿ“งSpam and email clustering
Group messages that are small variations of the same text.
๐Ÿ—ƒ๏ธData cleaning
Find duplicate records, such as the same customer typed in slightly different ways.

06Types / Parts / How It Works

Making and using a signature

Building the signature
Set A = {apple, bread, milk}
h1min = 7
h2min = 3
h3min = 9
h4min = 2
Set B = {apple, milk, tea}
h1min = 7
h2min = 5
h3min = 9
h4min = 4
Equal position Different position
Position i holds the smallest value of hash function i over all items in the set.

In this made-up example 2 of 4 positions match, so the estimate is 2 / 4 = 0.5. (The true Jaccard is 2 shared / 4 total = 0.5.)

Related ideas

MethodWhat it doesNote
MinHash with k hash functionsk min values per setThe classic form. Needs k hash computations for every item.
One permutation hashing and variantsSplit items into k buckets and keep the min per bucketMuch cheaper to compute, with similar accuracy.
Locality-sensitive hashing (LSH) for MinHashCut the signature into bands, and compare only items that share a whole bandFinds likely-similar pairs without checking every pair.
SimHashA different fingerprint, based on bit votes, for cosine similarityCommon for near-duplicate text, but not the same as MinHash.
VisualizerEstimate similarity from a small signaturePick how much two sets overlap, then drag the signature size from 1 to 128. Watch the estimate wobble at small k and settle near the true value.
How much do the two sets overlap?
The 60 possible items. Green = in both sets, cyan = only in A, purple = only in B, dark = in neither.
Signatures: for each hash function, the smallest hash value among the items of the set (first 12 of 16 shown). Equal positions are green.
Set A001001010000
Set B0161001020000
True similarity
0.82
27 shared / 33 in total
Estimate
0.81
13 of 16 positions equal
Error
0.01
estimate vs true
Signature
16
numbers, instead of 30 items
13 of the 16 signature positions are equal, so the estimate is 0.81. The true value is 0.82. Very close, and the signatures are tiny compared with the sets.

The estimate for k = 4 / 16 / 64 / 128 is 0.75 / 0.81 / 0.77 / 0.76. The true value is 0.82. Similarity here is the Jaccard index: items in both sets divided by items in either set. The hash functions are fixed, so the same choices always give the same numbers.

07How to Use It / Steps / Implementation

Finding similar documents

  1. 1
    Turn each item into a set
    For text, use shingles: every run of 5 or so words (or characters). Similar texts share many shingles.
  2. 2
    Pick k hash functions
    Often 100 to 200. Use the same functions for every document, or the signatures cannot be compared.
  3. 3
    Build each signature
    For each hash function, hash every shingle and keep the smallest value. The k minimums are the signature.
  4. 4
    Compare two signatures
    Count the positions where they are equal and divide by k. That is the estimated Jaccard similarity.
  5. 5
    Avoid comparing all pairs
    Split each signature into bands of a few rows. Put documents with an identical band in the same bucket (LSH), and compare only documents that share a bucket.
  6. 6
    Choose a threshold
    For example, treat pairs with an estimate above 0.8 as near-duplicates. Check a sample by hand.
๐Ÿ’กChoosing k
The typical error of the estimate is about โˆš(J ร— (1 โˆ’ J) / k). With k = 100 and J = 0.5, that is about 0.05. Four times more hash functions halve the error.
โš ๏ธIt estimates Jaccard, nothing else
MinHash says how much two sets overlap. It does not know word order, meaning or how often an item appears, unless you build that into the set.

08Key Terms to Know

TermMeaning in easy words
SetA group of different items, such as the shingles of a document
Jaccard indexSize of the intersection divided by size of the union. From 0 to 1
ShingleA short run of words or characters used as one item of a text set
Hash functionA function that maps each item to a number in a mixed-up order
Min-hashThe smallest hash value among a set's items, for one hash function
Signature (sketch)The k min-hash values that stand for a set
EstimateThe share of equal signature positions, close to the true Jaccard
Near-duplicateTwo items that are almost, but not exactly, the same
LSH (locality-sensitive hashing)A way to put similar items in the same bucket, so you avoid comparing all pairs
BandA group of consecutive signature rows used by LSH
Unbiased estimatorAn estimate that is right on average. Its errors have no built-in lean

09Pros, Cons and Trade-offs

โœ… Pros
  • Tiny fixed-size signatures
  • Compare two sets in k steps
  • Unbiased estimate of Jaccard similarity
  • Works with LSH to avoid all-pairs comparison
  • Signatures of unions are easy to combine
โš ๏ธ Cons
  • Only an estimate, with random error
  • Only measures set overlap (Jaccard)
  • Needs k hash computations per item
  • Poor for very small sets or very low similarity
  • Choosing shingle size, k and thresholds needs tuning

Trade-offs

ChoiceWe gainWe lose
Larger kA more accurate estimateMore memory and more hashing work
Smaller kTiny signatures, fast to buildA noisy estimate
Short shinglesCatches small editsUnrelated texts share many common shingles
Long shinglesMore meaningful matchesSmall edits break many shingles
Many LSH bandsFewer missed similar pairsMore false candidates to check
Few LSH bandsFew candidates to checkMore missed similar pairs

10Common Problems and Mistakes

Common mistakes

  1. Using different hash functions for different items. Signatures can only be compared when built with the same k functions in the same order.
  2. A signature that is too short. With k = 5 the estimate is mostly luck.
  3. Mixing up similarity types. Jaccard is not cosine similarity, and it ignores counts and order.
  4. Poor hash functions. If they are not well mixed, the estimate becomes biased.
  5. Comparing all pairs anyway. That gives up the main saving. Use LSH or another index.
  6. Treating the estimate as exact. Items near the threshold should be checked with the real sets.

Things to watch

๐ŸŽฒRandom error
Two runs with different hash functions give slightly different estimates. Fix the functions.
๐Ÿ“Very different sizes
A tiny set inside a huge one has a very low Jaccard value, even though it is fully contained.
๐ŸงฎShingle choice
The set you build decides everything. Test it on examples you understand.
๐ŸšงThreshold tuning
A cut-off that is too low floods you with false matches. Too high, and you miss near-duplicates.

11Real-World Examples

๐Ÿ”ŽWeb search
MinHash was developed for detecting near-duplicate web pages in early web search engines.
๐ŸงฌGenome tools
Sketching tools use MinHash to compare large genomes quickly.
๐Ÿ“šBig data libraries
Spark MLlib and several Python libraries offer MinHash with LSH for near-duplicate search.
๐Ÿ›’Recommendations
Compare users by their sets of items to find people with similar taste.
๐Ÿ“งSpam clustering
Group the many slight variations of one spam message.
๐Ÿ’ปCode clone detection
Find copied or near-identical source files across a large code base.
๐Ÿ“Note
Libraries differ in their hash functions, defaults and APIs. Read the documentation of the one you use.
Mini case: dedupe 10 million pages
๐Ÿ“„10 million pages
โ†’โ†“shingle + MinHash
๐Ÿ”ขSignatures128 numbers each
โ†’โ†“LSH bands
๐ŸชฃCandidate pairsshare a bucket
โ†’โ†“check
โœ…Near-duplicates
Signatures and LSH narrow the work to a small set of likely pairs.

12Related Topics to Read Next

Bloom Filtersโ†’

Another compact summary of a set, answering membership instead of similarity.

HyperLogLogโ†’

Estimates the size of a set. MinHash estimates the overlap of two sets.

Count-Min Sketchโ†’

A sketch for counting how often items appear.

Vector Databasesโ†’

Find similar items by distance between vectors, a different kind of similarity search.

Full-Text Search Enginesโ†’

They also work with words and shingles of text.

Checksumsโ†’

A checksum shows two things are exactly equal. MinHash shows how close they are.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a signature of k numbers per set, used to estimate set similarity.
  • โœ”Similarity: Jaccard = |A โˆฉ B| / |A โˆช B|.
  • โœ”Build: for each of k hash functions, keep the smallest hash over the set.
  • โœ”Estimate: matching positions / k.
  • โœ”Why: P(min hashes equal) = Jaccard.
  • โœ”Accuracy: error about โˆš(J(1 โˆ’ J) / k). Bigger k means a better estimate.
  • โœ”Scale up: LSH bands put likely-similar items in one bucket, so no all-pairs comparison.
  • โœ”One line: โ€œCompare tiny signatures, and the match rate tells you how alike the big sets are.โ€
โ† Previous
Merkle Trees
Next โ†’
Batch vs Stream Processing