Word embeddings (Word2Vec, GloVe)
Overview
Word embeddings are dense, low-dimensional vector representations of words that capture semantic meaning and relationships in continuous space. Unlike one-hot encodings (sparse, high-dimensional, no semantic info), embeddings place similar words close together in vector space.

Why Word Embeddings?
The problem with one-hot encoding:
- Vocabulary of 50,000 words → 50,000-dimensional vectors
- Every word equally distant from every other word (no semantic similarity)
- "cat" and "dog" are as different as "cat" and "democracy
What embedings fix:
- Dense representation: 50-300 dimensions instead of 50,000
- Semantic similarity: Similar words have similar vectors (measured by cosine similarity)
- Compositionality: Vector operations capture meaning relationships
- Transferability: Pre-train on large corpus, use in downstream tasks
Word2Vec: Learning from Context
Word2Vec has two architectures:
1. CBOW (Continuous Bag of Words)
CBOW predicts a target word from its surrounding context words.
How it works:
-
Input Layer: One-hot vectors for context words
-
Hidden Layer: Average the context word embedings where is context window size, is embedding for word
-
Output Layer: Compute scores for all vocabulary words where is output embedding for word
-
Softmax: Convert scores to probabilities
Why this works: Words that appear in similar contexts get pushed to similar embedding vectors.
Derivation from first principles:
- Start with goal: maximize probability of observing the corpus
- Corpus probability:
- Take log (turn product into sum):
- Minimize negative log-likelihood (equivalent to maximizing likelihood)
- Normalize by corpus length for stability
2. Skip-gram
Skip-gram does the reverse: predicts context words given a target word.
How it works:
- Input: One-hot vector for target word
- Hidden Layer: Just the target word embedding (no averaging)
- Output: Predict each context word independently
Why Skip-gram often works better: Each target word generates multiple training examples (one per context position), so rare words get more updates.
Computational Challenge: Softmax is Expensive
The denominator requires computing scores for all vocabulary words (often 50,000+) at every training step.
Solution 1: Hierarchical Softmax
Replace flat softmax with a binary tree (Huffman tree):
- Each word is a leaf
- To predict a word, traverse the tree (log₂|V| binary decisions instead of |V| comparisons)
- Probability of a word = product of probabilities along its path
Complexity: instead of
Solution 2: Negative Sampling
Negative sampling turns the problem into binary classification: "Is this word-context pair real or fake?"
The trick:
- For each real (target, context) pair, sample random "negative" words (5-20 typically)
- Train to distinguish real pair from negative pairs using logistic regression
Derivation:
- = probability real pair is real (should be high)
- = probability fake pair is fake (should be high)
- Negative samples drawn from noise distribution (smoothed unigram)
- Why ? Balances frequent vs. rare words—without smoothing, would only sample common words
Complexity: where
GloVe: Global Vectors for Word Representation
Word2Vec is local (looks at small context windows). GloVe is global (uses corpus-wide co-occurrence statistics).
Consider words "ice" and "steam", and context words "solid" vs. "gas":
- is high, is low → ratio is large
- is low, is high → ratio is small
- For unrelated words like "fashion", both probabilities are low → ratio ≈ 1
The idea: Word vectors should encode these ratios.
GloVe Model
Define:
- = total count of all words in context of word
- = probability of word appearing in context of
Goal: Find embedding vectors such that their dot product relates to log co-occurrence.
Components explained:
- : word embedding for word
- : context embedding for word
- : bias terms for each word
- : weighting function to handle zero and rare co-occurrences
Why this weighting?
- : Don't train on word pairs that never co-occur (would contribute infinite loss with log(0))
- for rare pairs: Rare co-occurrences are noisy, downweight them
- for frequent pairs: Cap the weight so very frequent pairs don't dominate
Derivation from ratio insight:
Start with goal: should relate to ratios.
- Ratio form: where is some function
- Since we want vectors, use dot products:
- Homorphism: suggests
- So:
- Take log:
- Absorb into bias:
- Distinguish word vs. context embedings (breaks symmetry for training):
- Minimize squared error with weighting: the loss function above
Example 1: CBOW Forward Pass
Sentence: "The cat sat on the mat" Task: Predict "sat" from context ["cat", "on"] (window size = 1) Vocabulary: {the, cat, sat, on, mat} (size5) Embedding dimension: 3
Step 1: Get context embeddings
Embedding matrix E (5 × 3):
"cat" → [0.2, 0.5, 0.1]
"on" → [0.3, 0.4, 0.2]
Step 2: Average context embeddings Why average? Represents the "central meaning" of the context, order-invariant.
Step 3: Compute output scores
Output matrix W_out (3 × 5):
Scores = W_out^T · h
"the": [0.1, 0.2, 0.3]^T · [0.25, 0.45, 0.15] = 0.025 + 0.09 + 0.045 = 0.16
"cat": [...]^T · h = 0.21
"sat": [...]^T · h = 0.42 ← highest score
"on": [...]^T · h = 0.18
"mat": [...]^T · h = 0.14
Why dot product? Measures alignment between context representation and candidate word.
Step 4: Softmax
Why softmax? Converts scores to valid probability distribution (sums to 1).
Example 2: Negative Sampling
Positive pair: (target="cat", context="sat") Task: Train embedings using negative sampling with negatives
Step 1: Compute positive score
v_cat = [0.2, 0.5, 0.1] (target embedding)
u_sat = [0.3, 0.4, 0.2] (context embedding)
score_pos = v_cat · u_sat = 0.06+ 0.20 + 0.02 = 0.28
Step 2: Sample negative words Sample 2 random words NOT in context: "the", "mat"
u_the = [0.1, 0.2, 0.3]
u_mat = [0.4, 0.1, 0.2]
score_neg1 = v_cat · u_the = 0.02 + 0.10 + 0.03 = 0.15
score_neg2 = v_cat · u_mat = 0.08 + 0.05 + 0.02 = 0.15
Why random sampling? Efficient approximation of the full vocabulary.
Step 3: Compute loss Interpretation: Positive pair should have high score (close to 1 after sigmoid), negatives should have low score.
Step 4: Gradient update
∂L/∂v_cat pushes v_cat closer to u_sat (positive context)
∂L/∂v_cat pushes v_cat away from u_the, u_mat (negative contexts)
Result: "cat" embedding moves toward words that actually appear near it, away from unrelated words.
Example 3: GloVe Training
Mini co-occurrence matrix:
cat sat mat
dog 5 2 3
cat 08 4
: "cat" appears in context of "dog" 5 times in corpus.
Training pair: (dog, cat) with
Current embedings:
w_dog = [0.5, 0.3]
w̃_cat = [0.4, 0.6]
b_dog = 0.1
b̃_cat = 0.2
Step 1: Compute prediction Why exponent? We're modeling log co-occurrence, so exp converts back to count scale.
Step 2: Compute loss for this pair Why squared error? Simple, differentiable objective that drives predicted log-count toward actual log-count.
Step 3: Update embeddings Gradient pushes and to make their dot product closer to .
After many updates: Words that co-occur frequently will have high dot products, rarely co-occurring words will have low dot products.
Properties of Trained Embeddings
Semantic Similarity
Cosine similarity between embedings captures meaning:
Similar words have similarity close to 1:
- cos(king, queen) ≈ 0.8
- cos(cat, dog) ≈ 0.76
Analogies
Vector arithmetic captures relationships:
Why this works:
- = "royalty" direction (removes "maleness")
- Adding projects onto female royalty
Other examples:
- Paris - France + Italy≈ Rome (capital of...)
- walking - walked + saw ≈ seeing (verb tense)
Clustering
Words cluster by semantic category in embedding space:
- Animals cluster together
- Countries cluster together
- Verbs cluster by aspect/tense
Word2Vec vs. GloVe
| Aspect | Word2Vec (Skip-gram) | GloVe |
|---|---|---|
| Learning type | Predictive (neural network) | Count-based (matrix factorization-like) |
| Uses | Local context windows | Global co-occurrence statistics |
| Training | Stochastic, online | Batch, full corpus |
| Scalability | Fast, can train online | Requires building co-occurrence matrix first |
| Performance | Slightly better on analogies | Slightly better on similarity |
| Rare words | Can struggle (few training examples) | Benefits from global statistics |
In practice: Both produce high-quality embeddings. Word2Vec (especially Skip-gram with negative sampling) is more popular due to speed. GloVe is preferred when you want explicit control over global statistics.
The mistake: "Since 'bank' (financial) and 'bank' (river) are the same word, they'll have the same embedding. Perfect!"
Why it feels right: One word = one vector seems natural.
The problem: Word2Vec and GloVe learn one vector per word type, averaging over all contexts where that word appears. Polysemous words (multiple meanings) get mudy embedings.
The fix:
- Use contextualized embeddings (ELMo, BERT) where "bank" gets different vectors based on context
- Or use sense2vec which clusters word contexts into separatenses
The mistake: Training Word2Vec on 10,000 sentences and expecting good embedings.
Why it feels right: "Deep learning works on small data if I tune carefully."
The problem: Word embedings need millions of word occurrences to capture statistical patterns. With small data:
- Rare words have unreliable embedings (few training examples)
- Semantic relationships are noisy
- Analogies don't work well
The fix:
- Use pre-trained embeddings (trained on billions of words: Google News, Wikipedia, Common Crawl)
- Fine-tune pre-trained embeddings on your domain if needed
- Or use subword embedings (FastText) which handle rare words better
The mistake: Computing to measure similarity.
Why it feels right: "Bigger dot product = more similar."
The problem: Dot product is affected by vector magnitude, not just direction. A word with high-magnitude embedding (perhaps because it's very frequent) will have high dot products with everything.
The fix: Always use cosine similarity (normalized dot product): This measures angle between vectors, independent of magnitude.
Recall Explain to a 12-year-old
Imagine you have a magic map where every word is a dot. Words that mean similar things are close together—so "happy" is near "joyful", and "cat" is near "dog". Words that mean opposite things are far apart.
Now here's the really cool part: you can do math with meanings! If you go from the dot for "king" to the dot for "man", you're moving in the "this is a male person" direction. If you then go the opposite way to "woman", you'll end up near "queen"! It's like meaning has directions you can walk in.
How do we build this map? We read a LOT of sentences (like, millions) and notice which words appear near each other. If "dog" and "bark" appear in the same sentences often, we put them close on the map. If "dog" and "telephone" never appear together, we put them far apart. The computer figures out where to put every word so that the map makes sense with all those patterns.
That's a word embedding—a map where word positions tell you what they mean!
Skip-gram = Skip the target, get the neighbors Predict context from middle word (looks "outward")
GloVe = Global Vectors Uses Global co-occurrence Vectors (not local windows)
Connections
- One-hot encoding ← what embedings replace
- Cosine similarity ← measuring semantic similarity
- Softmax function ← converting scores to probabilities
- Backpropagation ← how embedings are trained
- Transfer learning ← using pre-trained embeddings
- LSTM / GRU ← often use word embeddings as input
- Attention mechanism ← can replace fixed embedings with context-dependent ones
- BERT ← modern contextualized embeddings
- Subword tokenization ← handles rare words and morphology
- t-SNE ← visualizing high-dimensional embeddings in 2D
#flashcards/ai-ml
What are word embeddings? :: Dense, low-dimensional vector representations of words that capture semantic meaning and relationships in continuous space (typically 50-300 dimensions).
What is the key advantage of embedings over one-hot encoding?
What does CBOW stand for and what does it predict?
What does Skip-gram predict?
Why is Skip-gram often better than CBOW?
What computational problem does negative sampling solve?
Write the negative sampling loss function for one training example :: where is target, is context, are k negative samples.
What is the key insight behind GloVe?
Write the GloVe objective function :: where is co-occurrence count and is a weighting function.
What does the weighting function do in GloVe?
What famous property allows vector arithmetic with embedings?
How do you properly measure similarity between two embeddings?
What problem do standard word embeddings have with polysemy?
How does hierarchical softmax reduce computational cost?
Why does negative sampling use the distribution ?
What is the difference between Word2Vec and GloVe training?
How much training data do word embeddings typically need?
What is the typical dimensionality of word embeddings? :: 50-300 dimensions, balancing expressiveness and computational efficiency. Common choices: 100, 200, 300.
Why do we need separate word and context embeddings in Word2Vec?
What does represent in the GloVe co-occurrence matrix?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Chalo, is note ka core intuition samajhte hain. Sabse pehle problem yeh thi ki computer ke liye words ko represent karna mushkil hai. Purana tareeka tha one-hot encoding, jisme har word ek bahut lambi vector banti thi (50,000 words matlab 50,000 dimensions!), aur sabse badi dikkat yeh thi ki isme meaning ka koi concept hi nahi tha — "cat" aur "dog" utne hi alag lagte the jitne "cat" aur "democracy". Word embeddings yeh problem solve karti hai: yeh words ko chhote, dense vectors (bas 50-300 dimensions) mein badalti hai jaha similar meaning wale words ek doosre ke paas hote hain ek "meaning-space" mein. Iski sabse cool cheez yeh hai ki aap vector arithmetic kar sakte ho — jaise "king" - "man" + "woman" ≈ "queen"!
Ab yeh embeddings seekhte kaise hain? Simple idea: ek word ka meaning uske aas-paas aane wale words se pata chalta hai (context se). Word2Vec ke do tareeke hain. CBOW mein hum context words (aas-paas ke words) se target word predict karte hain, matlab surrounding words ki embeddings ko average karke beech ka word guess karte hain. Skip-gram ulta karta hai — ek target word de kar uske aas-paas ke context words predict karta hai. Jo words similar contexts mein aate hain, unki embeddings automatically similar ho jaati hain. Skip-gram often better kaam karta hai kyunki har word se multiple training examples bante hain, toh rare words ko bhi zyada seekhne ka mauka milta hai.
Yeh sab matter kyun karta hai? Kyunki ek baar aap embeddings ko ek bade text corpus par pre-train kar lete ho, toh aap unhe kisi bhi downstream task (jaise sentiment analysis, translation, chatbots) mein reuse kar sakte ho — yeh transferability hai. Yeh foundation hai modern NLP aur bade language models ka. Ek chhota computational challenge yeh hai ki softmax calculate karna mehnga hai (kyunki denominator mein saare vocabulary words ke scores chahiye), isliye Hierarchical Softmax jaise smart tricks use kiye jaate hain speed ke liye. Overall, embeddings ne machines ko words ka "meaning" samajhna sikhaya, jo aaj ke har AI language system ki jaan hai.