Calculate Set Similarity Measures in NumKong
mainNumKong provides optimized implementations for Hamming and Jaccard distance measures, which are essential for locality-sensitive hashing, MinHash sketches, and binary feature matching.
Hamming Distance
Counts the number of positions where elements differ.
- Binary vectors (packed octets): Counts the popcount of the XOR result.
- Byte-level vectors: Counts the number of mismatched bytes.
Jaccard Distance
Measures the dissimilarity of two sets.
- Binary vectors: Calculated as $1 - \frac{|A \cap B|}{|A \cup B|}$ using bitwise AND/OR and popcount.
- Word-level vectors (MinHash signatures): Calculated as the fraction of non-matching elements: $1 - \frac{\sum [a_i = b_i]}{n}$.
import numpy as np
def hamming_bits(a: np.ndarray, b: np.ndarray) -> int:
return np.unpackbits(np.bitwise_xor(a, b)).sum()
def jaccard_bits(a: np.ndarray, b: np.ndarray) -> float:
intersection = np.unpackbits(np.bitwise_and(a, b)).sum()
union = np.unpackbits(np.bitwise_or(a, b)).sum()
return 1 - intersection / union if union else 0
def jaccard_words(a: np.ndarray, b: np.ndarray) -> float:
return 1 - np.mean(a == b)