You can download this code by clicking the button below.
This code is now available for download.
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]