简体   繁体   中英

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?

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) 

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM