Word embeddings
Meaning as geometry: word2vec, GloVe and fastText
Word embeddings were the moment the field realized that meaning could be learned as geometry: similar words end up near each other, and directions encode relations. The skip-gram objective you derive here is a tiny neural network trained with the same cross-entropy and gradients as everything in Phase 4, its negative-sampling trick reappears in contrastive learning (5.8 Self-supervised and contrastive learning) and embedding models for RAG (9.2 Embeddings deep dive), and every transformer still begins with an embedding table (7.4 Inside the block: residuals, LayerNorm, FFN and embeddings).
You'll be able to
- Explain the distributional hypothesis and why dense vectors beat one-hot encodings
- Derive the skip-gram objective and its negative-sampling approximation, including the gradient for a center vector
- Describe GloVe's weighted least-squares objective and fastText's subword vectors
- Evaluate embeddings (analogies, similarity, downstream tasks), recognize their biases, and explain the move to contextual embeddings
Key ideas
- Distributional hypothesis: words in similar contexts have similar meanings; embeddings turn contexts into geometry.
- One-hot vectors are mutually orthogonal (no similarity); a dense embedding matrix E ∈ ℝ^(V×d) is a learned lookup table, and lookup = multiplying by a one-hot vector.
- Skip-gram predicts context words from the center word with a softmax over V; the embedding is the hidden layer of a one-layer network.
Show 4 more key ideas
- Negative sampling turns the V-way softmax into binary classification against K noise words (P_n ∝ U^{3/4}): O(Kd) per update, with a pull-positives/push-negatives gradient.
- GloVe fits dot products to log co-occurrence counts with weighted least squares; fastText sums character n-gram vectors so unseen and morphologically related words get vectors.
- Analogies (king − man + woman ≈ queen) show relational directions but are fragile; evaluate embeddings on your downstream task.
- Embeddings inherit corpus bias (programmer:homemaker) and static vectors conflate word senses; contextual embeddings (ELMo, BERT) fix the latter.
Suggested path through this lesson
The distributional hypothesis
"You shall know a word by the company it keeps" (Firth, 1957). Words that appear in similar contexts tend to have similar meanings: tea and coffee both follow "a cup of" and precede "with milk". If we can turn contexts into numbers, we can turn meaning into geometry.
From one-hot to dense
A one-hot vector for word is a -dimensional vector with a single 1. Every pair of one-hot vectors is orthogonal (1.1 Vectors, dot products and norms), so they encode identity and nothing about similarity: . A dense embedding maps each word to a vector in with (50–300 for word vectors, 768–4096 inside LLMs) in which similar words have high cosine similarity. The embeddings live in a matrix , and "looking up" word is the matrix–vector product — multiplying by a one-hot vector just selects a row (1.2 Matrices as transformations). The rows are learned parameters, trained by gradient descent like any other weight (4.4 Backpropagation, fully derived).
word2vec: the skip-gram model
Mikolov et al. (2013) trained embeddings with a deliberately simple task: given a center word , predict each word within a window of positions. Each word gets two vectors, as a center and as a context, and the prediction is a softmax over the vocabulary:
This is a one-layer neural network with cross-entropy loss (4.3 Loss functions catalog): the hidden layer is the embedding. The dot product is high when the context vector of aligns with the center vector of — the alignment-as-similarity idea from 1.1 Vectors, dot products and norms. Its problem is the denominator: a sum over the whole vocabulary for every training pair, per update.
Negative sampling
Skip-gram with negative sampling (SGNS) replaces the -way softmax with a binary task: is this (center, context) pair real or noise? For each observed pair draw noise words from a noise distribution and maximize
where is the sigmoid. The first term pushes real pairs together; the second pushes the center away from random words (5–20 of them). Each update now costs instead of . The noise distribution is the unigram distribution raised to the power, , which samples rare words more often than their frequency alone would. Frequent words ("the") are also subsampled from the training text so they do not dominate.
Math check. Treat the two terms as logistic regression (3.3 Logistic regression and softmax classification) with label 1 for the real pair and 0 for noise pairs. Using and , the gradient of the per-pair objective with respect to the center vector is
Gradient ascent moves toward the true context vector (by how surprised the model was) and away from each noise vector (by how much it wrongly believed them). The same "pull positives, push negatives" structure is the InfoNCE loss of contrastive learning (5.8 Self-supervised and contrastive learning, 9.2 Embeddings deep dive).
CBOW (continuous bag of words) reverses the task — predict the center from the average of the context vectors — and trains faster; skip-gram is better for rare words. Levy and Goldberg later showed that SGNS implicitly factorizes a shifted pointwise-mutual-information matrix of word co-occurrences, connecting the neural method back to counting (6.2 Classical NLP and n-gram language models).
GloVe: regression on co-occurrence counts
GloVe (Pennington, Socher & Manning, 2014) starts from the global co-occurrence matrix (how often word appears in the context of word ) and observes that ratios of co-occurrence probabilities carry meaning: is large, is small, and gives a ratio near 1. Requiring dot products to model log counts yields a weighted least-squares objective:
where the weighting ignores zero counts and caps the influence of very frequent pairs. GloVe trains on the (sparse) count matrix rather than on the text stream, and its word vectors behave much like word2vec's.
fastText: words as bags of character n-grams
word2vec and GloVe assign one vector per word type, so a word unseen in training has no vector and run/running/runner share nothing. fastText represents a word as the sum of the vectors of its character n-grams (3- to 6-grams, plus the whole word): where → ⟨wh, whe, her, ere, re⟩, ⟨where⟩. Morphologically related words share pieces, rare words borrow strength from their parts, and any new word gets a vector. It is the same subword insight as BPE (6.1 Text to numbers: tokenization) applied to embeddings. fastText also ships a very fast text classifier built on averaged embeddings.
Analogies, evaluation and bias
The famous result: (nearest neighbour by cosine, excluding the input words). Directions encode relations: gender, tense, capital-of, comparative. The effect is real but fragile — many analogies fail, and the standard evaluation quietly excludes the three input words. Intrinsic evaluations (word-similarity datasets, analogy sets) correlate only loosely with extrinsic performance on a downstream task, which is what you should care about.
Embeddings inherit the statistics of their corpus, including its stereotypes: Bolukbasi et al. (2016) found man : computer programmer :: woman : homemaker in Google News vectors, and occupations aligned along a gender direction. "Debiasing" by projecting out that direction removes the obvious analogy while leaving the bias recoverable from the geometry — a warning that applies to LLMs (8.12 Safety, risks and responsible AI).
From static to contextual
A static embedding gives bank one vector for riverbanks and savings accounts. The fix was to make the vector depend on the sentence: ELMo (2018) used the hidden states of a bidirectional LSTM language model (6.5 LSTM and GRU), and BERT (2019) used a transformer (7.5 Encoder-only: BERT and friends (and sentence embeddings)), producing contextual embeddings that differ for every occurrence. Modern sentence and document embeddings for search (9.2 Embeddings deep dive) are contextual models fine-tuned with the same contrastive idea as negative sampling. Yet the first layer of every one of these models is still a static lookup table (7.4 Inside the block: residuals, LayerNorm, FFN and embeddings) — word2vec's descendant.
Where this shows up later
- Embedding tables and weight tying in transformers — 7.4 Inside the block: residuals, LayerNorm, FFN and embeddings; contextual embeddings from BERT — 7.5 Encoder-only: BERT and friends (and sentence embeddings); sentence embeddings and MTEB — 9.2 Embeddings deep dive.
- Negative sampling → InfoNCE and contrastive learning — 5.8 Self-supervised and contrastive learning, CLIP — 8.10 Multimodal models; cosine similarity and high-dimensional geometry — 1.1 Vectors, dot products and norms.
- Bias and fairness in learned representations — 8.12 Safety, risks and responsible AI; probing what directions in activation space mean — 8.11 Interpretability: what is happening inside.
Common pitfalls (4)
- Comparing raw dot products instead of cosine similarity when vectors have very different norms (frequent words tend to have larger norms).
- Treating analogy accuracy as proof that embeddings 'understand' relations; the evaluation excludes input words and many analogies fail.
- Using static word embeddings for a task where word sense matters — contextual models exist for a reason.
- Assuming debiasing by projection removed the bias; it only hides the most visible symptom.
Recap: all 7 key points
- Distributional hypothesis: words in similar contexts have similar meanings; embeddings turn contexts into geometry.
- One-hot vectors are mutually orthogonal (no similarity); a dense embedding matrix E ∈ ℝ^(V×d) is a learned lookup table, and lookup = multiplying by a one-hot vector.
- Skip-gram predicts context words from the center word with a softmax over V; the embedding is the hidden layer of a one-layer network.
- Negative sampling turns the V-way softmax into binary classification against K noise words (P_n ∝ U^{3/4}): O(Kd) per update, with a pull-positives/push-negatives gradient.
- GloVe fits dot products to log co-occurrence counts with weighted least squares; fastText sums character n-gram vectors so unseen and morphologically related words get vectors.
- Analogies (king − man + woman ≈ queen) show relational directions but are fragile; evaluate embeddings on your downstream task.
- Embeddings inherit corpus bias (programmer:homemaker) and static vectors conflate word senses; contextual embeddings (ELMo, BERT) fix the latter.
Watch
Embeddings as the weights of a tiny network, plus the negative-sampling trick.
Read
Exercises
- Derive the context-vector gradient
Starting from the SGNS objective, derive (the gradient for the true context vector) and (for a noise vector). Expected: and — the same "surprise times the other vector" pattern.
- Skip-gram with negative sampling in NumPy or PyTorch
Train 50-dimensional embeddings on a few megabytes of text (e.g. the text8 corpus or a book) with window 2, K = 5 negatives and the 3/4-power noise distribution. Expected: nearest neighbours of "king", "paris" and "good" are semantically related after one epoch; some analogies work, many don't.
- Audit a pretrained embedding
Load a pretrained word-vector set (GloVe or fastText via gensim). Test 20 analogies of your own, then compute the projection of 30 occupation words onto the he−she direction. Expected: a mix of successes and failures on analogies, and a clear gender ordering of occupations — document both.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →