Embeddings: Categorical to Word2Vec
After this lesson, you will be able to:
- Explain why one-hot encoding fails at scale and why a learned embedding lookup table compresses millions of categories into a few hundred dense, similarity-aware dimensions
- Train your own categorical (entity) embeddings on a tabular dataset and beat one-hot + linear models with a small MLP that lets gradient descent discover the geometry of zip codes, product IDs, or user IDs
- Implement Word2Vec skip-gram with negative sampling from scratch and observe the famous king − man + woman ≈ queen vector arithmetic emerge from raw text
- Pick the right embedding strategy (entity, Word2Vec/GloVe, FastText, or pretrained contextual) based on cardinality, vocabulary openness, and the downstream task
Before you start
Don't worry if "embedding" sounds abstract. It is literally just a lookup table with one row per category, and gradient descent figures out what the rows should mean. Once you train one yourself you will see why this single trick replaced one-hot encoding everywhere it could.
#Why One-Hot Encoding Falls Apart
#The Embedding Layer Is a Learned Lookup Table
#Entity Embeddings for Tabular Data
nn.Embedding.The recipe
- For each categorical column, choose an embedding dim. Rule of thumb:
min(50, (V + 1) // 2)or fast.ai'smin(600, round(1.6 * V**0.56)). - Stack the embeddings of every categorical for a row, concatenate with the numeric columns.
- Feed the concatenated vector into an MLP.
- Train end-to-end with the task loss.
Why it works: gradient descent learns a geometry where similar categories get similar vectors. For zip codes, "similar" turns out to mean "similar customer behaviour", not geographic proximity per se, but whatever predicts the target. The model discovers which categories should cluster.
You are predicting credit risk and have a zip_code column with 35,000 unique values. You also have 50 numeric features. Which encoding do you reach for first?
For deep models, the embedding is almost always the right answer. Target encoding is a strong baseline for tree-based models (it leaks if not done with K-fold), but for a neural model that needs gradient flow through the whole pipeline, embeddings let the model discover its own zip-code geometry while training the prediction head.
#Word2Vec: Embeddings That Capture Meaning
#GloVe: Combining Local + Global Statistics
#FastText: Sub-Word Embeddings for Open Vocabulary
#Modern Context: Embeddings Are Now the Input Layer of Transformers
nn.Embedding(vocab_size, hidden_dim). Word2Vec did not die: it became the first layer of every LLM you have ever used.This example needs a deep-learning library, so it does not run on this page. Copy the code below to Google Colab.
# Copy to Colab: needs torch, so it cannot run on this page.
# Train a tiny Word2Vec skip-gram with negative sampling and watch
# vector arithmetic emerge.
import math
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
random.seed(42); torch.manual_seed(42)
# A toy corpus where royalty + gender relations are explicit
sentences = [
"the king rules the kingdom",
"the queen rules the kingdom",
"the man is a king",
"the woman is a queen",
"a prince is a young king",
"a princess is a young queen",
"the king and the queen rule together",
"the man and the woman are royal",
]
# 1) Build vocabulary
words = sorted({w for s in sentences for w in s.split()})
w2i = {w: i for i, w in enumerate(words)}
i2w = {i: w for w, i in w2i.items()}
V = len(words)
# 2) Generate (centre, context) pairs with window=2
WINDOW = 2
pairs = []
for s in sentences:
toks = [w2i[w] for w in s.split()]
for i, c in enumerate(toks):
for j in range(max(0, i-WINDOW), min(len(toks), i+WINDOW+1)):
if i != j:
pairs.append((c, toks[j]))
print(f"Vocab: {V} words, {len(pairs)} (centre, context) training pairs")
# 3) Skip-gram with negative sampling
D = 16 # embedding dim
NEG = 5 # negatives per positive
EPOCHS = 800
LR = 0.1
U = nn.Embedding(V, D) # centre embeddings
W = nn.Embedding(V, D) # context embeddings
opt = torch.optim.SGD(list(U.parameters()) + list(W.parameters()), lr=LR)
for epoch in range(EPOCHS):
random.shuffle(pairs)
total = 0.0
for c, ctx in pairs:
opt.zero_grad()
u = U(torch.tensor(c)) # (D,)
v_pos = W(torch.tensor(ctx)) # (D,)
loss_pos = -F.logsigmoid(u @ v_pos)
neg_ids = torch.randint(0, V, (NEG,))
v_neg = W(neg_ids) # (NEG, D)
loss_neg = -F.logsigmoid(-(v_neg @ u)).sum()
loss = loss_pos + loss_neg
loss.backward(); opt.step()
total += loss.item()
if epoch % 200 == 0:
print(f"epoch {epoch:4d} loss={total/len(pairs):.3f}")
# 4) Vector arithmetic: king - man + woman ≈ ?
def vec(w): return U(torch.tensor(w2i[w]))
target = vec("king") - vec("man") + vec("woman")
# Cosine similarity to every word
all_vecs = U.weight.detach()
cos = F.cosine_similarity(target.unsqueeze(0), all_vecs)
top = cos.argsort(descending=True)[:5]
print("\n king - man + woman is closest to:")
for idx in top:
print(f" {i2w[int(idx)]:>10s} cosine={cos[idx]:.3f}")
print("\n CHALLENGE: try prince - man + woman, and king - kingdom + ???")
# After ~800 epochs on this tiny toy corpus, the top-1 word for
# king - man + woman is usually 'queen' (sometimes 'princess' first
# on rerun — both are correct directions of the gender shift).
#
# Real Word2Vec is trained on billions of words and the analogies are
# much sharper. But the same arithmetic emerges from this 50-line model.
#
# To explore further:
# - Increase D to 32 and EPOCHS to 1500.
# - Add subsampling of frequent words (the canonical Word2Vec trick).
# - Try CBOW: predict centre from average of context vectors.#When to Use Which Embedding
| Scenario | Recommended approach |
|---|---|
| Tabular ML, deep model, high-cardinality categorical (>50 values) | Entity embedding via nn.Embedding, dim ≈ 1.6 * cardinality^0.56 |
| Tabular ML, tree-based model (XGBoost, LightGBM) | Target encoding or CatBoost native; tree models do not benefit from embeddings |
| Word-level NLP, small/medium corpus, frozen embeddings OK | Pretrained Word2Vec or GloVe |
| Word-level NLP, agglutinative/morphologically rich language, OOV expected | FastText |
| Sentence-level NLP, modern accuracy required | Pretrained transformer (BERT, sentence-transformers, OpenAI/Cohere/Voyage embeddings) |
| Recommender systems with user IDs / item IDs | Two-tower model with nn.Embedding for users and items, dot-product or cosine-similarity scoring |
| Multilingual or zero-shot retrieval | Pretrained multilingual sentence transformers (LaBSE, multilingual-e5) |
#Visualising Embeddings
Interactive Lab
Pick word pairs and watch cosine similarity update — see why 'king' and 'queen' land near each other in vector space.
Once you have trained embeddings, project them to 2-D with t-SNE or UMAP and plot them. This is the iconic ML visualization where related concepts cluster:
- Word2Vec on Wikipedia: capitals cluster, animals cluster, professions cluster.
- Entity embeddings on Rossmann store IDs: stores in similar regions cluster, even though no region label was provided to the model.
- Image embeddings on ImageNet: dog breeds cluster together; vehicles cluster separately; tools form a third cluster.
The act of training to predict a target compresses semantic information into the embedding geometry, and projection makes it visible.
#Key Takeaways
- Embeddings are dense lookup tables.
nn.Embedding(V, d)gives every category a learnable d-dim row, replacing V-dim sparse one-hot with a much smaller, similarity-aware representation - Entity embeddings beat one-hot for high-cardinality tabular columns in deep models — fast.ai's Rossmann result and every modern recommender confirms this
- Word2Vec's skip-gram + negative sampling turned word embeddings into a viable production technique by reducing per-step cost from O(vocabulary) to O(K+1)
- Vector arithmetic emerges because training pushes co-occurring words close in space:
king - man + woman ≈ queenis geometry that gradient descent built - Modern transformers contain embedding layers as their first step, but the static Word2Vec/GloVe vectors are now mostly replaced by contextual embeddings produced by the full transformer
#Quick Check
Why does negative sampling speed up Word2Vec training?