Sub topic 8
Implementing MinHash in Python
This chapter turns the MinHash idea into working code. It assumes you can read short Python programs, know what a hash function is, and know that the chance two sets get the same MinHash value equals their Jaccard similarity. You will build the signature function and the estimator, then check the estimate against the exact answer.
The plan in code
Each hash function stands in for one random ordering of all possible elements. For one function, the MinHash of a set is the smallest hash value among its elements. A signature is the list of these minimums, one per hash function. The estimator is the fraction of positions where two signatures agree.
Universal hash functions
You cannot store a random permutation of every possible element. Instead, use a family of cheap functions of the form h(x) = (a*x + b) mod P. Here P is a prime, a is drawn from 1 to P-1, and b from 0 to P-1. Each pair (a, b) defines one function, so k random pairs give k functions.
Two choices in the code below matter:
P = 2**61 - 1is a Mersenne prime larger than any 32-bit id. Becauseais not zero andPis prime, distinct ids belowPalways get distinct hash values, so the minimum is never ambiguous.- Strings become integers with
zlib.crc32, not Python's built-inhash. The built-in string hash is salted differently in each process, so signatures computed in two runs would not match.
The full program
import random
import zlib
P = (1 << 61) - 1 # a Mersenne prime larger than any 32-bit element id
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 estimate(sig1, sig2):
return sum(u == v for u, v in zip(sig1, sig2)) / len(sig1)
def jaccard(a, b):
return len(a & b) / len(a | b)
A = {str(i) for i in range(0, 150)}
B = {str(i) for i in range(50, 200)}
hashes = make_hashes(256)
sigA = signature(A, hashes)
sigB = signature(B, hashes)
print("exact: ", jaccard(A, B))
print("estimated:", estimate(sigA, sigB))The exact value is 0.5, because 100 elements are shared out of 200 distinct ones. The estimate will land near 0.5 but will rarely equal it. With 256 hash functions, the standard error is about 0.03.
Reading the code
make_hashes takes a seed so that the same family can be rebuilt later. This is required. Two signatures are comparable only if they were made with the same (a, b) pairs in the same order. Position i of one signature is compared with position i of the other, so a different seed or order makes the comparison meaningless.
signature runs in time proportional to k times the set size. The ids are computed once, outside the loop over hash functions, so each string is encoded only once.
estimate counts positions where the two minimums are equal. Each position is a trial that succeeds with probability equal to the Jaccard similarity. The mean of k trials is therefore an unbiased estimate of it.
Common errors
- Mixing hash families. Signatures built with different seeds will agree only by chance, and the estimate will be near zero for every pair.
- Using
hash()on strings. Results change between runs, so signatures stored on disk stop matching new ones. - Empty sets.
minof an empty sequence raisesValueError. Decide up front how to treat empty documents, for example by skipping them. - Comparing signatures of different lengths.
zipsilently truncates to the shorter one, which hides the bug. Checklen(sig1) == len(sig2)if the lengths can vary. - Id collisions. Two different strings can share a
crc32value. The two strings are then treated as one element. With millions of distinct elements this adds noticeable error, and a 64-bit hash of the element is the usual fix.
Exercises
Exercise
You build signatures for set X with make_hashes(128, seed=1) and for set Y with make_hashes(128, seed=2). Why is estimate(sigX, sigY) unreliable, even if X and Y are identical?
Show answer
The two signatures use different (a, b) pairs, so position i in one comes from a different ordering than position i in the other. Equal minimums then happen only by chance. Both signatures must come from the same hash family.
Exercise
Change the program so the signature length is 64 instead of 256. Roughly how does the standard error of the estimate change when the true similarity is 0.5?
Show answer
The standard error is sqrt(s(1-s)/k). For k=256 it is sqrt(0.25/256), about 0.031. For k=64 it is sqrt(0.25/64) = 0.0625. Cutting k by a factor of 4 doubles the error.