Log inStart free
LESSON 11.03 · 6 STAGES · 3 CONTROLS · 3 CHECKS

Near-duplicate detection with MinHash

Watch MinHash find near copies among six texts without comparing every pair.


EXPLAINER · 11.03 · DEDUP BAY
01
Stage 1 of 6 · Exact hashes
Deduplication keeps one copy of each text. Docs 1 and 2 differ by one word, but their CRC-32 values look unrelated.
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.

texts, shingleshashes, bands, limitsminimums, scoresremoved
Toy: 6 short texts, word pairs, CRC-32 hashes; meanings set by hand
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
Near copy
Pick the two texts to compare.
16
Slots in each signature.
4
Slots that must all match in one band.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
ci=crc32⁡(di)\sy{c}{out}{c_i} = \operatorname{crc32}(\sy{d}{data}{d_i})
c1=df230f8b≠c2=68763841c_{1} = \texttt{df230f8b} \ne c_{2} = \texttt{68763841}

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.

Predict, then reveal
0 / 3 REVEALED
Q01With 4 hash functions, does the estimate for docs 1 and 2 move away from 0.77?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With 2 rows per band, do docs 4 and 6 become a flagged pair?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03For an exact copy, how many of the 16 signature slots match?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. A whole-text hash catches exact copies only; one new word changes it.
  2. Two MinHash slots match with chance equal to the Jaccard similarity.
  3. Bands send near copies to one bucket; same meaning needs an embedding.