Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Fix 1651: make word_vec() return immutable vector #1662

Merged
merged 5 commits into from
Oct 30, 2017
Merged
Show file tree
Hide file tree
Changes from 4 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
7 changes: 5 additions & 2 deletions gensim/models/keyedvectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,12 @@ def word_vec(self, word, use_norm=False):
"""
if word in self.vocab:
if use_norm:
return self.syn0norm[self.vocab[word].index]
result = self.syn0norm[self.vocab[word].index]
else:
return self.syn0[self.vocab[word].index]
result = self.syn0[self.vocab[word].index]

result.setflags(write=False)
Copy link
Contributor

Choose a reason for hiding this comment

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

Please add test to check this behaviour (with Exception catching)

return result
else:
Copy link
Contributor

Choose a reason for hiding this comment

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

Why you remove this branch? We must raise an exception if word not in the dictionary.

raise KeyError("word '%s' not in vocabulary" % word)

Expand Down
6 changes: 6 additions & 0 deletions gensim/test/test_doc2vec.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,12 @@ def test_delete_temporary_training_data(self):
self.model_sanity(model, keep_training=False)
self.assertTrue(hasattr(model, 'syn1neg'))

def test_word_vec(self):
Copy link
Collaborator

Choose a reason for hiding this comment

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

More-descriptive name would be better, such as test_word_vec_non_writeable().

model = keyedvectors.KeyedVectors.load_word2vec_format(datapath('word2vec_pre_kv_c'))
vector = model['says']
with self.assertRaises(ValueError):
vector *= 0

@log_capture()
def testBuildVocabWarning(self, l):
"""Test if logger warning is raised on non-ideal input to a doc2vec model"""
Expand Down