v9.1.1
Menu

Chapter 4: Word Embeddings

Week 4

Learn how words are represented as dense vectors that capture semantic meaning, from Word2Vec and GloVe to subword methods like FastText and BPE. Master the algorithms, training objectives, and evaluation methods behind modern word representations.

Topics
6
Demos
3
Videos
3
Min read
47

Chapter Overview

Word embeddings are one of the most important breakthroughs in NLP. Instead of treating words as arbitrary symbols (one-hot vectors), embeddings map each word to a dense, low-dimensional vector where geometric relationships encode semantic meaning. Words with similar meanings cluster together, and directions in the vector space correspond to linguistic relationships like gender, tense, and geography.

The key insight is that you can learn these vectors from raw text alone. By training a model to predict words from their contexts (or vice versa), the model is forced to encode meaning into its weight matrices. The resulting vectors transfer to downstream tasks, providing a powerful initialization for everything from sentiment analysis to machine translation.

This chapter covers the major embedding algorithms --- Word2Vec (CBOW and Skip-gram), GloVe, and FastText --- along with subword tokenization methods (BPE, SentencePiece) that handle out-of-vocabulary words. You will also learn how to evaluate embedding quality using analogy tasks, similarity benchmarks, and downstream performance.

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
Word2Vec CBOW

Predicting a center word from context — learning dense embeddings by averaging surrounding word vectors.

CBOW Objective FunctionContext Window and SlidingEmbedding AveragingTraining and Loss
2
Skip-gram

Predicting context from a center word — better for rare words via negative sampling.

Skip-gram ObjectiveNegative SamplingNoise Distribution
Bridging predictive and count-based

Global co-occurrence and subword morphology

3
GloVe

Factorizing the global co-occurrence matrix — combining count-based and predictive approaches.

Co-occurrence MatrixGloVe Objective FunctionWeighting FunctionCo-occurrence Probability Ratios
4
FastText

Character n-gram embeddings — handling OOV words and morphology with subword information.

Character N-gram DecompositionOut-of-Vocabulary HandlingHashing Trick for Memory Efficiency
Measuring quality
5
Embedding Evaluation

Analogy tasks, similarity benchmarks, and downstream metrics — measuring what embeddings capture.

Word Analogy TasksCosine Similarity and Distance MetricsIntrinsic vs. Extrinsic EvaluationWord Similarity Benchmarks
Modern tokenization foundation
6
Subword Embeddings

BPE and SentencePiece — tokenization-level solutions that feed modern transformers.

Byte Pair Encoding (BPE)SentencePieceMorphological AwarenessVocabulary Size Trade-offs

Topics

6 topics in this chapter

Count-based vectors from the previous chapter have a dimension for every vocabulary word, so they are huge and sparse, and SVD on a 50,000 by 50,000 co-occurrence matrix is expensive to recompute whenever the corpus grows. Could a model instead learn short dense vectors directly from raw text, one sentence at a time, with a training signal that requires no labels?

The previous chapter, Text Representation, ended with dimensionality reduction, which compressed co-occurrence statistics into dense vectors. This chapter, Word Embeddings, learns such vectors by prediction, and it opens with Word2Vec's Continuous Bag of Words model from Mikolov et al. (2013). CBOW hides the center word of a window and predicts it from the surrounding words. The topic first states the CBOW objective, a softmax over the vocabulary, and then shows how the context window slides across the corpus to create training examples. Embedding averaging follows, the step that gives CBOW its bag-of-words name. It closes with the training loss and why the full softmax is too expensive, which sets up negative sampling in the next topic.

Definition

Continuous Bag of Words (CBOW) is a Word2Vec architecture that learns word embeddings by predicting a center word wtw_t from the average hˉ\bar{h} of its context words' input embeddings within a window of cc words on each side. Training maximizes log⁡P(wt∣context)\log P(w_t \mid \text{context}) over the corpus; the input embedding matrix becomes the word vectors.

In this topic

  1. 1CBOW Objective Function
  2. 2Context Window and Sliding
  3. 3Embedding Averaging
  4. 4Training and Loss
1 of 4
CBOW Objective Function

P(wt∣wt−c,…,wt+c)=softmax(W′⋅hˉ)P(w_t \mid w_{t-c}, \ldots, w_{t+c}) = \text{softmax}(W' \cdot \bar{h})

CBOW maximizes the probability of the center word wtw_t given its context. The context is represented by averaging the input embedding vectors of surrounding words to produce hˉ=12c∑−c≤j≤c,j≠0vwt+j\bar{h} = \frac{1}{2c} \sum_{-c \leq j \leq c, j \neq 0} v_{w_{t+j}}. This average vector is projected through a second weight matrix W′W' and passed through softmax over the entire vocabulary. The model has two sets of embeddings: input embeddings WW (used for context words) and output embeddings W′W' (used for prediction). After training, usually only the input embeddings WW are kept.

Mathematical Intuition

CBOW maximizes P(wt∣wt−c,…,wt+c)=softmax(W′hˉ)P(w_t \mid w_{t-c}, \ldots, w_{t+c}) = \text{softmax}(W' \bar{h}) where hˉ\bar{h} is the average of context embeddings. The softmax denominator ∑w=1Vexp⁡(vw′⋅hˉ)\sum_{w=1}^{V} \exp(\mathbf{v}'_w \cdot \bar{h}) sums over all ∣V∣|V| words — O(∣V∣)O(|V|) per training step. With ∣V∣=100,000|V| = 100{,}000 and billions of training positions, this is the computational bottleneck that negative sampling and hierarchical softmax were designed to solve.

Example:

Given the sentence "the quick brown fox jumps" with window size 2, what is the training example when "brown" is the center word?

2 of 4
Context Window and Sliding

The window size cc sets how many words on each side of the center count as context, giving up to 2c2c context words per position. The window slides over every position of the corpus, so CBOW creates one training example per token, and sentence edges get truncated contexts. Window size shapes what the vectors encode: small windows of about 2 favor syntactic neighbors, words that can replace each other in a sentence, while large windows of 5 to 10 favor topical relatedness. The original tool also samples an effective window size uniformly between 1 and cc for each position, which weights near neighbors more heavily than distant ones.

Mathematical Intuition

The context window of size cc produces 2c2c context words per position. Larger cc captures topical similarity (words about the same subject cluster together), while smaller cc captures syntactic similarity (words with the same part of speech cluster). Empirically, c=5c = 5 works well for most tasks. The window slides TT times across the corpus, generating TT training examples — the entire training set is just the corpus itself.

Example:

For the sentence "I love natural language processing" with window size 1, list all (context, target) training pairs.

3 of 4
Embedding Averaging

hˉ=12c∑j=−c,j≠0cvwt+j\bar{h} = \frac{1}{2c} \sum_{j=-c, j \neq 0}^{c} v_{w_{t+j}}

CBOW combines the context into a single vector by averaging the input embeddings vwt+jv_{w_{t+j}} of the 2c2c context words, as in the formula. Averaging discards the order of words inside the window, which is the bag-of-words part of the name, and it keeps the computation per example to one prediction no matter how many context words there are. Each context word receives the same share of the gradient. The average works because the model can spread complementary information across context words, but it also blurs them: a window containing both "river" and "money" yields a vector halfway between two meanings. Skip-gram, the next topic, avoids averaging altogether.

Mathematical Intuition

Embedding averaging hˉ=12c∑jvwt+j\bar{h} = \frac{1}{2c} \sum_{j} v_{w_{t+j}} is a lossy compression: 2c2c vectors are reduced to one. The information loss is bounded by the variance of the context embeddings: if all context vectors are similar (semantically coherent context), the average preserves most information. If they are dissimilar (diverse context), averaging destroys individual word signals. This is why CBOW struggles with rare words — their contexts are diverse.

Example:

If the embeddings for "the" = [0.1, 0.3], "cat" = [0.5, -0.1], "on" = [0.2, 0.4], "mat" = [-0.1, 0.2], what is hˉ\bar{h}?

4 of 4
Training and Loss

L=−1T∑t=1Tlog⁡P(wt∣wt−c,…,wt+c)\mathcal{L} = -\frac{1}{T} \sum_{t=1}^{T} \log P(w_t \mid w_{t-c}, \ldots, w_{t+c})

The training objective is to minimize the negative log-likelihood averaged over all TT positions in the corpus. Computing the full softmax over a vocabulary of VV words is expensive (requires summing over all words for the normalizing constant), so practical implementations use hierarchical softmax or negative sampling to approximate the gradient. Stochastic gradient descent with linear learning rate decay is standard. Training typically requires one or two passes over the corpus.

Mathematical Intuition

The cross-entropy loss L=−1T∑tlog⁡P(wt∣context)\mathcal{L} = -\frac{1}{T} \sum_t \log P(w_t \mid \text{context}) decreases as the model learns to predict center words. The gradient ∇hˉL=y^−y\nabla_{\bar{h}} \mathcal{L} = \hat{y} - y (predicted minus true distribution) has magnitude proportional to the prediction error. After convergence, the embedding matrix W∈R∣V∣×dW \in \mathbb{R}^{|V| \times d} encodes each word's meaning in dd dimensions, where d=100–300d = 100\text{--}300 is typical.

Example:

Why is computing the full softmax expensive for large vocabularies?

Theory Exercise

Problem:

Explain why CBOW tends to perform better on frequent words while Skip-gram performs better on rare words. What property of the CBOW architecture causes this?

Hints:
  • Think about how averaging affects rare vs. frequent words

Coding Exercise

Problem:

Implement a minimal CBOW model using NumPy. Create the forward pass that takes context word indices, looks up embeddings, averages them, and computes the softmax output.

Hints:
  • Use a random embedding matrix of shape (vocab_size, embed_dim)