Word2Vec Model Creation and Loading Example

  • Share this:

Code introduction


This function uses the Word2Vec model from the gensim library to convert input text into word vectors and saves and loads the model.


Technology Stack : gensim, Word2Vec, LineSentence

Code Type : Function

Code Difficulty : Intermediate


                
                    
def word2vec_model_example(input_text):
    from gensim.models import Word2Vec
    from gensim.models.word2vec import LineSentence

    # Create a Word2Vec model
    model = Word2Vec(LineSentence(input_text), vector_size=100, window=5, min_count=5, workers=4)

    # Save the model to disk
    model.save("word2vec_model")

    # Load the model from disk
    loaded_model = Word2Vec.load("word2vec_model")

    # Get the vector for a specific word
    word_vector = loaded_model.wv["word"]

    return word_vector