Word embeddings represent each word as a dense vector so that words used in similar contexts get similar vectors. Word2Vec (Google, 2013) made them popular; they were the step between Bag of Words and modern transformers.
What You Will Learn
- The distributional hypothesis
- Build tiny embeddings from co-occurrence counts with NumPy
- How Word2Vec (CBOW, Skip-gram) learns
- Train Word2Vec with gensim
- Static vs contextual embeddings
Prerequisites
Bag of Words & TF-IDF, Eigenvalues (helpful).
“You Shall Know a Word by the Company It Keeps”
If “king” and “queen” appear next to the same words (rules, kingdom, the), they probably mean related things. Embeddings turn this idea into maths.
Embeddings from Scratch
import numpy as np
corpus = ["king rules the kingdom", "queen rules the kingdom", "the king is a man",
"the queen is a woman", "man and woman walk", "apple and mango are fruits",
"i eat an apple", "i eat a mango", "mango is a sweet fruit", "apple is a sweet fruit"]
toks = [s.split() for s in corpus]
vocab = sorted({w for t in toks for w in t})
ix = {w: i for i, w in enumerate(vocab)}
C = np.zeros((len(vocab), len(vocab))) # co-occurrence within ±2 words
for t in toks:
for i, w in enumerate(t):
for j in range(max(0, i - 2), min(len(t), i + 3)):
if j != i:
C[ix[w], ix[t[j]]] += 1
P = C / C.sum()
pw = P.sum(1, keepdims=True)
ppmi = np.maximum(np.log(np.maximum(P / (pw @ pw.T), 1e-12)), 0) # positive PMI
U, S, Vt = np.linalg.svd(ppmi)
E = U[:, :4] * S[:4] # 4-dimensional embeddings
E = E / np.linalg.norm(E, axis=1, keepdims=True)
sim = lambda a, b: round(float(E[ix[a]] @ E[ix[b]]), 2)
for a, b in [("king", "queen"), ("apple", "mango"), ("king", "apple"), ("queen", "mango")]:
print(a, b, sim(a, b))
king queen 1.0 apple mango 0.8 king apple 0.07 queen mango -0.0
Explanation: We counted which words appear near each other, re-weighted the counts with PPMI (how much more often than chance) and compressed them with SVD into 4 numbers per word. Without being told anything about royalty or fruit, the vectors put king and queen together and apple and mango together, far from each other. Word2Vec and GloVe learn the same kind of structure from billions of words.
How Word2Vec Learns
| Variant | Task | Good for |
|---|---|---|
| CBOW | Predict the middle word from its neighbours | Faster, frequent words |
| Skip-gram | Predict neighbours from the middle word | Rare words, small data |
A shallow network is trained on this prediction task with tricks like negative sampling; the learned input weights become the embeddings (typically 100–300 dimensions). Famous result: vector(“king”) − vector(“man”) + vector(“woman”) ≈ vector(“queen”).
Train with gensim
# pip install gensim
from gensim.models import Word2Vec
sentences = [s.split() for s in corpus] # use thousands of sentences in practice
model = Word2Vec(sentences, vector_size=50, window=2, min_count=1, sg=1, epochs=200, seed=1)
print(model.wv.most_similar("apple", topn=3))
import gensim.downloader as api # or use pre-trained vectors
glove = api.load("glove-wiki-gigaword-100")
print(glove.most_similar(positive=["king", "woman"], negative=["man"], topn=1))
Static vs Contextual Embeddings
| Word2Vec / GloVe / FastText | BERT / GPT embeddings | |
|---|---|---|
| One vector per word | Yes – “bank” is the same in “river bank” and “bank loan” | No – depends on the sentence |
| Unknown words | Not handled (FastText uses sub-words) | Handled via sub-word tokens |
| Cost | Very cheap | Needs a transformer |
| Use today | Lightweight features, small devices | Most NLP tasks – see BERT and text embeddings |
Series
NLP series: NLP Intro · Tokenizer · Stop Words · Stemming · Lemmatization · Bag of Words & TF-IDF · Word Embeddings · Sentiment Analysis · NER · Topic Modeling · BERT · Spam Project
Interview Questions
Q: What is a word embedding?
A dense vector representing a word so that semantically similar words are close together.
Q: CBOW vs Skip-gram?
CBOW predicts a word from its context; skip-gram predicts the context from a word and works better for rare words.
Q: Why are Word2Vec embeddings called static?
Each word has one vector regardless of context.
Practice Exercises
- Add sentences about cars and bikes to the corpus and check whether they form a third group.
- Load GloVe vectors and solve five analogies like Paris − France + India.
Summary
Word embeddings capture meaning from context. Count-based (PPMI + SVD) and prediction-based (Word2Vec) methods learn similar structure; contextual models like BERT go further.
Next: Sentiment Analysis · BERT Explained
Machine Learning Tutorials, Courses and Certifications