Before You Start
- Required knowledge
- Tokenization, matrix multiplication, SVD, sigmoid, and gradient descent.
- Libraries used
- NumPy
- Dataset and source
- An embedded toy text corpus used to build word-context counts and skip-gram pairs.
- Expected output
- PPMI/SVD embeddings, cosine neighbors and analogies, plus trained SGNS embeddings with negative sampling.
Embeddings & Representation Learning โ Theory & Concepts
Read this before attempting the exercises. This lab is about how dense word vectors emerge from context statistics, first with a count-based pipeline and then with a predictive one.
Quick Map
| Method | How embeddings are obtained |
|---|---|
| PPMI + SVD | Matrix factorization |
| Word2Vec | Prediction task |
| GPT | Gradient descent inside a Transformer |
Bigger NLP Representation Pipeline
Bag of Words
-> TF-IDF
-> PPMI + SVD
-> Word2Vec / GloVe
-> Contextual embeddings
-> Transformers
This is the broader progression of text representations:
- โ
Bag of Words,TF-IDF: sparse classical features - โ
PPMI + SVD,Word2Vec,GloVe: dense static embeddings - โ
Contextual embeddings,Transformers: token meaning depends on surrounding context
PPMI + SVD
Corpus
-> Co-occurrence Matrix
-> PPMI
-> SVD
-> Embeddings
Word2Vec SGNS
Corpus
-> (center, context) pairs
-> Negative sampling
-> Gradient updates
-> Embeddings
1. Why embeddings instead of one-hot vectors?
One-hot vectors tell the model only that two tokens are different. They do not express that king and queen are more related than king and banana.
one-hot("king") = [0, 0, 0, ..., 1, ..., 0]
one-hot("queen") = [0, 1, 0, ..., 0, ..., 0]
Their dot product is zero unless the words are identical.
An embedding maps each token to a short dense vector:
king -> [ 0.42, -0.11, 0.77, ... ]
queen -> [ 0.39, -0.08, 0.74, ... ]
Now similarity can be expressed geometrically: nearby vectors often correspond to words used in similar contexts.
2. The central idea: distributional semantics
The lab follows the distributional hypothesis:
Words that appear in similar contexts tend to have similar meanings.
Example:
the king ruled the kingdom
the queen ruled the kingdom
king and queen appear near similar surrounding words, so a good representation should place them near each other.
3. Count-based embeddings in this lab
The first half of the notebook builds embeddings from explicit corpus statistics:
corpus
-> token counts
-> co-occurrence matrix C
-> PPMI matrix M
-> low-rank SVD
-> dense embedding matrix E_svd
Pipeline summary:
PPMI + SVD
Corpus
-> Co-occurrence Matrix
-> PPMI
-> SVD
-> Embeddings
Co-occurrence
For each center word, count which words appear within a small window around it.
Why PMI / PPMI?
Raw counts overvalue frequent words like the or and.
PMI stands for Pointwise Mutual Information.
PMI rescales a pair (i, j) by comparing:
observed co-occurrence
vs
expected co-occurrence if i and j were independent
Formally:
PMI(i,j) = log( P(i,j) / (P(i) P(j)) )
PPMI(i,j) = max(PMI(i,j), 0)
Here:
- โ
P(i,j)= probability that context wordjappears near center wordi - โ
P(i)= marginal probability of seeingi - โ
P(j)= marginal probability of seeingj
If P(i,j) is much larger than P(i)P(j), then the pair occurs together more often than chance would predict, so PMI is positive.
If it is smaller, PMI is negative.
PPMI keeps only positive values:
PPMI(i,j) = max(PMI(i,j), 0)
This is the core idea behind PPMI: keep only the positive surprises and discard the negative ones.
That usually gives a cleaner signal than raw counts on small corpora.
Why SVD?
PPMI is still a large sparse matrix. SVD compresses it into a low-dimensional dense space:
M โ U S V^T
Using the top k singular directions gives a compact embedding per word. Intuitively, this keeps the strongest co-occurrence structure and drops noise.
4. Predictive embeddings in this lab: SGNS
The second half of the notebook switches from matrix factorization to prediction.
Skip-gram with Negative Sampling (SGNS) learns embeddings by solving a local discrimination problem:
- โmake real
(center, context)pairs score high - โmake randomly sampled negative pairs score low
Pipeline summary:
Word2Vec SGNS
Corpus
-> (center, context) pairs
-> Negative sampling
-> Gradient updates
-> Embeddings
Training objective intuition:
real pair -> large dot product
fake pair -> small dot product
For a center embedding u_c and context embedding v_w:
maximize log ฯ(u_c ยท v_pos) + ฮฃ log ฯ(-u_c ยท v_neg)
This is why SGNS is called a predictive method: the vector is useful if it helps predict which nearby words are likely.
5. Count-based vs predictive: what to notice
This is the main comparison in the lab.
| Method | Learns from | Mechanism | Intuition |
|---|---|---|---|
| PPMI + SVD | global co-occurrence counts | matrix factorization | compress the corpus statistics |
| SGNS | local context pairs | prediction + negative sampling | learn vectors that separate true vs fake contexts |
Both can produce meaningful neighborhoods such as:
nearest_neighbors("king")
but the route is different:
- โSVD starts from a full co-occurrence table, then compresses it
- โSGNS starts from sampled training pairs and updates vectors directly
6. Cosine similarity and nearest neighbors
Magnitude is often less informative than direction for embeddings, so the lab normalizes rows and uses cosine similarity:
cos(a, b) = (a ยท b) / (||a|| ||b||)
This is why a nearest-neighbor query typically means:
Which other words point in a similar direction in embedding space?
7. Why analogies are in the lab
The notebook also tests a toy analogy:
king - man + woman
This is not a rigorous benchmark. It is a quick diagnostic for whether vector offsets capture some relational structure.
Use it as a sanity check, not as proof that one embedding method is universally better.
8. What students should take away
By the end of this lab, the important mental model is:
- โembeddings are dense representations learned from context
- โcount-based methods build a matrix first, then compress it
- โpredictive methods learn vectors directly by optimizing a training objective
- โcosine neighbors and analogy probes are ways to inspect the learned geometry
This lab is the bridge from classical sparse NLP features to learned representations used in modern deep learning.
Ready to practice?
Embeddings & Representation โ Student Lab
You will implement classic embedding methods offline:
- โco-occurrence matrices
- โPMI / PPMI
- โSVD embeddings
- โskip-gram with negative sampling (Word2Vec-style)
Focus: correctness, determinism, and interview-ready intuition.
Corpus (offline)
We use a 52-sentence corpus with repeated semantic patterns so embeddings have enough signal for similarity and analogy checks.
Tokenization + vocabulary
Section 0 โ Tokenization + vocabulary
Task 0.1
Implement tokenize(s) that extracts lowercase alphabetic tokens.
Hint: regex [a-z]+.
Task 0.2
Build vocab with min_count and reserve id 0 for UNK.
Return (word2id, id2word, counts).
Co-occurrence matrix
Section 1 โ Co-occurrence matrix
We build a target-context co-occurrence matrix C with a sliding window.
Task 1.1
Implement build_cooccurrence(texts, word2id, window=2) returning C of shape (V,V).
Count context words within +/- window positions (excluding the center token).
FAANG gotcha: for large corpora, this should be sparse; we use dense here for simplicity.
PMI / PPMI
Section 2 โ PMI / PPMI
PMI stands for Pointwise Mutual Information.
PMI(i,j) = log( P(i,j) / (P(i) P(j)) ). PPMI(i,j) = max(PMI(i,j), 0).
Intuition: PMI measures how much more often two words occur together than chance would predict. If a pair appears together more than expected, PMI is positive. If it appears less than expected, PMI is negative. PPMI keeps only the positive values, which is the core idea behind PPMI.
Task 2.1
Implement ppmi(C) returning a matrix same shape as C.
Use smoothing to avoid log(0).
SVD embeddings
Section 3 โ SVD embeddings
We compute low-rank embeddings from PPMI.
Task 3.1
Implement svd_embeddings(M, k) returning E of shape (V,k).
Use np.linalg.svd (dense).
Task 3.2 โ Similarity
Implement cosine similarity and nearest neighbors for a query word.
Task 3.3 โ Analogy bridge
Implement analogy(a,b,c,E) and test on SVD embeddings before SGNS.
Skip-gram with Negative Sampling (SGNS)
Section 4 โ Skip-gram with Negative Sampling (SGNS)
We train center and context embeddings so that true (center,context) pairs have high dot-product.
Task 4.1
Create training pairs (center_id, context_id) from the corpus for a given window.
Return arrays centers, contexts.
Task 4.2
Implement negative sampling distribution p(w) รขยย count(w)^{0.75} and a sampler.
Hint: build a CDF and sample with rng.random + np.searchsorted.
Task 4.3
Train SGNS embeddings.
Implement:
- โ
sigmoid - โone SGD step for a (center, context) positive pair and K negatives
Hints:
- โmaximize
log ฯ(u_c ยท v_pos) + ฮฃ log ฯ(-u_c ยท v_neg) - โuse gradients on dot products
- โkeep learning rate small
Tiny analogy checks
Section 5 โ Tiny analogy checks
We already implemented analogy(...) above. Now use it to compare count-based and predictive embeddings on the same toy relation.
Task 5.1
Run the same analogy on both E_svd and E_sgns, then inspect whether the nearest neighbors look similar or different.