Word Embedding
Nlp tutorial · PySpark.in
Word Embeddings (NLP)
In NLP, one of the most important tasks is to represent words in a way that machines can understand. Words themselves are symbolic, so to perform tasks like text classification, sentiment analysis, or machine translation, we need to convert words into numerical vectors.
What are Word Embeddings?
“In NLP, word embedding is a term used for the representation of words for text analysis, typically in the form of real-valued vectors that encode the meaning of words such that words closer in the vector space are expected to be similar in meaning.”
In simpler terms, word embeddings map words into a continuous vector space. Words with similar meanings are placed close together, while words with opposite or unrelated meanings are far apart.
-
Happy and Excited will be close to each other in vector space.
-
Happy and Angry will be far apart since their meanings are opposite.
Detect similar words (e.g., happy ≈ joyful).
Capture opposites (e.g., happy ≠ sad).
Suggest contextually relevant words in a sentence.
Word2Vec is a neural network-based model that learns word associations from a large corpus of text.
Instead of sparse vectors filled with 0s and 1s (like in BoW/TF-IDF), Word2Vec produces dense vectors (e.g., 300 dimensions). These vectors encode semantic meaning — so words with similar meanings are closer in vector space.
By plotting these vectors (using techniques like PCA for dimensionality reduction), we can visualize semantic relationships between words.
Types of Word Embedding Techniques
Word embeddings can broadly be divided into two categories:
1. Count/Frequency-Based Methods
These are simpler techniques that rely on word frequency in documents.
-
One-Hot Encoding – Represents each word as a binary vector (sparse and inefficient).
-
Bag of Words (BoW) – Represents documents by counting word occurrences, but ignores word order.
-
TF-IDF (Term Frequency – Inverse Document Frequency) – Improves BoW by reducing the weight of common words (like "the", "is") and giving importance to rare words.
Limitations of these methods:
-
Sparse vectors (high-dimensional).
-
Do not capture semantic meaning.
-
Cannot understand context.
2. Deep Learning-Based Methods
To overcome the limitations of frequency-based methods, deep learning techniques were introduced. The most famous one is:
Word2Vec
-
Developed by Google.
-
Produces dense vector representations of words.
-
Learns semantic meaning – words used in similar contexts appear closer in the vector space.
-
Removes sparsity problems.
Word2Vec comes in two architectures:
-
CBOW (Continuous Bag of Words) – Predicts a word based on its surrounding context.
-
Skip-Gram – Predicts the surrounding words given a target word.
Example:
-
In the sentence “The king and the queen rule the kingdom”:
-
CBOW would predict queen if given the surrounding words.
-
Skip-Gram would predict surrounding words if given queen.
-
Word2Vec models can be trained from scratch, but they require a huge dataset. Luckily, pre-trained Word2Vec models.
Why Word2Vec is Better
Compared to one-hot, BoW, and TF-IDF, Word2Vec:
-
Produces dense, low-dimensional vectors.
-
Captures semantic relationships (e.g., king – man + woman = queen).
-
Handles large vocabularies efficiently.
-
Improves performance on downstream NLP tasks.
How Does Word2Vec Work?
At the core, Word2Vec represents each word as a vector of real numbers, derived by analyzing word usage patterns in text.
For example, consider a vocabulary with:
Each word gets represented as a vector across multiple hidden features such as:
-
Gender
-
Royalty
-
Age
-
Food
We don’t manually define these features the model learns them automatically. But for intuition:
-
Boy may map to
[gender=-1, royal=0.01, age=0.03, food=0.0...] -
Girl may map to
[gender=+1, royal=0.02, age=0.02, food=0.0...] -
King may map to
[gender=-0.92, royal=0.95, age=0.75...] -
Queen may map to
[gender=+0.93, royal=0.96, age=0.68...] -
Apple may map to
[gender≈0, royal≈0, food=0.91...]
This way, semantic relationships emerge naturally.
Example: Word Arithmetic
One of the most fascinating aspects of Word2Vec is word vector arithmetic.
For example:
This works because the vectors capture gender and royalty relationships simultaneously.
Measuring Word Similarity
To measure how close two word vectors are, we often use Cosine Similarity:
Cosine Similarity = cos ( θ ) = A ⋅ B ∣ ∣ A ∣ ∣ ∣ ∣ B ∣ ∣
-
If similarity ≈ 1 → words are very similar.
-
If similarity ≈ 0 → words are unrelated.
-
If similarity ≈ -1 → words are opposites.
Example:
-
King and Queen will have high similarity.
-
King and Apple will have low similarity.
Architectures of Word2Vec
Word2Vec has two main training architectures:
-
CBOW (Continuous Bag of Words)
-
Predicts a word given its surrounding context.
-
Faster and works well with smaller datasets.
-
-
Skip-Gram
-
Predicts surrounding words given a target word.
-
Better at capturing rare words and complex contexts.
-
Advantages of Word2Vec
Dense vector representation (no sparsity).
Captures semantic meaning (context-aware).
Enables arithmetic on words.
Improves NLP tasks like sentiment analysis, translation, recommendations.
Available in pre-trained models.
Applications of Word2Vec
-
Search Engines → Better query understanding.
-
Recommendation Systems → “If you liked Avengers, you may also like Iron Man.”
-
Chatbots/Assistants → Context-aware responses.
-
Machine Translation → Captures cross-lingual similarities.
Word2Vec CBOW Model Explained Step by Step
In our earlier discussion, we introduced Word2Vec and its two architectures:
-
CBOW (Continuous Bag of Words)
-
Skip-Gram
Now, we’ll go deeper into CBOW, understand how the model is created, what inputs/outputs look like, and how it is trained using deep learning concepts like loss functions and optimizers.
Pre-requisites
Before diving in, you should be familiar with:
-
Neural networks (fully connected layers)
-
Loss functions (like cross-entropy)
-
Optimizers (like gradient descent, Adam)
Step 1: The Corpus
Let’s take a small example corpus to understand CBOW:
In real-world applications, Word2Vec is trained on massive corpora. For example, Google’s pre-trained Word2Vec model is trained on 3 billion words.
Step 2: Window Size
Word2Vec works by considering a window of context words around a target (center) word.
Suppose we choose window size = 5.
That means:
-
4 words are input (context)
-
1 word is output (center word)
Example with window = 5:
We slide the window across the sentence, generating multiple (input → output) training pairs.
Step 3: Converting Words into Vectors
Neural networks cannot understand raw text. So we convert words into numerical vectors.
Here’s how:
-
Build a vocabulary:
→ 8 unique words.
-
Represent each word using One-Hot Encoding:
-
"I" → [1, 0, 0, 0, 0, 0, 0, 0]
-
"company" → [0, 0, 1, 0, 0, 0, 0, 0]
-
"is" → [0, 0, 0, 1, 0, 0, 0, 0]
-
Each word is a vector of length |Vocab| = 8.
Step 4: The CBOW Neural Network
The CBOW model is essentially a shallow neural network with:
-
Input Layer
-
Takes one-hot vectors of context words.
-
In our example: 4 words → 4 one-hot vectors.
-
-
Hidden Layer
-
Dense layer with
Nneurons (embedding size). -
Example: Google’s model uses
N = 300. -
Our toy example may use
N = 5.
This hidden layer is where the word embeddings are learned.
-
-
Output Layer
-
Softmax layer of size
|Vocab|. -
Predicts the probability distribution over all words.
-
The correct output is the center word (target).
-
Step 5: Training the Model
The training process looks like this:
-
Input context words → One-hot vectors.
-
Average their embeddings (from hidden layer).
-
Pass through output layer (softmax).
-
Compare predicted word distribution (
ŷ) with true output (y). -
Compute loss (cross-entropy).
-
Backpropagate to adjust weights (embedding vectors).
This process repeats for every training pair until the embeddings capture semantic meaning.
Step 6: Output Word Vectors
After training:
-
Each word has a learned embedding vector of size
N. -
Example (with
N=5):-
"I" → [0.92, 0.11, 0.36, 0.45, 0.25]
-
"company" → [0.12, 0.88, 0.44, 0.39, 0.76]
-
These vectors capture semantic relationships:
-
Similar words are close in vector space.
-
Arithmetic works:
king - man + woman ≈ queen.
Word2Vec Skip-Gram Model Explained
We have discussed CBOW (Continuous Bag of Words) and how it predicts the center word given its context.
Now let’s explore the second Word2Vec architecture – Skip-Gram, understand how it differs from CBOW, and when to use it.
What is Skip-Gram?
The Skip-Gram model works the opposite way of CBOW:
-
CBOW: Predicts the center word using surrounding context words.
-
Skip-Gram: Predicts the surrounding context words given the center word.
In simple terms:
-
CBOW = Context → Center
-
Skip-Gram = Center → Context
Example Sentence
Let’s use the same sentence:
Suppose we set window size = 5.
In CBOW:
-
Input: 4 context words →
["I", "neuron", "company", "related", "to"] -
Output: 1 center word →
"is"
In Skip-Gram:
-
Input: 1 center word →
"is" -
Output: Its context words →
["I", "neuron", "company", "related", "to"]
So, the direction of prediction changes.
Neural Network Structure
Skip-Gram uses a shallow neural network (like CBOW). Let’s break it down:
-
Input Layer
-
One-hot vector of the center word.
-
If the vocabulary size is
V = 7, the input vector has 7 dimensions. -
Example:
"is"→[0, 0, 1, 0, 0, 0, 0]
-
-
Hidden Layer
-
Dense layer with
Nneurons (embedding size). -
Example:
N = 5for a toy model, orN = 300in Google’s pre-trained Word2Vec. -
Learns the word embeddings.
-
-
Output Layer
-
Softmax layer of size
V. -
Predicts probability distribution for each context word.
-
Since window size = 5, we expect 5 context outputs.
-
Training Process
-
Input: One-hot encoding of the center word.
-
Multiply with weights → project to embedding space.
-
Predict context words using softmax.
-
Compare predicted distribution (
ŷ) with actual output (y). -
Compute loss (cross-entropy).
-
Apply backpropagation + optimizer (e.g., SGD, Adam).
-
Repeat until loss is minimized.
After training, every word is represented as a dense vector (N dimensions).
Example: Word Vectors
Suppose embedding size N = 5. After training, Skip-Gram might learn:
-
"is"→[0.15, 0.82, 0.45, 0.31, 0.09] -
"company"→[0.66, 0.14, 0.78, 0.25, 0.33]
These vectors capture semantic meaning. For example:
-
"king" - "man" + "woman" ≈ "queen"
When to Use CBOW vs Skip-Gram
-
CBOW:
-
Works better with small datasets.
-
Faster to train.
-
-
Skip-Gram:
-
Works better with large datasets.
-
Captures rare word representations more effectively.
-
Proven in research (used in Google’s Word2Vec paper).
-
How to Improve Skip-Gram (or CBOW)
-
Increase Training Data
-
More data → better accuracy.
-
-
Increase Window Size
-
Larger context window captures richer word relationships.
-
-
Increase Embedding Dimension
-
Instead of 5, use 100–300 dimensions.
-
Example: Google’s pre-trained Word2Vec uses 300-dimensional embeddings trained on 3 billion words from Google News.
-
Pre-Trained Word2Vec Models
Instead of training from scratch, you can use pre-trained embeddings.
-
Example: Google’s Word2Vec model
-
Trained on 3 billion words
-
Produces 300-dimensional embeddings
-
Available via Gensim library in Python
-
Example: The word "cricket" would be represented as a 300-dimensional vector, capturing its real-world semantic relationships.
Advantages of Word2Vec
1. Dense Vector Representation
-
Traditional methods like BoW and TF-IDF produce sparse matrices (lots of 0s and 1s).
-
Sparse matrices often lead to overfitting and make models computationally expensive.
-
Word2Vec generates dense vectors, meaning fewer zero values and compact, information-rich representations.
Why this matters: Dense vectors improve training efficiency and help machine learning models generalize better.
2. Captures Semantic Meaning
Unlike BoW or TF-IDF, Word2Vec goes beyond raw frequency. It captures the semantic relationship between words.
-
Similar words are placed close to each other in vector space.
-
Example:
-
"honest"and"good"→ vectors will be close. -
"happy"and"excited"→ vectors cluster together. -
"happy"and"angry"→ vectors will be far apart.
-
This makes it possible to measure similarity between words using metrics like cosine similarity.
3. Fixed-Dimension Embeddings
-
In BoW/TF-IDF, the vector size depends on the vocabulary size. If vocabulary = 50,000, each vector has 50,000 dimensions!
-
In Word2Vec, embeddings are fixed size, independent of vocabulary.
-
Example: Google’s pre-trained Word2Vec produces 300-dimensional vectors for every word.
Why this matters: This reduces dimensionality drastically and makes training efficient, even with very large corpora.
4. Handles Out-of-Vocabulary (OOV) Better
Earlier models struggled with out-of-vocabulary words (words not seen during training).
-
Word2Vec, especially when trained on large corpora (e.g., Google News dataset), minimizes this issue.
-
It learns general semantic and syntactic patterns, so even rare or unseen words can be approximated more effectively.
Why this matters: Makes Word2Vec more practical in real-world applications where new words frequently appear.
5. Improves Performance in Downstream Tasks
By providing meaningful word embeddings, Word2Vec improves performance in multiple NLP tasks such as:
-
Text classification
-
Sentiment analysis
-
Named Entity Recognition (NER)
-
Machine translation
-
Recommendation systems
Problem with plain Word2Vec
-
Word2Vec converts each word into a fixed-size vector (say, 300-D if using Google pre-trained).
-
Example:
-
"the" → 300-D
-
"food" → 300-D
-
"is" → 300-D
-
"good" → 300-D
-
-
For the sentence "the food is good", you now have four separate vectors, but for classification tasks, you need one vector representing the whole sentence/document.
Solution → Average Word2Vec
-
Take all word embeddings in the sentence and average them element-wise.
-
This gives one fixed-size vector (still 300-D if using 300-D embeddings) representing the entire sentence.
-
Example:
Advantages
-
Fixed-length representation: No matter how many words in the sentence, you always get a single 300-D vector.
-
Captures semantic meaning: Since Word2Vec embeddings already encode semantic similarity, averaging helps keep the “gist” of the sentence.
-
Efficient for classification: You can directly use this averaged vector as input to ML models (e.g., Logistic Regression, SVM, Neural Networks).
More Nlp tutorials
- Natural Language Understanding (NLU) , Natural Language Generation (NLG) and phases of NL
- Tokenization in NLP and NLP Project Life Cycle
- Coverting The Text to Vector(one hot encoding and bag of words method)
- Convert text to vector: N-grams and TF-IDF method
- What is Natural Language Processing ?
- Working with Text in NLP
All tutorials · Try the free PySpark compiler · Practice challenges