Learned Embeddings
Every encoder so far was decided before training: one-hot gives each category its own axis, target encoding gives it one number computed from the label. A neural network can do something more flexible: give each category a short vector of numbers, an embedding, and learn those numbers during training together with the rest of the model. Categories that behave alike end up with similar vectors. This is how recommender systems represent millions of users and items, how language models represent tokens, and how tabular deep-learning models handle columns such as store_id or product_id.
An embedding is a lookup table
An embedding layer for k categories and d dimensions is a table with k rows and d columns. Encoding category number i means reading row i. That is exactly the same as multiplying a one-hot vector by the table, without building the one-hot vector:
import numpy as np
rng = np.random.default_rng(0)
k, d = 5, 3 # 5 categories, 3 numbers each
table = rng.normal(0, 0.1, (k, d)) # the embedding: learned in practice
ids = np.array([2, 0, 2]) # three rows: categories 2, 0, 2
lookup = table[ids] # what an embedding layer does
one_hot = np.eye(k)[ids] # the long way round
print(np.round(lookup, 3))
print("same as one-hot @ table:", np.allclose(lookup, one_hot @ table))
print("parameters:", table.size, "| one-hot width:", k, "| embedding width:", d)[[ 0.13 0.095 -0.07 ]
[ 0.013 -0.013 0.064]
[ 0.13 0.095 -0.07 ]]
same as one-hot @ table: True
parameters: 15 | one-hot width: 5 | embedding width: 3
Rows 0 and 2 of the result are identical because both are category 2, and the one-hot product gives exactly the same numbers. The layer holds 15 parameters (5 categories times 3 numbers), and each row comes out 3 numbers wide instead of 5.
So an embedding is "one-hot followed by a linear layer", stored efficiently. The table starts random; gradient descent then moves each row so that the whole model predicts better. Only the rows of categories present in a batch receive gradient. The math of embeddings and similarity is in Embeddings.
Training one: a recorded PyTorch example
PyTorch's nn.Embedding is that table. In the example below, eight products belong to two hidden groups (four sports items, four books). The model never sees the groups; it only sees product_id, a price and whether the item was bought. After training, the learned 2-D vectors of products in the same group should point in similar directions.
PyTorch does not run in the browser, so this example is recorded: it ran on CPU in the course's Docker image, and the output below is what it printed.
import torch
from torch import nn
seed = 0
torch.manual_seed(seed)
n_products, n_rows = 8, 800
product = torch.randint(0, n_products, (n_rows,))
group = (product >= 4).float() # hidden: 0-3 sports, 4-7 books
price = torch.rand(n_rows)
logit = 2.5 * (1 - 2 * group) * (price - 0.5) + 1.5 * group - 0.75
bought = (torch.rand(n_rows) < torch.sigmoid(logit)).float()
class Model(nn.Module):
def __init__(self):
super().__init__()
self.emb = nn.Embedding(n_products, 2) # 8 x 2 learned table
self.head = nn.Linear(2 + 1, 1)
self.inter = nn.Linear(2, 1) # lets the price effect depend on the product
def forward(self, p, x):
e = self.emb(p)
return self.head(torch.cat([e, x[:, None]], 1)).squeeze(1) + self.inter(e).squeeze(1) * x
model = Model()
opt = torch.optim.Adam(model.parameters(), lr=0.05)
loss_fn = nn.BCEWithLogitsLoss()
for step in range(301):
opt.zero_grad()
loss = loss_fn(model(product, price), bought)
loss.backward()
opt.step()
if step % 100 == 0:
print(f"step {step:3d} loss {loss.item():.3f}")
E = nn.functional.normalize(model.emb.weight.detach(), dim=1)
sim = E @ E.T
within = (sim[:4, :4].sum() - 4 + sim[4:, 4:].sum() - 4) / 24
between = sim[:4, 4:].mean()
print(f"mean cosine similarity within groups: {within.item():.2f}")
print(f"mean cosine similarity between groups: {between.item():.2f}")step 0 loss 0.739
step 100 loss 0.547
step 200 loss 0.546
step 300 loss 0.546
mean cosine similarity within groups: 0.73
mean cosine similarity between groups: -0.73
The loss falls from 0.739 to 0.546 within the first 100 steps and then stays put. The learned vectors tell the story: products of the same hidden group have a mean cosine similarity of 0.73, products of different groups -0.73. The model discovered the two groups from purchase behaviour alone, because treating them alike was the cheapest way to predict well.
Choosing the size, and what to watch
- Dimension d: small for small vocabularies (2 to 16 for tens of categories, 32 to 256 for millions). A rule of thumb from the fastai library is about 1.6 times k to the power 0.56 (k = number of categories), capped at a few hundred; tune it like any other hyperparameter.
- Rare categories get few gradient updates and keep near-random vectors. Group them into an "other" row (as
min_frequencydoes for one-hot) and reserve a row for unknown categories at inference. - Leakage still applies: embeddings are fitted parameters. Learn them on training data only; reusing embeddings trained on the full dataset (including test rows) as features for another model leaks the test labels, just as naive target encoding does.
- Reuse: a trained table can be exported and used as features elsewhere, for instance fed to a gradient-boosted tree, or to find similar items by cosine similarity. Pretrained word and sentence embeddings are the text version of this idea (Preparing Text Data).
When to use embeddings
Use them when the model is a neural network anyway and a categorical column has many levels with enough rows each: users, items, stores, words. For a gradient-boosted tree on a few thousand rows, target encoding or one-hot is simpler and usually as good.
Pitfalls
- Expecting meaning from too little data: with a few rows per category, the vectors are noise.
- No unknown row: a new ID at inference has no row; map it to a reserved index.
- Comparing embeddings from two training runs: they can be rotated or flipped versions of each other; only similarities within one run are meaningful.
- Leakage through pretrained tables learned on data that includes your test period.
Practice
- An embedding table has 50,000 rows and 32 columns. How many parameters is that, and how many columns would one-hot encoding of the same column produce?
Answer
50,000 times 32 = 1,600,000 learned numbers; one-hot would produce 50,000 columns per row (sparse), and a first linear layer of width 32 on top of them would have the same 1.6 million weights. The embedding is that layer, stored as a lookup.
- In the recorded example, why do products from the same group end up with similar vectors even though the group was never given to the model?
Answer
Products of one group affect the purchase probability in the same way (same price effect, same base rate). The loss is lowest when the model treats them alike, so gradient descent moves their rows in the same direction. Similarity in the embedding reflects similar behaviour with respect to the target.
Test yourself
Looking up row i of an embedding table is mathematically the same as what?
- Hashing the category
- Multiplying the one-hot vector of i by the table
- Target encoding
- Taking the mean of the table
Which rows of an embedding table receive gradient in a training step?
- All rows
- Only the rows of categories present in the batch
- Only the first row
- None; embeddings are fixed
How should a learned-embedding model handle a product ID it has never seen?
- Crash
- Map it to a reserved unknown (or other) row
- Create a random new row at inference
- Use the ID number as the embedding