Word embeddings (Word2Vec, GloVe)
3.5.11· AI-ML › Sequence Models
Overview
Word embeddings dense, low-dimensional vector representations hain words ki, jo continuous space mein semantic meaning aur relationships capture karte hain. One-hot encodings (sparse, high-dimensional, koi semantic info nahi) ke unlike, embeddings similar words ko vector space mein paas-paas rakhte hain.

Why Word Embeddings?
One-hot encoding ke saath problem:
- 50,000 words ki vocabulary → 50,000-dimensional vectors
- Har word har doosre word se equally door (koi semantic similarity nahi)
- "cat" aur "dog" utne hi different hain jitne "cat" aur "democracy"
Embeddings kya fix karte hain:
- Dense representation: 50,000 ki jagah 50-300 dimensions
- Semantic similarity: Similar words ke similar vectors hote hain (cosine similarity se measure hota hai)
- Compositionality: Vector operations meaning relationships capture karte hain
- Transferability: Large corpus par pre-train karo, downstream tasks mein use karo
Word2Vec: Learning from Context
Word2Vec ke do architectures hain:
1. CBOW (Continuous Bag of Words)
CBOW apne surrounding context words se ek target word predict karta hai.
Ye kaise kaam karta hai:
-
Input Layer: Context words ke liye one-hot vectors
-
Hidden Layer: Context word embeddings ka average nikalo jahan context window size hai, word ka embedding hai
-
Output Layer: Saare vocabulary words ke liye scores compute karo jahan word ka output embedding hai
-
Softmax: Scores ko probabilities mein convert karo
Ye kyu kaam karta hai: Jo words similar contexts mein appear hote hain unhe similar embedding vectors ki taraf push kiya jaata hai.
First principles se derivation:
- Shuru karo goal se: corpus observe karne ki probability maximize karo
- Corpus probability:
- Log lo (product ko sum mein convert karo):
- Negative log-likelihood minimize karo (likelihood maximize karne ke equivalent hai)
- Stability ke liye corpus length se normalize karo
2. Skip-gram
Skip-gram ulta karta hai: ek target word diya hua ho toh context words predict karta hai.
Ye kaise kaam karta hai:
- Input: Target word ke liye one-hot vector
- Hidden Layer: Sirf target word embedding (koi averaging nahi)
- Output: Har context word ko independently predict karo
Skip-gram aksar better kyu kaam karta hai: Har target word multiple training examples generate karta hai (ek har context position ke liye), isliye rare words ko zyada updates milte hain.
Computational Challenge: Softmax is Expensive
Denominator ko saare vocabulary words (often 50,000+) ke liye scores compute karne padte hain har training step par.
Solution 1: Hierarchical Softmax
Flat softmax ko ek binary tree (Huffman tree) se replace karo:
- Har word ek leaf hai
- Ek word predict karne ke liye, tree traverse karo (|V| comparisons ki jagah log₂|V| binary decisions)
- Ek word ki probability = uske path ke saath probabilities ka product
Complexity: ki jagah
Solution 2: Negative Sampling
Negative sampling problem ko binary classification mein badal deta hai: "Kya ye word-context pair real hai ya fake?"
Trick:
- Har real (target, context) pair ke liye, random "negative" words sample karo (typically 5-20)
- Logistic regression use karke real pair ko negative pairs se distinguish karna seekho
Derivation:
- = probability ki real pair real hai (high honi chahiye)
- = probability ki fake pair fake hai (high honi chahiye)
- Negative samples noise distribution se draw kiye jaate hain (smoothed unigram)
- kyu? Frequent vs. rare words ko balance karta hai—smoothing ke bina, sirf common words sample honge
Complexity: jahan
GloVe: Global Vectors for Word Representation
Word2Vec local hai (chhote context windows dekhta hai). GloVe global hai (corpus-wide co-occurrence statistics use karta hai).
"Ice" aur "steam" words socho, aur context words "solid" vs. "gas":
- high hai, low hai → ratio bada hai
- low hai, high hai → ratio chota hai
- "Fashion" jaise unrelated words ke liye, dono probabilities low hain → ratio ≈ 1
Idea: Word vectors ko ye ratios encode karne chahiye.
GloVe Model
Define karo:
- = word ke context mein saare words ka total count
- = probability ki word , word ke context mein appear hoga
Goal: Aise embedding vectors dhundho jinka dot product log co-occurrence se relate kare.
Components explained:
- : word ke liye word embedding
- : word ke liye context embedding
- : har word ke liye bias terms
- : zero aur rare co-occurrences handle karne ke liye weighting function
Ye weighting kyu?
- : Aise word pairs par train mat karo jo kabhi co-occur nahi hue (log(0) ke saath infinite loss contribute karte)
- rare pairs ke liye: Rare co-occurrences noisy hoti hain, unhe downweight karo
- frequent pairs ke liye: Weight ko cap karo taaki bahut frequent pairs dominate na karein
Ratio insight se derivation:
Shuru karo goal se: ko ratios se relate hona chahiye.
- Ratio form: jahan koi function hai
- Kyunki hum vectors chahte hain, dot products use karo:
- Homomorphism: suggest karta hai
- Toh:
- Log lo:
- ko bias mein absorb karo:
- Word vs. context embeddings alag karo (training ke liye symmetry todta hai):
- Weighting ke saath squared error minimize karo: upar wala loss function
Example 1: CBOW Forward Pass
Sentence: "The cat sat on the mat" Task: "sat" predict karo context ["cat", "on"] se (window size = 1) Vocabulary: {the, cat, sat, on, mat} (size 5) Embedding dimension: 3
Step 1: Context embeddings lo
Embedding matrix E (5 × 3):
"cat" → [0.2, 0.5, 0.1]
"on" → [0.3, 0.4, 0.2]
Step 2: Context embeddings ka average nikalo Average kyu? Context ka "central meaning" represent karta hai, order-invariant.
Step 3: Output scores compute karo
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
Dot product kyu? Context representation aur candidate word ke beech alignment measure karta hai.
Step 4: Softmax
Softmax kyu? Scores ko valid probability distribution mein convert karta hai (sum 1 hota hai).
Example 2: Negative Sampling
Positive pair: (target="cat", context="sat") Task: negatives ke saath negative sampling use karke embeddings train karo
Step 1: Positive score compute karo
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: Negative words sample karo Context mein nahi hain aise 2 random words sample karo: "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
Random sampling kyu? Puri vocabulary ka efficient approximation hai.
Step 3: Loss compute karo Interpretation: Positive pair ka score high hona chahiye (sigmoid ke baad 1 ke paas), negatives ka low hona chahiye.
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 un words ki taraf move karta hai jo actually uske paas appear hote hain, unrelated words se door.
Example 3: GloVe Training
Mini co-occurrence matrix:
cat sat mat
dog 5 2 3
cat 08 4
: "cat" corpus mein "dog" ke context mein 5 baar appear hua.
Training pair: (dog, cat) with
Current embeddings:
w_dog = [0.5, 0.3]
w̃_cat = [0.4, 0.6]
b_dog = 0.1
b̃_cat = 0.2
Step 1: Prediction compute karo Exponent kyu? Hum log co-occurrence model kar rahe hain, toh exp count scale par wapas convert karta hai.
Step 2: Is pair ke liye loss compute karo Squared error kyu? Simple, differentiable objective jo predicted log-count ko actual log-count ki taraf drive karta hai.
Step 3: Embeddings update karo Gradient aur ko push karta hai taaki unka dot product ke paas aaye.
Kai updates ke baad: Jo words frequently co-occur hote hain unke high dot products honge, rarely co-occur hone wale words ke low dot products honge.
Properties of Trained Embeddings
Semantic Similarity
Embeddings ke beech cosine similarity meaning capture karti hai:
Similar words ki similarity 1 ke paas hoti hai:
- cos(king, queen) ≈ 0.8
- cos(cat, dog) ≈ 0.76
Analogies
Vector arithmetic relationships capture karta hai:
Ye kyu kaam karta hai:
- = "royalty" direction ("maleness" remove karta hai)
- add karna female royalty par project karta hai
Doosre examples:
- Paris - France + Italy ≈ Rome (capital of...)
- walking - walked + saw ≈ seeing (verb tense)
Clustering
Words embedding space mein semantic category ke hisaab se cluster karte hain:
- Animals saath cluster karte hain
- Countries saath cluster karte hain
- Verbs aspect/tense ke hisaab se cluster karte hain
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, online train ho sakta hai | Pehle co-occurrence matrix banana padta hai |
| Performance | Analogies par thoda better | Similarity par thoda better |
| Rare words | Struggle kar sakta hai (few training examples) | Global statistics se benefit hota hai |
Practice mein: Dono high-quality embeddings produce karte hain. Word2Vec (especially Skip-gram with negative sampling) speed ki wajah se zyada popular hai. GloVe prefer hota hai jab global statistics par explicit control chahiye ho.
Galti: "'bank' (financial) aur 'bank' (river) same word hain, toh unka same embedding hoga. Perfect!"
Kyu sahi lagta hai: Ek word = ek vector natural lagta hai.
Problem: Word2Vec aur GloVe har word type ke liye ek vector seekhte hain, un saare contexts ka average lekar jahan wo word appear hota hai. Polysemous words (multiple meanings) ke muddy embeddings ho jaate hain.
Fix:
- Contextualized embeddings use karo (ELMo, BERT) jahan "bank" ko context ke hisaab se alag vectors milte hain
- Ya sense2vec use karo jo word contexts ko alag senses mein cluster karta hai
Galti: Word2Vec ko 10,000 sentences par train karna aur achhe embeddings expect karna.
Kyu sahi lagta hai: "Deep learning chhote data par bhi kaam karta hai agar carefully tune karun."
Problem: Word embeddings ko statistical patterns capture karne ke liye millions of word occurrences chahiye. Chhote data ke saath:
- Rare words ke embeddings unreliable hote hain (few training examples)
- Semantic relationships noisy hoti hain
- Analogies achhe se kaam nahi karti
Fix:
- Pre-trained embeddings use karo (billions of words par trained: Google News, Wikipedia, Common Crawl)
- Agar zaroorat ho toh apne domain par pre-trained embeddings fine-tune karo
- Ya subword embeddings (FastText) use karo jo rare words ko better handle karta hai
Galti: Similarity measure karne ke liye compute karna.
Kyu sahi lagta hai: "Bada dot product = zyada similar."
Problem: Dot product vector magnitude se affect hota hai, sirf direction se nahi. Ek word jiska high-magnitude embedding hai (shayad kyunki wo bahut frequent hai) har cheez ke saath high dot products rakhega.
Fix: Hamesha cosine similarity use karo (normalized dot product): Ye vectors ke beech angle measure karta hai, magnitude se independent.
Recall Ek 12-saal ke bacche ko samjhao
Socho tumhare paas ek jaduyi map hai jahan har word ek dot hai. Similar cheezein mean karne wale words paas-paas hain—toh "happy" "joyful" ke paas hai, aur "cat" "dog" ke paas hai. Opposite cheezein mean karne wale words door hain.
Ab ye bahut cool part hai: tum meanings ke saath math kar sakte ho! Agar "king" dot se "man" dot ki taraf jaao, tum "ye ek male person hai" direction mein move kar rahe ho. Agar phir "woman" ki taraf ulti direction mein jaao, toh tum "queen" ke paas pahunch jaoge! Jaise meaning ke directions hain jin mein tum chal sakte ho.
Hum ye map kaise banate hain? Hum BAHUT saare sentences padhte hain (jaise, millions) aur notice karte hain ki kaun se words ek doosre ke paas appear hote hain. Agar "dog" aur "bark" aksar same sentences mein hain, unhe map par paas rakhte hain. Agar "dog" aur "telephone" kabhi saath nahi aate, unhe door rakhte hain. Computer figure out karta hai har word ko kahan rakhna hai taaki map un saare patterns ke saath sense kare.
Ye hai word embedding—ek map jahan word positions batate hain unka kya matlab hai!
Skip-gram = Skip the target, get the neighbors Beech ke word se context predict karo ("outward" dekhta hai)
GloVe = Global Vectors Global co-occurrence Vectors use karta hai (local windows nahi)
Connections
- One-hot encoding ← jise embeddings replace karti hain
- Cosine similarity ← semantic similarity measure karna
- Softmax function ← scores ko probabilities mein convert karna
- Backpropagation ← embeddings kaise train hoti hain
- Transfer learning ← pre-trained embeddings use karna
- LSTM / GRU ← aksar word embeddings input ke roop mein use karte hain
- Attention mechanism ← fixed embeddings ko context-dependent ones se replace kar sakta hai
- BERT ← modern contextualized embeddings
- Subword tokenization ← rare words aur morphology handle karta hai
- t-SNE ← high-dimensional embeddings ko 2D mein visualize karna
#flashcards/ai-ml
Word embeddings kya hain? :: Dense, low-dimensional vector representations of words jo continuous space mein semantic meaning aur relationships capture karti hain (typically 50-300 dimensions).
One-hot encoding ke upar embeddings ka key advantage kya hai?
CBOW ka matlab kya hai aur ye kya predict karta hai?
Skip-gram kya predict karta hai?
Skip-gram aksar CBOW se better kyu hota hai?
Negative sampling kaunsi computational problem solve karta hai?
Ek training example ke liye negative sampling loss function likhein :: jahan target hai, context hai, k negative samples hain.
GloVe ke peeche key insight kya hai?
GloVe objective function likhein :: jahan co-occurrence count hai aur weighting function hai.
GloVe mein weighting function kya karta hai?
Embeddings ke saath vector arithmetic allow karne wali famous property kya hai?
Do embeddings ke beech similarity properly kaise measure karte hain?
Standard word embeddings ko polysemy ke saath kya problem hoti hai?
Hierarchical softmax computational cost kaise reduce karta hai?
Negative sampling distribution kyu use karta hai?
Word2Vec aur GloVe training mein kya fark hai?
Word embeddings ko typically kitna training data chahiye?
Word embeddings ki typical dimensionality kya hoti hai? :: 50-300 dimensions, expressiveness aur computational efficiency balance karte hue. Common choices: 100, 200, 300.