Sub topic 7
Signatures and the similarity estimator
This chapter assumes you know the MinHash value of a set (the smallest hash over its elements) and the earlier result that two sets have equal MinHash values with probability equal to their Jaccard similarity. You should also be comfortable reading short Python programs.
From one value to a signature
A single MinHash value is a poor measurement. Two sets either match on it or they don't, so one comparison gives you a 0 or a 1. You can't read a similarity such as 0.5 from that.
The fix is to repeat the experiment with many independent hash functions. A signature is the list of MinHash values of a set under k different hash functions:
signature(S) = [min h1(S), min h2(S), ..., min hk(S)]The signature has length k no matter how large the set is. A set with a million elements and a set with ten elements both become k numbers.
Each hash function must be chosen once and then reused for every set you compare. Signatures are only comparable position by position if position i always means "hash function i".
The estimator
Take two sets A and B with signatures sigA and sigB. For each position i, the probability that sigA[i] equals sigB[i] is J(A, B). That is the collision property from the previous chapter. The k positions use independent hash functions, so each position is an independent coin flip that lands "match" with probability J.
The estimator is the fraction of positions where the signatures agree:
estimate(A, B) = (number of i with sigA[i] == sigB[i]) / kIts expected value is exactly J(A, B), so it is unbiased. The estimate is also a count of successes divided by k, so it behaves like a binomial proportion. Its variance is J(1 − J) / k, which shrinks as k grows.
A worked implementation
The code below builds on the exact-Jaccard example from the first chapter. It uses hash functions of the form (a * x + b) mod P. The chapter on implementation covers why this family works. Here the point is how signatures and the estimator fit together.
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)
hashes = make_hashes(256)
A = {str(i) for i in range(0, 150)}
B = {str(i) for i in range(50, 200)}
print(estimate(signature(A, hashes), signature(B, hashes))) # close to the true value 0.5The sets share 100 of 200 distinct elements, so the true Jaccard similarity is 0.5. With k = 256 the printed value will be near 0.5. With this k the standard deviation is about 0.03, so a result between 0.44 and 0.56 is ordinary.
Three details in the code matter:
make_hashesis called once, and the samehasheslist is passed to bothsignaturecalls. Using different hash lists for A and B would make the positions unrelated, and the estimate would be near 0.signaturefirst turns each string into an integer withzlib.crc32. The hash family needs integers. Python's built-inhashfor strings changes between runs unless you fix the hash seed, so it would make stored signatures unusable later.- The signature is computed once per set. After that,
estimatenever touches the original elements.
Where this fits with documents
For documents, the set is the set of shingles from the shingling chapter. You would pass shingles(text) as items. Then a document of any length becomes k integers, and comparing two documents costs k comparisons instead of a set intersection over thousands of shingles.
You can also store signatures and compare them later. This is the main practical gain: the expensive pass over each document happens once.
Common errors
- Empty sets.
minof an empty sequence raises an error, and the Jaccard similarity of two empty sets is 0/0. Decide how to handle empty documents before computing signatures. - Treating the estimate as exact. An estimate of 0.52 does not mean the true value is above 0.5. Compare estimates against thresholds with the error in mind.
- Reading matches as set overlap. A matching position says the minimum-hash element lies in the intersection. It says nothing about which elements are shared.
- Duplicate-heavy data. MinHash works on sets. Repeated elements collapse, so a document that repeats one phrase 100 times looks the same as one that contains it once.
Exercise
Exercise
Two sets have true Jaccard similarity 0.8. You compute signatures with k = 100 hash functions. What is the expected number of matching positions, and what is the standard deviation of the estimate?
Show answer
Each position matches with probability 0.8, so the expected number of matches is 100 × 0.8 = 80, which gives an expected estimate of 0.8. The variance of the estimate is J(1 − J) / k = 0.8 × 0.2 / 100 = 0.0016, so the standard deviation is 0.04.
Exercise
A colleague computes the signature of set A with make_hashes(128, seed=1) and the signature of set B with make_hashes(128, seed=2), then calls estimate. What result should they expect, and why?
Show answer
They should expect a value near 0, whatever the true similarity. The two signatures use different hash functions, so matching positions no longer correspond to the collision property for the same permutation. Matches then happen only by chance. Both signatures must come from the same list of hash functions.