Reputation: 779
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
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
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