Sub topic 10
Finding Similar Pairs with LSH Banding
This chapter assumes you can compute a MinHash signature and estimate Jaccard similarity from two signatures, as covered earlier. You should also be comfortable with basic probability and short Python programs.
The problem signatures leave open
A signature is short, so comparing two signatures is cheap. But with n documents there are n(n-1)/2 pairs. For a million documents that is about 500 billion comparisons, even if each one takes microseconds. Most pairs are not similar at all, so almost all of that work is wasted.
Locality-sensitive hashing (LSH) with banding avoids it. The idea is to make similar documents likely to land in the same hash bucket. Then you compare only documents that share a bucket.
How banding works
Take a signature of k = b r values. Split it into b bands of r consecutive rows each. For every band, hash the tuple of r values to a bucket. Two documents become a candidate pair* if they fall in the same bucket in at least one band. Buckets are per band, so a match in band 3 never pairs with a match in band 7.
Candidate pairs are only suggestions. Verify each one by estimating similarity from the full signatures, or by computing the exact Jaccard similarity.
Why this favors similar pairs
Suppose two sets have Jaccard similarity s. Each signature position matches with probability s. Then:
- All r rows of one band match with probability s^r.
- That band does not match with probability 1 - s^r.
- None of the b bands match with probability (1 - s^r)^b, treating bands as independent.
- At least one band matches with probability 1 - (1 - s^r)^b.
This curve rises slowly, then steeply, then flattens. It is called an S-curve. The steep part sits near the threshold t ≈ (1/b)^(1/r). Pairs well above t are almost always found, and pairs well below it are almost always skipped.
For b = 20, r = 5 (k = 100), the threshold is about 0.55:
| Jaccard similarity s | Probability of becoming a candidate |
|---|---|
| 0.2 | 0.006 |
| 0.3 | 0.047 |
| 0.5 | 0.470 |
| 0.8 | 0.9996 |
Implementation
The first two functions below implement banding and the S-curve. The demo reuses the MinHash code from the previous chapter. Document C shares no elements with A or B.
import random
import zlib
from collections import defaultdict
P = (1 << 61) - 1
def make_hashes(k, seed=0):
rng = random.Random(seed)
return [(rng.randrange(1, P), rng.randrange(0, P)) for _ in range(k)]
def signature(items, hashes):
ids = [zlib.crc32(x.encode()) for x in items]
return [min((a * x + b) % P for x in ids) for a, b in hashes]
def candidate_pairs(signatures, b, r):
# signatures: dict mapping doc id to a signature list of length b * r
buckets = defaultdict(list)
for doc, sig in signatures.items():
assert len(sig) == b * r
for band in range(b):
key = (band, tuple(sig[band * r:(band + 1) * r]))
buckets[key].append(doc)
pairs = set()
for docs in buckets.values():
for i in range(len(docs)):
for j in range(i + 1, len(docs)):
pairs.add((docs[i], docs[j]))
return pairs
def candidate_probability(s, b, r):
# chance that two sets with Jaccard similarity s share at least one band
return 1 - (1 - s ** r) ** b
b, r = 64, 4
hashes = make_hashes(b * r)
docs = {
"A": {str(i) for i in range(0, 150)},
"B": {str(i) for i in range(50, 200)}, # Jaccard with A is 0.5
"C": {str(i) for i in range(1000, 1150)},
}
sigs = {name: signature(items, hashes) for name, items in docs.items()}
print(sorted(candidate_pairs(sigs, b, r)))
print(candidate_probability(0.5, b, r))The last line prints about 0.98. So A and B are very likely reported as a pair, and C is almost certainly paired with neither. The result is random, because it depends on the hash seed.
Keeping the band index in the key matters. Without it, a band-1 value in one document could collide with an identical band-5 tuple in another, which is not a real match.
Choosing b and r
With k fixed, b * r = k, so raising r lowers b.
- Larger r makes each band stricter. The threshold moves up and fewer false candidates appear, but true pairs near the threshold are more likely to be missed.
- Larger b gives more chances to match. The threshold moves down and you catch more true pairs, but you get more false candidates to verify.
Pick the threshold t you care about, then pick b and r so that (1/b)^(1/r) is near t. Check the probability at a few values of s with candidate_probability.
Common errors
- Using a signature whose length is not b * r. The assertion in the code catches this.
- Treating candidates as confirmed matches. Banding gives false positives, so always verify.
- Expecting a sharp cutoff. A wider gap between b and r values gives a steeper curve only when k is larger.
- Putting very common band values into huge buckets. If many documents share a band, the pair loop in that bucket grows quadratically.
Exercise
A signature has k = 100 values, split into b = 25 bands of r = 4 rows. Estimate the similarity threshold, and compute the probability that a pair with s = 0.5 becomes a candidate.
Show answer
The threshold is about (1/25)^(1/4) = sqrt(0.2) ≈ 0.45. For s = 0.5, s^4 = 0.0625, so the probability is 1 - (1 - 0.0625)^25 = 1 - 0.9375^25 ≈ 1 - 0.20 = 0.80.
Exercise
You keep k = 100 but change from b = 20, r = 5 to b = 50, r = 2. Does the threshold go up or down, and what is the cost?
Show answer
It goes down, to about (1/50)^(1/2) ≈ 0.14. You catch nearly all similar pairs, but many dissimilar pairs also share a band, so you must verify far more candidates.