S30 Logo
S30 AI Labwww.thes30.com
Back
#40

Embeddings & Representation

Hard๐Ÿ“ NLP & TransformersW9 D1

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

MethodHow embeddings are obtained
PPMI + SVDMatrix factorization
Word2VecPrediction task
GPTGradient 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 word j appears near center word i
  • โ—P(i) = marginal probability of seeing i
  • โ—P(j) = marginal probability of seeing j

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.

MethodLearns fromMechanismIntuition
PPMI + SVDglobal co-occurrence countsmatrix factorizationcompress the corpus statistics
SGNSlocal context pairsprediction + negative samplinglearn 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?

Python 3 โ€” Notebook
0/11 solvedSubstack Notes
1
Dataset & Setup

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.

Loading editor...
1

Tokenization + vocabulary

2
Implement `tokenize` + `build_vocab` (UNK at id 0).
1

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).

Loading editor...
2

Co-occurrence matrix

3
Implement `word_id` and `build_cooccurrence` with sliding window.
1

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.

Loading editor...
3

PMI / PPMI

4
Implement `ppmi(C)` returning a non-negative matrix.
1

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).

Loading editor...
4

SVD embeddings

5
Implement `svd_embeddings(M, k)` and verify embedding shape.

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).

Loading editor...
6
Task 3.2 โ€” Similarity via cosine nearest neighbors.

Task 3.2 โ€” Similarity

Implement cosine similarity and nearest neighbors for a query word.

Loading editor...
7
Task 3.3 โ€” Analogy on SVD embeddings (bridge).

Task 3.3 โ€” Analogy bridge

Implement analogy(a,b,c,E) and test on SVD embeddings before SGNS.

Loading editor...
5

Skip-gram with Negative Sampling (SGNS)

8
Create training pairs `(center_id, context_id)` from a windowed corpus.
2

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.

Loading editor...
9
Implement negative sampling CDF and sampler.
1

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.

Loading editor...
10
Train SGNS embeddings.

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
Loading editor...
6

Tiny analogy checks

11
Compare analogy behavior on SVD vs SGNS embeddings.

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.

Loading editor...

Need help? Share feedback