820. Bucket embeddings with random-hyperplane LSH
Why it matters Near-duplicate detection and some approximate nearest neighbour indexes use random-hyperplane LSH (SimHash).
Locality-sensitive hashing (LSH) with random hyperplanes gives similar vectors the same bit signature with high probability, so you only compare vectors that share a bucket.
Write lsh_buckets(X, planes). X is (n, d) and planes is (b, d). Bit j of vector x is 1 if planes[j] . x >= 0, else 0. The signature is the integer with bit 0 as the most significant bit (so bits [1, 0, 1] give 5). Return (signatures, buckets) where signatures is a list of ints and buckets is a dict signature -> sorted list of row ids.
def lsh_buckets(X, planes)Example 1
Input: lsh_buckets([[1.0, 1.0], [2.0, 0.5], [-1.0, -1.0]], [[1.0, 0.0], [0.0, 1.0], [1.0, -1.0]])
Output: ([7, 7, 1], {7: [0, 1], 1: [2]})
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
X @ planes.T gives every dot product at once, shape (n, b).
Hint 2
Turn each row of booleans into an integer with bit 0 as the highest bit.
Hint 3
Group row ids by signature with a dict.
Common mistakes
- Reading bit 0 as the least significant bit.
- Using > 0 instead of >= 0, which changes vectors that lie on a plane.
Understand the idea
Each random hyperplane splits space in two. Two vectors land on the same side with probability 1 - angle / pi, so vectors with a small angle tend to share most bits. Scaling a vector never changes its signature; negating it flips every bit (except exact zeros).
[1, 1] and [2, 0.5] are on the positive side of all three planes, signature 0b111 = 7; [-1, -1] gives [0, 0, 1] = 1 because it lies exactly on the third plane (dot 0 counts as 1).
bit_j = (planes[j] . x >= 0); signature = bits read as binary, bit 0 first