Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

Word2Vec Explained: From Theory to Python Implementation with Gensim

Word2Vec is a foundational NLP technique that converts words into dense vector embeddings using CBOW and Skip-Gram architectures to capture semantic relationships. This guide explains the core principles in detail and demonstrates a complete Python implementation with Gensim on a Shakespeare dataset, including word similarity search and PCA visualization.

Word2VecWord EmbeddingsGensim TutorialCBOWSkip-Gram

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

Subtitle: An Intuitive Understanding of Word2Vec and Its Implementation in Python

Original Article: https://towardsdatascience.com/word2vec-explained-49c52b4ccb71

Author: Vatsal (Machine Learning Engineer at MongoDB)

Translator: Dorothy, WaytoAGI (Way to AGI) Community Contributor

Introduction

Word2Vec is a recent breakthrough in the field of Natural Language Processing (NLP). Tomas Mikolov, a Czech computer scientist and currently a researcher at CIIRC (Czech Institute of Informatics, Robotics and Cybernetics), is one of the primary contributors to the research and implementation of Word2Vec. Word embeddings have become an indispensable part of solving many problems in NLP. They represent how humans teach machines to understand language. You can think of them as vectorized representations of text. Word2Vec is a widely used method for generating word embeddings and has numerous applications, such as text similarity, recommendation systems, sentiment analysis, and more.

Word Embeddings

Before diving into Word2Vec, let’s first understand what word embeddings are. This is important because the overall result and output of Word2Vec are the embeddings associated with each unique word passed to the algorithm. Word embedding is a technique that converts individual words into numerical representations (i.e., vectors). When each word is mapped to a vector, that vector is learned in a way similar to how a neural network learns. These vectors attempt to capture various features of the word in relation to the entire text. These features may include semantic relationships, definitions, context, and more. With these numerical representations, you can do many things, such as measuring similarity or dissimilarity between words.

Clearly, these embeddings are essential as input for various aspects of machine learning. Machines cannot process raw text directly, so converting text into embeddings allows users to feed them into classical machine learning models. The simplest form of embedding is one-hot encoding of text data, where each vector is mapped to a category.

However, such simple embeddings have several limitations: they cannot capture the semantic features of words, and they become extremely large depending on the size of the corpus.

Word2Vec Architecture

The power of Word2Vec comes from its ability to group vectors of similar words together. Given a sufficiently large dataset, Word2Vec can make strong estimates of a word’s meaning based on how often it appears in the text. These estimates produce word associations with other words in the corpus.

For example, words like “King” and “Queen” are very similar to each other. When performing algebraic operations on word embeddings, you can find approximations of word similarity. For instance, the 2-dimensional embedding of “King” minus the 2-dimensional embedding of “Man” plus the 2-dimensional embedding of “Woman” produces a vector very close to the embedding of “Queen”.

Note that the values below are randomly chosen for illustration.

King - Man + Woman = Queen
[5,3] - [2,1] + [3, 2] = [6,4]

You can see that the words “King” and “Queen” are positioned very close to each other. (Image by the author)

The success of Word2Vec is attributed to two main architectures: the Skip-gram and CBOW architectures.

CBOW (Continuous Bag of Words)

This architecture is very similar to a feed-forward neural network. The model essentially tries to predict a target word from a set of context words. The intuition behind this model is quite simple: given the phrase “Have a great day,” we choose “a” as the target word and [“have”, “great”, “day”] as the context words. What the model does is use the distributed representations of the context words to predict the target word.

CBOW architecture. Image source: Efficient Estimation of Word Representations in Vector Space

Skip-Gram Model

The Skip-Gram model is a simple neural network with a hidden layer, trained to predict the probability of a given word appearing when an input word is present. Intuitively, the Skip-Gram model is the exact opposite of the CBOW model. In this architecture, it takes the current word as input and tries to accurately predict the words that appear before and after the current word. This model essentially attempts to learn and predict the context words for a given input word. Experimental evaluations of the model’s accuracy have shown that, when given a wide range of word vectors, prediction quality improves, although computational complexity also increases. This process can be visualized as shown in the figure below.

Example of generating training data for the Skip-Gram model. Window size is 3.

As shown in the figure above, given a text corpus, a target word is selected within a sliding window. The training data consists of paired combinations of this target word with all other words in the window. This is how the neural network generates its training data. Once the model is trained, we can obtain the probability of a word appearing in the context of a given target word. The figure below illustrates the neural network architecture of the Skip-Gram model.

Skip-Gram Model Architecture

A corpus can be represented as a vector of size N, where each element in N corresponds to a word in the corpus. During training, we have a pair of target and context words. In the input array, all elements except the target word are set to 0, while the target word is set to 1. The hidden layer learns an embedding representation for each word, producing a d-dimensional embedding space. The output layer is a dense layer with a softmax activation function. Essentially, the output layer produces a vector of the same size as the input layer, where each element contains a probability. This probability represents the similarity between the target word and the corresponding word in the corpus.

For a more detailed understanding of both models, I strongly recommend reading the original paper.

Implementation

I will demonstrate how to use word2vec to generate word embeddings and then use these embeddings to find similar words and visualize the embeddings using PCA.

PCA (Principal Component Analysis) is a commonly used algorithm for dimensionality reduction. Its main idea is to map n-dimensional features to k dimensions. These k dimensions are new orthogonal features, also known as principal components, reconstructed from the original n-dimensional features¹. In short, the purpose of PCA is to reduce the number of variables in a dataset while retaining as much information as possible².

Data

For the purpose of this tutorial, we will use the Shakespeare dataset. You can find the file I used for this tutorial here. It includes all the lines Shakespeare wrote for his plays.

The Shakespeare dataset contains all of Shakespeare’s plays, characters, lines, and acts. Each sample corresponds to a continuous set of lines spoken by a character in a particular play.

Requirements

nltk==3.6.1
node2vec==0.4.3
pandas==1.2.4
matplotlib==3.3.4
gensim==4.0.1
scikit-learn==0.24.1

Note: You need to download the NLTK corpus to follow this tutorial. You can easily do so with the following commands:

python
import nltk
nltk.download('stopwords')
nltk.download('punkt')

Import Data

python
import pandas as pd
import nltk
import string
import matplotlib.pyplot as plt

from nltk.corpus import stopwords
from nltk import word_tokenize
from gensim.models import Word2Vec as w2v
from sklearn.decomposition import PCA


# constants
PATH = 'data/shakespeare.txt'
sw = stopwords.words('english')
plt.style.use('ggplot')

# nltk.download('punkt')

# nltk.download('stopwords')

import data

lines = [] with open(PATH, 'r') as f: for l in f: lines.append(l)


[**view raw**](https://gist.github.com/vatsal220/13f5e99da6e14af2ad9746a477b3f3a7/raw/fcbd3078ecc3f14a3f3ed75725ac4206ca94d7aa/w2v_import.py)[**w2v_import.py**](https://gist.github.com/vatsal220/13f5e99da6e14af2ad9746a477b3f3a7#file-w2v_import-py) 

**Note: You need to change the PATH variable to the path of the data you are using.**


## Preprocess Data

```python

# remove new lines
lines = [line.rstrip('\n') for line in lines]


# make all characters lower
lines = [line.lower() for line in lines]


# remove punctuations from each line
lines = [line.translate(str.maketrans('', '', string.punctuation)) for line in lines]


# tokenize
lines = [word_tokenize(line) for line in lines]

def remove_stopwords(lines, sw = sw):
    '''
    The purpose of this function is to remove stopwords from a given array of 
    lines.
    
    params:
        lines (Array / List) : The list of lines you want to remove the stopwords from
        sw (Set) : The set of stopwords you want to remove
        
    example:
        lines = remove_stopwords(lines = lines, sw = sw)
    '''
    
    res = []
    for line in lines:
        original = line
        line = [w for w in line if w not in sw]
        if len(line) < 1:
            line = original
        res.append(line)
    return res
    
filtered_lines = remove_stopwords(lines = lines, sw = sw)

view raww2v_preprocess.py

Stopword Filtering

  • When processing Shakespearean text data, we need to pay special attention to stopword filtering. Since these texts come from another century, we must consider the linguistic habits of that era. This is very important for cleaning words and preprocessing the data.

  • For example, modern English words like “you” or “yourself” would typically be removed by a standard stopword list, but in Shakespeare’s texts these words were not commonly used. Instead, words like “thou” or “thyself” may be more appropriate to filter out. Pay attention to these subtle differences, as they can have a significant impact on model performance.

  • In this example, I will not go into detail on how to identify stopwords from different eras, but please keep in mind that you should do so.

Embeddings

python
w = w2v(
    filtered_lines,
    min_count=3,  
    sg = 1,       
    window=7      
)       

print(w.wv.most_similar('thou'))

emb_df = (
    pd.DataFrame(
        [w.wv.get_vector(str(n)) for n in w.wv.key_to_index],
        index = w.wv.key_to_index
    )
)
print(emb_df.shape)
emb_df.head()

view raww2v_embedd.py

PCA on Embeddings

python
pca = PCA(n_components=2, random_state=7)
pca_mdl = pca.fit_transform(emb_df)

emb_df_PCA = (
    pd.DataFrame(
        pca_mdl,
        columns=['x','y'],
        index = emb_df.index
    )
)

plt.clf()
fig = plt.figure(figsize=(6,4))

plt.scatter(
    x = emb_df_PCA['x'],
    y = emb_df_PCA['y'],
    s = 0.4,
    color = 'maroon',
    alpha = 0.5
)

plt.xlabel('PCA-1')
plt.ylabel('PCA-2')
plt.title('PCA Visualization')
plt.plot()

view raww2v_pca.py

In the word embedding space, similar words tend to cluster close to each other. Image source: the author.

TensorFlow provides a very elegant, intuitive, and user-friendly visualization of word2vec models. I highly recommend exploring it, as it lets you interact directly with the results of word2vec. Link: projector.tensorflow.org

Closing Thoughts

Word embeddings are a crucial component in solving many NLP (Natural Language Processing) problems. They allow machines to understand how humans perceive and interpret language. Given a large text corpus, word2vec generates an associated embedding vector for every word in the corpus. The structure of these embeddings places words with similar characteristics close to one another in vector space. CBOW (Continuous Bag of Words) and Skip-gram are the two primary architectures of word2vec. Given an input word, the Skip-gram model attempts to predict the surrounding context words, whereas the CBOW model takes multiple context words and tries to predict the missing target word. (In other words, Skip-gram predicts context words from the center word, while CBOW predicts the center word from the context words.)

I have also written an article about node2vec, which applies the word2vec approach to generate node embeddings for a given network. You can read it via the link below.

Node2Vec Explained

Explaining & Implementing the Node2Vec Paper in Python

towardsdatascience.com

Resources