Search code examples
pythongensimword2vec

How to check if a key exists in a word2vec trained model or not


I have trained a word2vec model using a corpus of documents with Gensim. Once the model is training, I am writing the following piece of code to get the raw feature vector of a word say "view".

myModel["view"]

However, I get a KeyError for the word which is probably because this doesn't exist as a key in the list of keys indexed by word2vec. How can I check if a key exits in the index before trying to get the raw feature vector?


Solution

  • convert the model into vectors with

    word_vectors = model.wv
    

    then we can use

    if 'word' in word_vectors.vocab