Skip to content

Commit 7e99ead

Browse files
committed
feat: add MinHash Jaccard similarity estimator
1 parent 25bcced commit 7e99ead

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

machine_learning/min_hash.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""MinHash signatures for estimating Jaccard similarity.
2+
3+
MinHash uses the minimum value produced by several independent hash functions
4+
to turn a set into a compact signature. The fraction of equal positions in two
5+
signatures is an unbiased estimator of their Jaccard similarity.
6+
7+
References:
8+
https://en.wikipedia.org/wiki/MinHash
9+
https://www.cs.princeton.edu/courses/archive/spring13/cos598C/broder.pdf
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import hashlib
15+
from collections.abc import Iterable, Sequence
16+
17+
18+
def _token_hash(token: str, seed: int, permutation: int) -> int:
19+
"""Return a deterministic 64-bit hash for one token and permutation."""
20+
payload = f"{seed}:{permutation}:{token}".encode("utf-8")
21+
return int.from_bytes(hashlib.blake2b(payload, digest_size=8).digest(), "big")
22+
23+
24+
def min_hash(
25+
tokens: Iterable[str], num_perm: int = 128, seed: int = 0
26+
) -> tuple[int, ...]:
27+
"""Build a MinHash signature for an iterable of tokens.
28+
29+
``tokens`` is treated as a set: repeated tokens do not affect the
30+
signature. ``num_perm`` controls the accuracy/size trade-off.
31+
32+
>>> first = min_hash({"a", "b", "c"}, num_perm=64)
33+
>>> second = min_hash({"a", "b", "d"}, num_perm=64)
34+
>>> len(first) == len(second) == 64
35+
True
36+
>>> 0.0 <= estimated_jaccard(first, second) <= 1.0
37+
True
38+
>>> min_hash({"a", "b"}, num_perm=8) == min_hash({"a", "b"}, num_perm=8)
39+
True
40+
"""
41+
if num_perm <= 0:
42+
raise ValueError("num_perm must be positive")
43+
44+
unique_tokens = set(tokens)
45+
if not unique_tokens:
46+
raise ValueError("tokens must contain at least one item")
47+
48+
return tuple(
49+
min(_token_hash(token, seed, permutation) for token in unique_tokens)
50+
for permutation in range(num_perm)
51+
)
52+
53+
54+
def estimated_jaccard(first: Sequence[int], second: Sequence[int]) -> float:
55+
"""Estimate Jaccard similarity from two MinHash signatures.
56+
57+
>>> estimated_jaccard((1, 2, 3), (1, 4, 3))
58+
0.6666666666666666
59+
>>> estimated_jaccard((1, 2), (1,))
60+
Traceback (most recent call last):
61+
...
62+
ValueError: signatures must have the same length
63+
"""
64+
if len(first) != len(second):
65+
raise ValueError("signatures must have the same length")
66+
if not first:
67+
raise ValueError("signatures must not be empty")
68+
69+
return sum(left == right for left, right in zip(first, second)) / len(first)
70+
71+
72+
if __name__ == "__main__":
73+
import doctest
74+
75+
doctest.testmod()

0 commit comments

Comments
 (0)