Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 10 additions & 13 deletions docarray/document/mixins/featurehash.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,16 @@ def _any_hash(v):
try:
return int(v) # parse int parameter
except ValueError:
try:
return float(v) # parse float parameter
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can also check the parsed value, and raise exception then

v = float(v)
if math.isnan(v) or math.isinf(v):
    raise ValueError

except ValueError:
if not v:
# ignore it when the parameter is empty
if not v:
# ignore it when the parameter is empty
return 0
if isinstance(v, str):
v = v.strip()
if v.lower() in {'true', 'yes'}: # parse boolean parameter
return 1
if v.lower() in {'false', 'no'}:
return 0
if isinstance(v, str):
v = v.strip()
if v.lower() in {'true', 'yes'}: # parse boolean parameter
return 1
if v.lower() in {'false', 'no'}:
return 0
if isinstance(v, (tuple, dict, list)):
v = json.dumps(v, sort_keys=True)
if isinstance(v, (tuple, dict, list)):
v = json.dumps(v, sort_keys=True)

return int(hashlib.md5(str(v).encode('utf-8')).hexdigest(), base=16)
13 changes: 10 additions & 3 deletions tests/unit/document/test_feature_hashing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,17 @@
@pytest.mark.parametrize('sparse', [True, False])
@pytest.mark.parametrize('metric', ['jaccard', 'cosine'])
def test_feature_hashing(n_dim, sparse, metric):
da = DocumentArray.empty(3)
da.texts = ['hello world', 'world, bye', 'hello bye']
da = DocumentArray.empty(6)
da.texts = [
'hello world',
'world, bye',
'hello bye',
'infinity test',
'nan test',
'2.3 test',
]
da.apply(lambda d: d.embed_feature_hashing(n_dim=n_dim, sparse=sparse))
assert da.embeddings.shape == (3, n_dim)
assert da.embeddings.shape == (6, n_dim)
da.embeddings = to_numpy_array(da.embeddings)
da.match(da, metric=metric, use_scipy=True)
result = da['@m', ('id', f'scores__{metric}__value')]
Expand Down