Random Text Vector Generation with Word2Vec

  • Share this:

Code introduction


This function uses the Word2Vec model from the gensim library to generate the vector of a randomly selected word from the given text.


Technology Stack : gensim (Word2Vec, CoherenceModel)

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from gensim.models import Word2Vec
from gensim.models.coherencemodel import CoherenceModel

def generate_random_text_vector(model, text):
    """
    Generate a random text vector using a trained Word2Vec model.
    """
    # Ensure the model is trained
    if not model.wv:
        raise ValueError("Model is not trained. Please train the model before using this function.")
    
    # Split the text into words
    words = text.split()
    
    # Randomly select a word and generate its vector
    random_word = random.choice(words)
    return model.wv[random_word]