Word2Vec: Generate Word Vectors or Random Ones

  • Share this:

Code introduction


This function uses gensim's Word2Vec model to generate a word vector for a given word. If the word is not in the model's vocabulary, it generates a random vector.


Technology Stack : gensim library, Word2Vec model, numpy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_word_vector(word, model):
    """
    Generates a random word vector for a given word using a trained Word2Vec model.

    Args:
    word (str): The word for which to generate the vector.
    model (gensim.models.Word2Vec): The trained Word2Vec model.

    Returns:
    numpy.ndarray: The word vector.
    """
    # Check if the word is in the model's vocabulary
    if word in model.wv:
        return model.wv[word]
    else:
        # Generate a random vector if the word is not in the vocabulary
        return np.random.rand(model.vector_size)