Skip to content
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

Fix KeyedVectors.add_vectors() error when use most_similar #3320

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion gensim/models/keyedvectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,8 @@ def add_vectors(self, keys, weights, extras=None, replace=False):
for attr, extra in extras:
self.expandos[attr][in_vocab_idxs] = extra[in_vocab_mask]

self.fill_norms()

def __setitem__(self, keys, weights):
"""Add keys and theirs vectors in a manual way.
If some key is already in the vocabulary, old vector is replaced with the new one.
Expand Down Expand Up @@ -705,7 +707,7 @@ def fill_norms(self, force=False):
either recalculated or 'None', to trigger a full recalculation later on-request.

"""
if self.norms is None or force:
if self.norms is None or len(self) != len(self.norms) or force:
self.norms = np.linalg.norm(self.vectors, axis=1)

@property
Expand Down
5 changes: 5 additions & 0 deletions gensim/test/test_keyedvectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,11 @@ def test_add_multiple(self):
for ent, vector in zip(entities, vectors):
self.assertTrue(np.allclose(kv[ent], vector))

# assert `len(kv)` == `len(kv.norms)` after `fill_norms()`
kv.fill_norms()
kv.add_vectors(["___not_present_in_keyed_vectors___"], [np.random.randn(self.vectors.vector_size)], replace=False)
self.assertEqual(len(kv), len(kv.norms))

def test_add_type(self):
kv = KeyedVectors(2)
assert kv.vectors.dtype == REAL
Expand Down