Word Embeddings: From Words to Vectors
After this lesson, you will be able to:
- Understand why neural networks need words turned into numbers before they can do anything useful
- See why the simplest approach (one-hot encoding) breaks down for real language
- Learn how Word2Vec discovers word meaning automatically using two clever tricks (CBOW and Skip-gram)
- Understand how GloVe figures out word meaning by counting which words appear near each other
- See how the embedding layer in neural networks feeds into transformers
- Measure how similar two words are using cosine similarity
Before you start
#The Translation Problem: Words to Numbers
This lesson covers the journey from naive word representations to the powerful embeddings that underpin every modern language model.
#Attempt 1: One-Hot Encoding (and Why It Fails)
The simplest idea: assign each word in your vocabulary a unique index, then represent it as a vector of all zeros with a single one at that index.
For a vocabulary of 4 words (["cat", "dog", "king", "queen"]) one-hot vectors look like:
This seems clean, but it has three fatal problems:
-
Massive dimensionality. A real vocabulary has 50,000+ words. Each vector is 50,000-dimensional with a single non-zero entry. That is extraordinarily wasteful.
-
No similarity information. The dot product between any two different one-hot vectors is always zero. "Cat" is exactly as similar to "dog" as it is to "democracy", which is absurd. The representation encodes no meaning whatsoever.
-
No generalization. If the model learns something about "cat" (e.g., it is an animal, it is a pet), that knowledge does not transfer to "kitten" at all because their representations share nothing.
#Word2Vec: Learning Meaning from Context
In 2013, Tomas Mikolov at Google proposed a brilliant insight: a word's meaning is defined by the company it keeps. If "cat" and "dog" appear in similar contexts ("The ___ sat on the mat", "I fed the ___"), they should have similar vector representations.
Word2Vec trains a shallow neural network on a massive text corpus using one of two strategies:
#CBOW (Continuous Bag of Words)
Given the surrounding context words, predict the center word.
CBOW averages the context word vectors and passes them through a simple network to predict the target. It is fast and works well for frequent words.
#Skip-gram
Given a center word, predict the surrounding context words. This is the reverse of CBOW.
Skip-gram creates more training examples per word (one for each context position), so it captures better representations for rare words.
Skip-gram trains by maximising the average log probability of the context words. Over a corpus of T words and a window of m words on each side of the centre word, the objective is:
The probability is a softmax over the whole vocabulary. Every word has two vectors: v_c when it is the centre word and u_o when it is a context word (o for outside, c for centre).
To learn, we need the gradient of log p(o | c) with respect to the vectors. It has a clean shape: the context vector we observed, minus the average context vector the model expected. Open the derivation to see where that comes from, and why it makes the full softmax expensive.
Which two words would be closest in embedding space: cat/dog, cat/democracy, or cat/refrigerator?
Both words appear in contexts about animals, pets, and homes. Word2Vec learns this automatically — no one tells the model that cats and dogs are both animals. The model discovers it from patterns in billions of sentences.
#CBOW: Averaging the Context
CBOW first averages the C context vectors into one vector h, then uses the same softmax to predict the centre word from h. Averaging has a simple effect on learning: the gradient of the loss is split equally among the context words. Open the derivation to see why.
#Negative Sampling: Replacing the Softmax
The full softmax touches all V words for every pair. Negative sampling (Mikolov et al., 2013) turns the problem into a handful of yes or no questions. For the real pair (centre c, context o) the model should say yes. For k randomly drawn words w_1 up to w_k, the model should say no. The objective for one pair is:
Open the derivation to see the gradient, its link to the softmax gradient above, and where the sigmoid comes from.
How should the k noise words be drawn? Not uniformly, and not from the raw word frequency either. Mikolov et al. found that the unigram frequency raised to the power 3/4 worked best. Open the derivation to see the effect of that power.
#Subsampling Frequent Words
Words like "the" and "in" appear billions of times and say little about their neighbours. Mikolov et al. throw each occurrence of word w away with a probability that grows with its frequency f(w), and they keep t as a threshold, typically around 0.00001:
Open the derivation to see what this does to the effective frequencies the model trains on.
#fastText: Words Built from Pieces
< and >, and take all n-grams with n from 3 to 6. For "where" with n = 3 the pieces are <wh, whe, her, ere and re>.Open the derivation to see why training shares knowledge across words, and how many pieces a word has.
#The Magic: Word Arithmetic
- Paris - France + Italy ≈ Rome (capital city relationship)
- walking - walked + swam ≈ swimming (tense relationship)
- bigger - big + small ≈ smaller (comparative form)
#The 3CosAdd Rule
To answer "a is to a* as b is to what?", the standard rule picks the word b* whose vector is most similar in cosine to b - a + a*. It is called 3CosAdd.
The name comes from a rewriting: when every vector has length 1, this one cosine equals a sum of three cosines. Open the derivation to see the algebra.
#GloVe: Learning from Co-occurrence
The idea: build a giant matrix counting how often each word appears near every other word across the entire corpus. Then factorize this matrix into dense vectors.
Where does this equation come from? Pennington et al. start from a different place than a loss: they ask what in the counts carries meaning. Let X_ij be how often word j appears in the context of word i, X_i the total for word i, and P_ij = X_ij / X_i the probability that j appears near i. Open the derivation to see how the equation follows from ratios of these probabilities.
The equation cannot hold exactly for a real corpus, and log X is undefined where X is 0. GloVe therefore minimises a weighted squared error over all pairs, where a weight f(X_ij) of 0 removes the zero entries and a cap stops the very frequent pairs from dominating:
The weight f(x) = (x / x_max)^0.75 for counts below x_max = 100 and 1 above it is the choice in the paper; the authors say they offer only empirical motivation for the exponent 3/4 (f(10) = 0.178, f(50) = 0.595, f(100) = 1).
#Skip-gram as Matrix Factorisation
Word2Vec and GloVe look like different methods, but Levy and Goldberg (2014) proved a link: skip-gram with negative sampling quietly factorises a matrix of pointwise mutual information (PMI) numbers. PMI measures how much more often a word and a context occur together than chance would predict, and it is derived in Information Theory & Entropy. Write #(w, c) for the count of the pair, #(w) and #(c) for the counts of each word, and |D| for the total number of pairs. Open the derivation to see what the best dot product is.
This is why skip-gram and GloVe produce similar vectors: both factorise a matrix of logarithms of co-occurrence statistics. The skip-gram matrix is shifted PMI, the GloVe matrix is the log counts with biases.
Change the window and k in the lab below, then check the PMI of one pair by hand: cat and dog, or king and queen, should land close together once their PMI is above 0.
#The Embedding Layer in Neural Networks
#Step 1: Build an Embedding Table
Create a matrix of shape [vocabulary_size x embedding_dim]. For a 50,000-word vocabulary with 512-dimensional embeddings, that is a 50,000 x 512 matrix. Each row corresponds to one word's embedding vector. Initially, all values are random.
#Step 2: Look Up Word Vectors
When a word enters the model, its token ID is used as an index to look up the corresponding row in the embedding table. The word "cat" (token ID 3421) retrieves row 3421 from the matrix. This lookup is just a table indexing operation — no multiplication needed.
#Step 3: Train with Backpropagation
As the full model trains on its task (translation, classification, generation), gradients flow back into the embedding table. Each word's vector is nudged to better serve the downstream task. Words that behave similarly in context gradually develop similar vectors.
#Step 4: Task-Specific Representations
Unlike generic Word2Vec embeddings, these learned embeddings are optimized for the specific task. A sentiment analysis model might learn embeddings where "great" and "wonderful" are close. A medical model might learn embeddings where "aspirin" and "ibuprofen" are close.
How many numbers does the model store? Each of the V words has an input vector in the table E and, for a model that predicts words, an output vector as well. Open the derivation to count them. (The one-hot product that equals a row lookup is derived in Embeddings: Categorical to Word2Vec.)
Models that tie the input and output tables, as noted in the Architect View later in this lesson, store only V d.
#How Transformers Use Embeddings
In a transformer (like GPT or BERT), the embedding layer is the very first component:
- Tokenize the input text into token IDs: "The cat sat" → [464, 3797, 3332]
- Look up each token's embedding vector from the embedding table
- Add positional encoding so the model knows token order
- Feed the resulting vectors into the transformer layers
The embedding table is learned end-to-end during training. By the time a model like GPT-4 finishes training on trillions of tokens, its embedding table contains incredibly rich representations of every token in its vocabulary.
#Measuring Similarity: Cosine Similarity
#Interactive: Explore Word Embeddings
Explore how words cluster in embedding space. Related words form tight groups — animals cluster together, countries cluster together, verbs cluster together. Try searching for specific words and see which neighbors appear. Notice that the clusters capture meaning, not spelling — "good" is near "great" and "excellent", not near "food" or "hood".
#Try It Yourself
#Key Takeaways
- One-hot encoding fails for language. It produces sparse, high-dimensional vectors with no notion of similarity between words.
- Word2Vec learns meaningful vectors from context. CBOW predicts a word from its neighbors and Skip-gram predicts neighbors from a word. Both learn that words in similar contexts get similar vectors.
- GloVe factorizes a global word co-occurrence matrix into dense vectors, with similar quality to Word2Vec.
- Word arithmetic reveals learned structure: relationships like gender, geography, and tense are encoded as consistent vector directions (king - man + woman ≈ queen).
- Neural networks use learnable embedding layers. Instead of pre-trained vectors, modern models learn task-specific embeddings end-to-end via backpropagation.
- Cosine similarity, the cosine of the angle between two embedding vectors, tells you how similar their meanings are.
#Quick Check
Why does one-hot encoding fail as a word representation for NLP?