Random-Hyperplane LSH (Cosine)
Background
Random-hyperplane LSH (SimHash) turns each vector into a compact binary signature by taking dot products against random Gaussian hyperplane normals and thresholding at zero. The Hamming distance between signatures approximates the angular distance between the original vectors — sub-linear nearest-neighbour search with no learned parameters.
Problem statement
Implement lsh_signature(vec, hyperplanes). Compute the dot product of vec with each row of hyperplanes; return a boolean array where each entry is True iff the dot product is .
Input
vec— 1-Dnp.ndarrayof length .hyperplanes— 2-Dnp.ndarrayshape , rows sampled i.i.d. from .
Output
Returns np.ndarray of bool, shape .
Examples
Example 1 — shape
Input: vec shape=(2,), hyperplanes shape=(8, 2)
Output: shape=(8,), dtype=bool
Example 2 — opposite vectors have flipped signatures
Input: sig_a = lsh_signature(v, H); sig_b = lsh_signature(-v, H)
Output: sig_a == ~sig_b
Example 3 — near vectors share most bits
Input: v1 = [1, 0], v2 = [0.99, 0.01] over 64 hyperplanes
Output: Hamming distance is small (< 20% of bits)
Constraints
vec.shape[0] == hyperplanes.shape[1](dim match).- Output dtype is
bool. - Threshold is (not ) — matters only on exact zeros.
Notes
- Why it works. For random hyperplanes, equals the angle between and divided by — so Hamming distance is a sample estimate of angular distance.
- Indexing. With bits per vector, you can shard the database into buckets ( or so) for sub-linear lookup.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference small signature
- •Sample 2D signature
- •Example 3D signature