30 Mins

2. Word Embeddings & Semantic Representation

From Sparse Vectors to Dense Embeddings

Traditional NLP methods relied on One-Hot encoding, where a vocabulary of size V is represented by vectors of dimension V, containing mostly zeros. This approach suffers from the curse of dimensionality, creating extremely sparse matrices that fail to capture semantic relationships. Two words with similar meanings, like 'cat' and 'dog', would be orthogonal in a one-hot space, meaning the dot product is zero, thus failing to encode any inherent similarity.

Dense word embeddings represent words as low-dimensional vectors in a continuous vector space. By projecting words into a smaller, fixed-size dimension, the model learns a latent semantic space where spatial proximity reflects semantic similarity. This transformation is not just a dimension reduction technique; it is a learning objective where the geometry of the space captures linguistic regularities such as gender, tense, or pluralization.

Operator Note: Dense embeddings are trainable parameters. During backpropagation, the gradients update the specific row corresponding to the input token, making the model sensitive to context.
Python 3
import torch
import torch.nn as nn
# Define vocabulary size and embedding dimension
vocab_size, embedding_dim = 1000, 32
# nn.Embedding is essentially a lookup table that stores vector weights
embedding_layer = nn.Embedding(vocab_size, embedding_dim)
# Map word index 5 to a dense vector
word_index = torch.tensor([5])
embedded_vector = embedding_layer(word_index)
print(embedded_vector.shape) # Result: torch.Size([1, 32])

Word2Vec: CBOW vs. Skip-gram

The Word2Vec architecture introduces two distinct training methodologies: Continuous Bag of Words (CBOW) and Skip-gram. CBOW predicts a target word based on its surrounding context window, making it highly effective for smaller datasets and frequently occurring words. By averaging the vectors of the context tokens, the model smooths out individual word noise, leading to efficient convergence.

Conversely, Skip-gram predicts the surrounding context tokens given a single target word. This architecture performs significantly better on rare words because it forces the model to generate multiple context-sensitive predictions for each target instance. While computationally more expensive than CBOW, Skip-gram creates higher-quality vector representations by maximizing the probability of observing context words, effectively building a robust semantic manifold.

Operator Note: When evaluating similarity, always normalize your vectors first if the model is not trained with a specific cosine loss, as dot product magnitudes can vary widely depending on frequency.
Python 3
import torch.nn.functional as F
# Mock representation of two words
vec_cat = torch.randn(32)
vec_dog = torch.randn(32)
# Calculate Cosine Similarity: dot(a, b) / (||a|| * ||b||)
sim = F.cosine_similarity(vec_cat.unsqueeze(0), vec_dog.unsqueeze(0))
print(f'Semantic Similarity: {sim.item():.4f}')

Knowledge Check

Ready to test your understanding of 2. Word Embeddings & Semantic Representation?

Back