Near-duplicate detection with MinHash
Watch MinHash find near copies among six texts without comparing every pair.
Explain it simply
Each text gets a checksum, a short code made from all of its bytes. Docs 4 and 5 are the same text, so their codes match and doc 5 goes. Change one word, and the whole code changes. So docs 1 and 2, one word apart, both stay.
Six texts in rows, each with its CRC-32 code on the right. Docs 4 and 5 show the same code, and doc 5 is crossed out. Docs 1 and 2 are marked.
Each text gets one 32-bit code from all of its bytes.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import zlib
from math import sqrt
docs = [
"the cat sat on the mat and fell asleep in the sun",
"the cat sat on the mat and fell asleep in the warm sun",
"a kitten rested on the rug and dozed off in the sunshine",
"stock prices rose on monday after the bank cut rates",
"stock prices rose on monday after the bank cut rates",
"stock prices fell on monday after the bank raised rates",
]
P = 2**31 - 1 # a prime: hash values run from 0 to P - 1
H, R = 16, 4 # hash functions, rows per band
A, B = 0, 1 # the pair: doc 1 and doc 2
def crc(s):
return zlib.crc32(s.encode())
# 1. exact dedup: one CRC-32 per whole text
print([format(crc(d), "08x") for d in docs])
# ['df230f8b', '68763841', '449135b3', '82677c2c', '82677c2c', '683ed550']
# 2. shingles: the set of word pairs of each text
def shingles(text):
w = text.split()
return {" ".join(w[i:i + 2]) for i in range(len(w) - 1)}
S = [shingles(d) for d in docs]
print(len(S[A] & S[B]), len(S[A] | S[B]), round(len(S[A] & S[B]) / len(S[A] | S[B]), 2))
# 10 13 0.77
# 3. MinHash: h_k(s) = (a_k * crc(s) + b_k) mod P; each text keeps the smallest
a = [crc(f"a1168-{k}") % (P - 1) + 1 for k in range(H)]
b = [crc(f"b1168-{k}") % P for k in range(H)]
print(a[0], b[0]) # 436315144 736738970
def signature(sh):
return [min((a[k] * crc(s) + b[k]) % P for s in sh) for k in range(H)]
sig = [signature(s) for s in S]
print(round(sig[A][0] / P, 3), round(sig[B][0] / P, 3))
# 0.014 0.014
matches = sum(x == y for x, y in zip(sig[A], sig[B]))
print(matches, round(matches / H, 2))
# 13 0.81
# 4. LSH: H // R bands of R rows; one equal band flags a pair
buckets = {}
for d, s in enumerate(sig):
for band in range(H // R):
key = (band, tuple(s[band * R:(band + 1) * R]))
buckets.setdefault(key, []).append(d)
pairs = sorted({(x, y) for ds in buckets.values() for x in ds for y in ds if x < y})
print([(x + 1, y + 1) for x, y in pairs])
# [(1, 2), (4, 5)]
# keep the first text of each cluster of flagged pairs
parent = list(range(len(docs)))
def find(x):
while parent[x] != x:
x = parent[x]
return x
for x, y in pairs:
rx, ry = find(x), find(y)
parent[max(rx, ry)] = min(rx, ry)
print([d + 1 for d in range(len(docs)) if find(d) != d])
# [2, 5]
# 5. same meaning: a toy embedding, one count per meaning (set by hand, not learned)
MEANING = {
"cat": "cat", "kitten": "cat", "sat": "sit", "rested": "sit", "mat": "mat", "rug": "mat",
"fell": "fall", "asleep": "sleep", "dozed": "sleep", "sun": "sun", "sunshine": "sun",
"warm": "warm", "stock": "stock", "prices": "price", "rose": "rise", "monday": "monday",
"bank": "bank", "cut": "cut", "raised": "raise", "rates": "rate",
}
def embed(text):
v = {}
for w in text.split():
if w in MEANING:
v[MEANING[w]] = v.get(MEANING[w], 0) + 1
return v
def cosine(u, v):
dot = sum(x * v.get(k, 0) for k, x in u.items())
return dot / sqrt(sum(x * x for x in u.values()) * sum(x * x for x in v.values()))
E = [embed(d) for d in docs]
print(round(cosine(E[A], E[B]), 2))
# 0.93
print([(x + 1, y + 1) for x in range(6) for y in range(x + 1, 6) if cosine(E[x], E[y]) >= 0.9])
# [(1, 2), (1, 3), (4, 5)]
Copy it into a file and run it. It prints what the diagram shows for the chosen controls.
Common mix-ups
MYTHMinHash finds texts that mean the same thing.
FIXMinHash measures shared word pairs. Docs 1 and 3 share few, so the estimate is 0.13; their cosine is 0.91.
MYTHMore bands make the duplicate check stricter.
FIXOne equal band flags a pair. With 16 bands of 1 row, docs 1 and 3 share a band, so doc 3 goes.
Takeaways
- A whole-text hash catches exact copies only; one new word changes it.
- Two MinHash slots match with chance equal to the Jaccard similarity.
- Bands send near copies to one bucket; same meaning needs an embedding.