Embeddings

Represent objects as learned vectors whose geometry carries meaning.

The Big Question

Representation Learning taught us that a model can learn useful internal descriptions of data. Embeddings make that idea concrete.

An embedding is a learned vector that represents an object. The object might be a restaurant, user, movie, product, word, sentence, image, city, protein, or almost anything else we want a model to reason about.

If a model learns a useful representation, what does that representation usually look like? A vector.

Core Intuition

Imagine building a restaurant recommendation system. If a user likes McDonalds, Burger King should probably be a better recommendation than Nobu. A human sees that immediately. To a computer, these are just different labels.

RestaurantCuisine labelWhat the label misses
McDonaldsFast Foodcheap, quick, burger, drive-through
Burger KingFast Foodcheap, quick, burger, drive-through
NobuJapaneseexpensive, sushi, special occasion
Olive GardenItaliancasual sit-down, pasta, family meal

An embedding replaces each label with a learned vector. The individual dimensions do not need predefined meanings. What matters is the geometry: similar restaurants should land near each other.

RestaurantEmbeddingInterpretation
McDonalds(0.92, 0.18, 0.11)Fast, cheap, burger-like
Burger King(0.89, 0.20, 0.09)Very similar burger behavior
Nobu(0.10, 0.91, 0.82)Expensive, Japanese, special occasion
Olive Garden(0.34, 0.71, 0.44)Casual sit-down, Italian

McDonalds and Burger King have similar vectors. Nobu is far away. Olive Garden is somewhere between fast casual and sit-down dining. That vector is the embedding.

Interactive Demo

Embedding geometry lab
McDonald'sBurger KingShake ShackNobuSushi YasudaOlive GardenChipotle
Selected object
McDonald's

At 0%, the points behave like unrelated labels. At 100%, similar restaurants sit close together. Drag a point to see how recommendations change.

Embedding row
[0.92, 0.18, 0.11]
Recommendation by distance
  1. 1. Chipotle
  2. 2. Sushi Yasuda
  3. 3. Shake Shack

Start at 0% to see category labels as unrelated points. Move toward 100% to see a learned embedding space where similarity becomes geometry.

Mathematics

What Is An Embedding?

An embedding is a dense vector representation of an object. If the object is xx, an embedding function maps it into a vector space:

e=f(x)e=f(x)
eRde\in\mathbb{R}^d

The dimension dd might be 2, 16, 128, 768, or 4096. The important point is not the exact dimension. The important point is that nearby vectors represent similar objects.

Why Not One-Hot Encoding?

A one-hot vector gives every category its own coordinate. With four restaurants, the representation might look like this:

McDonalds=(1,0,0,0)\text{McDonalds}=(1,0,0,0)
Burger King=(0,1,0,0)\text{Burger King}=(0,1,0,0)
Nobu=(0,0,1,0)\text{Nobu}=(0,0,1,0)

The problem is that all one-hot categories are equally far apart. The model cannot tell from the representation that McDonalds is more similar to Burger King than it is to Nobu.

Embeddings solve this by learning coordinates where distance means something.

The Embedding Matrix

Suppose there are VV possible restaurants and we choose embedding dimension dd. We learn an embedding matrix:

ERV×dE\in\mathbb{R}^{V\times d}

Each row is one object embedding. For four restaurants and three dimensions:

E=[0.920.180.110.890.200.090.100.910.820.340.710.44]E=\begin{bmatrix}0.92&0.18&0.11\\0.89&0.20&0.09\\0.10&0.91&0.82\\0.34&0.71&0.44\end{bmatrix}

If Burger King has ID 2, the embedding lookup simply returns row 2:

E2=(0.89,0.20,0.09)E_2=(0.89,0.20,0.09)

This lookup is efficient. A 768-dimensional embedding can be much cheaper than a one-hot vector with millions of dimensions.

Learning The Embeddings

Embeddings are not typed in by humans. They usually start as small random numbers. During training, gradient descent updates the rows that appear in the mini-batch.

EBurger KingEBurger KingηLEBurger KingE_{\text{Burger King}}\leftarrow E_{\text{Burger King}}-\eta\frac{\partial L}{\partial E_{\text{Burger King}}}

If users who like McDonalds often click Burger King, the loss encourages those vectors to become useful in similar ways. Over many updates, restaurants that appear in similar contexts move closer together.

The model is never explicitly told that McDonalds is similar to Burger King. It discovers that because the similarity helps reduce prediction error.

Why It Works

Embeddings learn geometry. Instead of memorizing isolated labels, the model learns where objects should live in a vector space. Similar behavior becomes nearby geometry. Different behavior becomes distance.

This geometry allows generalization. If a new burger restaurant appears, a few updates can move its vector toward other burger restaurants. The model can then reuse what it already learned about nearby objects.

A Concrete Language Example

Word embeddings are learned the same way. A model sees words in context and adjusts vectors so words used in similar contexts become close.

king=(0.84,0.12,0.44)\text{king}=(0.84,0.12,-0.44)
queen=(0.81,0.15,0.39)\text{queen}=(0.81,0.15,-0.39)
man=(0.71,0.18,0.62)\text{man}=(0.71,-0.18,-0.62)
woman=(0.68,0.13,0.58)\text{woman}=(0.68,-0.13,-0.58)

The model was not handed a dictionary of grammar. It learned vectors that helped predict words from surrounding words. Semantic relationships emerged because they were useful for the training task.

Embeddings Versus Feature Engineering

QuestionFeature EngineeringEmbeddings
Who chooses the features?Human designs themModel learns them
ShapeOften sparseDense vector
MeaningUsually named by humansLearned from the task
SimilarityMust be designed manuallyMeasured by vector distance or dot product
ReuseOften tied to one projectOften transferable across tasks

Complexity

If there are VV objects and embedding dimension dd, the embedding table contains:

V×dV\times d

parameters. Training usually updates only the rows for objects in the current mini-batch, which is why embeddings remain practical even with large vocabularies.

Implementation

This PyTorch sketch learns restaurant and user embeddings for a recommendation task. A high score means the model predicts the user will like the restaurant.

import torch
import torch.nn as nn

class RestaurantRecommender(nn.Module):
    def __init__(self, num_users, num_restaurants, dim=32):
        super().__init__()
        self.user_embedding = nn.Embedding(num_users, dim)
        self.restaurant_embedding = nn.Embedding(num_restaurants, dim)

    def forward(self, user_ids, restaurant_ids):
        user_vec = self.user_embedding(user_ids)
        restaurant_vec = self.restaurant_embedding(restaurant_ids)
        score = (user_vec * restaurant_vec).sum(dim=1)
        return score

model = RestaurantRecommender(
    num_users=10_000,
    num_restaurants=50_000,
    dim=32,
)

user_ids = torch.tensor([17, 17, 42])
restaurant_ids = torch.tensor([3, 91, 3])
scores = model(user_ids, restaurant_ids)

print(scores)
print(model.restaurant_embedding.weight[3])

After training, you can visualize restaurant embeddings by reducing them to two dimensions with PCA or t-SNE. Similar restaurants should often cluster together if the training signal was useful.

Interview Discussion

What is an embedding?

An embedding is a learned dense vector representation of an object, such as a word, restaurant, user, product, or image.

Why are embeddings better than one-hot encoding?

One-hot vectors treat every category as equally unrelated. Embeddings can place similar objects near each other.

How are embeddings learned?

They are parameters. Gradient descent updates the embedding rows that appear in training examples.

Why do similar objects often have similar embeddings?

Objects used in similar contexts tend to receive similar gradient updates because similar vectors help reduce the training loss.

Can embeddings be reused across tasks?

Often yes. A useful embedding space can transfer knowledge to related tasks, especially when trained on large data.

Active Recall

1. What problem do embeddings solve?

2. Why can one-hot encoding not represent similarity?

3. What is an embedding matrix?

4. How are embeddings updated during training?

5. Why do embeddings form a meaningful geometric space?

Common Mistakes

  • Thinking each embedding dimension has a predefined meaning.
  • Believing embeddings are manually engineered.
  • Assuming embeddings only exist for words.
  • Confusing embeddings with one-hot encoding.
  • Forgetting that embeddings are learned parameters.

Connection To Principal Component Analysis

Representation Learning showed that models can learn useful features automatically. Embeddings are one concrete form of those learned features: vector spaces where similarity, relationships, and structure emerge from data. Next we look at a different kind of representation: compressing data while preserving as much structure as possible.