oren_isp
oren_isp

Reputation: 779

Randomly select vector in gensim word2vec

I trained a word2vec model using gensim and I want to randomly select vectors from it, and find the corresponding word. What is the best what to do so?

Upvotes: 2

Views: 1403

Answers (2)

Kyrylo Malakhov
Kyrylo Malakhov

Reputation: 1446

If you want to get n random words (keys) from word2vec with Gensim 4.0.0 just use random.sample:

import random
import gensim
# Here we use Gensim 4.0.0
w2v = gensim.models.KeyedVectors.load_word2vec_format("model.300d")
# Get 10 random words (keys) from word2vec model
random_words = random.sample(w2v.index_to_key, 10)
print("Random words: "+ str(random_words))

Piece a cake :)

Upvotes: 0

gojomo
gojomo

Reputation: 54173

If your Word2Vec model instance is in the variable model, then there's a list of all words known to the model in model.wv.index2word. (The properties are slightly different in older versions of gensim.)

So, you can pick one item using Python's built-in choice() method in the random module:

import random
print(random.choice(model.wv.index2entity) 

Upvotes: 1

Related Questions