Repository navigation
Add SimHash (Charikar's LSH) implementation #15797
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
samissue-He
wants to merge
2
commits into
TheAlgorithms:master
Choose a base branch
from
samissue-He:feat/simhash
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| """ | ||
| SimHash (Charikar's Locality-Sensitive Hashing for angular/cosine similarity). | ||
|
|
||
| Reference: | ||
| Moses S. Charikar (2002), "Similarity estimation techniques from rounding algorithms", | ||
| STOC '02: Proceedings of the 34th Annual ACM Symposium on Theory of Computing. | ||
| https://en.wikipedia.org/wiki/SimHash | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import hashlib | ||
| import re | ||
| from collections.abc import Iterable | ||
|
|
||
| _MAX_BIT_WIDTH = 512 | ||
|
|
||
|
|
||
| def tokenize(text: str) -> list[str]: | ||
| """ | ||
| Extract lowercase alphanumeric tokens from text. | ||
|
|
||
| >>> tokenize("SimHash: Fast, simple LSH!") | ||
| ['simhash', 'fast', 'simple', 'lsh'] | ||
| >>> tokenize("") | ||
| [] | ||
| """ | ||
| return re.findall(r"\w+", text.lower()) | ||
|
|
||
|
|
||
| def _hash_token(token: str, bit_width: int) -> int: | ||
| """ | ||
| Return a deterministic bit_width-bit integer digest for token. | ||
|
|
||
| >>> digest = _hash_token("simhash", 8) | ||
| >>> 0 <= digest < 256 and digest == _hash_token("simhash", 8) | ||
| True | ||
| """ | ||
| # Use blake2b instead of built-in hash() so fingerprints are deterministic | ||
| # across Python processes regardless of PYTHONHASHSEED. | ||
| digest_bytes = (bit_width + 7) // 8 | ||
| raw = hashlib.blake2b(token.encode("utf-8"), digest_size=digest_bytes).digest() | ||
| mask = (1 << bit_width) - 1 | ||
| return int.from_bytes(raw, "big") & mask | ||
|
|
||
|
|
||
| def _validate_bit_width(bit_width: int) -> None: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file |
||
| """ | ||
| Validate that bit_width is within [1, 512]. | ||
|
|
||
| >>> _validate_bit_width(64) | ||
| >>> _validate_bit_width(0) | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: bit_width must be between 1 and 512, got 0 | ||
| """ | ||
| if not 1 <= bit_width <= _MAX_BIT_WIDTH: | ||
| msg = f"bit_width must be between 1 and {_MAX_BIT_WIDTH}, got {bit_width}" | ||
| raise ValueError(msg) | ||
|
|
||
|
|
||
| def simhash( | ||
| features: Iterable[str | tuple[str, float]], | ||
| bit_width: int = 64, | ||
| ) -> int: | ||
| """ | ||
| Compute the SimHash fingerprint of unweighted or weighted features. | ||
|
|
||
| >>> h1 = simhash(tokenize("the quick brown fox jumps over the lazy dog")) | ||
| >>> h2 = simhash(tokenize("the quick brown fox leaps over the lazy dog")) | ||
| >>> h3 = simhash(tokenize("quantum chromodynamics and lattice gauge theory")) | ||
| >>> hamming_distance(h1, h2) < hamming_distance(h1, h3) | ||
| True | ||
| >>> simhash([("apple", 3.0), ("banana", 1.0)], bit_width=32) < (1 << 32) | ||
| True | ||
| >>> simhash([]) | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: features must not be empty | ||
| >>> simhash(["a"], bit_width=0) | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: bit_width must be between 1 and 512, got 0 | ||
| """ | ||
| _validate_bit_width(bit_width) | ||
| weights = [0.0] * bit_width | ||
| has_features = False | ||
|
|
||
| for item in features: | ||
| has_features = True | ||
| token, weight = (item, 1.0) if isinstance(item, str) else item | ||
| token_hash = _hash_token(token, bit_width) | ||
| for bit_index in range(bit_width): | ||
| if (token_hash >> bit_index) & 1: | ||
| weights[bit_index] += weight | ||
| else: | ||
| weights[bit_index] -= weight | ||
|
|
||
| if not has_features: | ||
| raise ValueError("features must not be empty") | ||
|
|
||
| fingerprint = 0 | ||
| for bit_index, total_weight in enumerate(weights): | ||
| if total_weight >= 0.0: | ||
| fingerprint |= 1 << bit_index | ||
| return fingerprint | ||
|
|
||
|
|
||
| def hamming_distance(hash_a: int, hash_b: int) -> int: | ||
| """ | ||
| Return the Hamming distance between two non-negative integer hashes. | ||
|
|
||
| >>> hamming_distance(0b1010, 0b1100) | ||
| 2 | ||
| >>> hamming_distance(42, 42) | ||
| 0 | ||
| >>> hamming_distance(-1, 0) | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: hash values must be non-negative | ||
| """ | ||
| if hash_a < 0 or hash_b < 0: | ||
| raise ValueError("hash values must be non-negative") | ||
| return (hash_a ^ hash_b).bit_count() | ||
|
|
||
|
|
||
| def similarity(hash_a: int, hash_b: int, bit_width: int = 64) -> float: | ||
| """ | ||
| Return normalized SimHash similarity in [0.0, 1.0]. | ||
|
|
||
| >>> similarity(0b1010, 0b1010, bit_width=4) | ||
| 1.0 | ||
| >>> similarity(0b1111, 0b0000, bit_width=4) | ||
| 0.0 | ||
| >>> similarity(0b1010, 0b1100, bit_width=4) | ||
| 0.5 | ||
| >>> similarity(16, 0, bit_width=4) | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: hash values must fit within bit_width=4 | ||
| """ | ||
| _validate_bit_width(bit_width) | ||
| upper_bound = 1 << bit_width | ||
| if not (0 <= hash_a < upper_bound and 0 <= hash_b < upper_bound): | ||
| msg = f"hash values must fit within bit_width={bit_width}" | ||
| raise ValueError(msg) | ||
| return 1.0 - hamming_distance(hash_a, hash_b) / bit_width | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import doctest | ||
|
|
||
| doctest.testmod() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As there is no test file in this pull request nor any test function or class in the file
hashes/simhash.py, please provide doctest for the function_hash_token