Embeddings & Representation Learning

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

An embedding maps a discrete or high-dimensional object (a word, a user, a product, an image, a graph node) to a dense vector of real numbers, learned so that geometric relations between vectors reflect relations between the objects. Representation learning is the wider goal behind it: let the model discover useful features instead of designing them by hand. Embeddings are the interface between raw data and almost every neural network in the next pages, and the data structure behind semantic search and retrieval-augmented generation.

This page covers the foundations from the machine-learning side: how embedding layers work, how vectors are learned, how to compare and inspect them, and the pitfalls. Production concerns for text embedding models (dedicated models, dimensions and cost, Matryoshka truncation, multilingual and multimodal models, vector databases) are in the AI and database sections: Embeddings and Tokens & Tokenization.

Examples target Python 3.13, NumPy 2.5, PyTorch 2.15 and Keras 3.15 (TensorFlow 2.21 backend), checked against their documentation on 2026-10-30. Examples were run on Python 3.13 with NumPy, PyTorch 2.15 (CPU) and Keras 3.15 on TensorFlow 2.21 on 2026-11-01.

From one-hot to dense vectors

The simplest encoding of a category with \(V\) possible values is one-hot: a vector of length \(V\) with a single 1. It is exact but has two weaknesses: it is huge when \(V\) is a vocabulary or a catalogue (hundreds of thousands), and every pair of categories is equally far apart, so nothing the model learns about "cat" transfers to "kitten".

Property One-hot Dense embedding

Dimension

\(V\), often tens of thousands to millions

\(d\), typically 16 to 1024

Similarity between items

None (all orthogonal)

Learned; similar items are close

Parameters

None

\(V \times d\) learned numbers

Interpretable axes

Yes (one per category)

No (directions, not features)

Unseen categories

Cannot represent

Needs a fallback (unknown bucket, hashing, subwords)

An embedding layer is mathematically a one-hot vector multiplied by a weight matrix \(E \in \mathbb{R}^{V \times d}\): \(e_i = \mathbf{1}_i^{\top} E\), which is just row \(i\) of \(E\). Implementations skip the multiplication and index the row, so the layer is a trainable lookup table and its gradient touches only the rows used in the batch.

import numpy as np

rng = np.random.default_rng(0)
V, d = 6, 3
E = rng.standard_normal((V, d))          # embedding matrix, one row per item

i = 4
one_hot = np.eye(V)[i]
print(np.allclose(one_hot @ E, E[i]))    # True: one-hot times E equals row lookup

def cosine(a, b):
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))

print(round(cosine(E[0], E[1]), 3), round(cosine(E[0], E[0]), 3))   # second value is 1.0

Embedding layers in practice

PyTorch

nn.Embedding(num_embeddings, embedding_dim) takes integer ids of any shape and returns the same shape with an extra last dimension of size embedding_dim. The main options:

  • padding_idx: the row for this id is initialised to zeros and receives no gradient, so padding stays neutral.

  • max_norm: renormalises looked-up rows in place that exceed this norm. It modifies the weight during the forward pass, which interacts badly with autograd if you reuse the rows; use it with care.

  • sparse=True: produces sparse gradients for huge tables. Only some optimisers accept sparse gradients (SGD, SparseAdam, Adagrad), so check the optimiser documentation before enabling it.

  • nn.Embedding.from_pretrained(weights, freeze=True): loads a pre-trained matrix; freeze=True (the default) disables training, set it to False to fine-tune.

nn.EmbeddingBag looks up many ids per example and reduces them (mode="mean", "sum" or "max") in one fused step, without materialising the padded (batch, length, d) tensor. It is the efficient layer for bag-of-words classifiers and for pooling a variable number of features.

import torch
from torch import nn

torch.manual_seed(0)

emb = nn.Embedding(num_embeddings=1000, embedding_dim=16, padding_idx=0)
ids = torch.tensor([[5, 7, 0, 0], [9, 2, 4, 1]])      # 0 is padding
vectors = emb(ids)
print(vectors.shape)                                  # torch.Size([2, 4, 16])
print(vectors[0, 2].abs().sum().item())               # 0.0 (padding row is zero)

# A bag-of-words classifier: average the word vectors, then a linear layer.
class BagClassifier(nn.Module):
    def __init__(self, vocab: int, d: int, classes: int):
        super().__init__()
        self.bag = nn.EmbeddingBag(vocab, d, mode="mean")
        self.fc = nn.Linear(d, classes)

    def forward(self, flat_ids, offsets):
        return self.fc(self.bag(flat_ids, offsets))

model = BagClassifier(1000, 16, 3)
flat_ids = torch.tensor([5, 7, 9, 2, 4, 1])           # two examples concatenated
offsets = torch.tensor([0, 2])                        # example 0 = ids[0:2], example 1 = ids[2:]
print(model(flat_ids, offsets).shape)                 # torch.Size([2, 3])

# Load pre-trained vectors and freeze them.
pretrained = torch.randn(1000, 16)                    # stand-in for e.g. GloVe/word2vec rows
frozen = nn.Embedding.from_pretrained(pretrained, freeze=True, padding_idx=0)

Keras

keras.layers.Embedding(input_dim, output_dim, mask_zero=False) is the equivalent. input_dim is the vocabulary size (largest id plus one), mask_zero=True reserves id 0 for padding and emits a mask downstream layers respect (so the vocabulary effectively starts at 1). Embedding.set_weights or the embeddings_initializer (for example keras.initializers.Constant(matrix)) loads pre-trained vectors; set trainable=False to freeze them. Text-to-id conversion is done by keras.layers.TextVectorization (adapt it on training text only).

import numpy as np
import keras
from keras import layers

vocab_size, dim = 1000, 16
pretrained = np.random.default_rng(0).standard_normal((vocab_size, dim)).astype("float32")

embedding = layers.Embedding(
    vocab_size, dim, mask_zero=True,
    embeddings_initializer=keras.initializers.Constant(pretrained),
    trainable=False,
)

inputs = keras.Input(shape=(None,), dtype="int32")
x = embedding(inputs)
x = layers.GlobalAveragePooling1D()(x)               # honours the mask from mask_zero
outputs = layers.Dense(3, activation="softmax")(x)
model = keras.Model(inputs, outputs)
model.summary()

The distributional idea: word2vec

"You shall know a word by the company it keeps": words appearing in similar contexts should have similar vectors. word2vec turns this into a prediction task over a text corpus, with two variants:

  • Skip-gram: given a centre word, predict the surrounding context words.

  • CBOW (continuous bag of words): given the context words, predict the centre word.

Computing a softmax over a vocabulary of hundreds of thousands of words per example is too slow, so training uses negative sampling: for each true (centre, context) pair, draw a few random "noise" words and train a logistic classifier to tell real pairs from noise. With centre vectors \(v_c\), context vectors \(u_o\) and \(k\) noise words \(n_j\):

\[ \mathcal{L} = -\log \sigma(u_o^{\top} v_c) - \sum_{j=1}^{k} \log \sigma(-u_{n_j}^{\top} v_c) \]

After training, the centre vectors (sometimes averaged with the context vectors) are the embeddings. GloVe is a related method that factorises global co-occurrence counts. Both give a single static vector per word type, so they cannot separate the "bank" of a river from a bank account; that limitation led to contextual embeddings below. The famous analogies (king - man + woman ~ queen) are real but cherry-picked, and an analogy search must exclude the query words or it will simply return one of them; the details and a gensim walk-through are in Embeddings.

import torch
from torch import nn
import torch.nn.functional as F

class SkipGramNS(nn.Module):
    """Skip-gram with negative sampling."""

    def __init__(self, vocab_size: int, dim: int):
        super().__init__()
        self.center = nn.Embedding(vocab_size, dim)
        self.context = nn.Embedding(vocab_size, dim)
        nn.init.uniform_(self.center.weight, -0.5 / dim, 0.5 / dim)
        nn.init.zeros_(self.context.weight)

    def forward(self, center, positive, negatives):
        v = self.center(center)                                # (B, d)
        u_pos = self.context(positive)                         # (B, d)
        u_neg = self.context(negatives)                        # (B, k, d)
        pos_loss = F.logsigmoid((v * u_pos).sum(-1))           # (B,)
        neg_loss = F.logsigmoid(-(u_neg @ v.unsqueeze(-1)).squeeze(-1)).sum(-1)   # (B,)
        return -(pos_loss + neg_loss).mean()

model = SkipGramNS(vocab_size=5000, dim=50)
opt = torch.optim.Adam(model.parameters(), lr=1e-2)

# One illustrative step on random ids (a real run iterates over windows from a corpus).
B, k = 32, 5
loss = model(torch.randint(0, 5000, (B,)),
             torch.randint(0, 5000, (B,)),
             torch.randint(0, 5000, (B, k)))
opt.zero_grad()
loss.backward()
opt.step()
print(loss.item())

Comparing vectors

Three measures cover almost all uses:

Measure Formula Use when

Cosine similarity

\(\dfrac{a \cdot b}{\lVert a\rVert \lVert b\rVert}\)

Direction matters, length does not; the default for text embeddings

Dot product

\(a \cdot b\)

Vectors were trained with dot-product scores, or are normalised (then equal to cosine)

Euclidean distance

\(\lVert a - b\rVert_2\)

Clusters and nearest-neighbour methods; for unit vectors it is monotonic in cosine

Use the measure the model was trained with; an embedding trained with a dot product may encode importance in the vector length, which cosine discards. Nearest-neighbour search over millions of vectors needs an approximate index, covered in Embeddings and the vector-database pages that follow it.

Learning representations without labels

Autoencoders

An autoencoder trains an encoder \(z = f(x)\) and a decoder \(\hat{x} = g(z)\) to reconstruct the input through a narrower bottleneck, minimising a reconstruction loss such as mean squared error. The code \(z\) is a learned compressed representation. With a linear encoder and decoder and squared loss the optimum spans the same subspace as PCA; non-linear layers can capture curved structure. Variants add constraints so the network cannot copy the input: sparsity, noise (denoising autoencoder: corrupt the input, reconstruct the clean one) or a probabilistic latent (variational autoencoders, see Generative Models).

import torch
from torch import nn

class AutoEncoder(nn.Module):
    def __init__(self, in_dim: int = 784, code_dim: int = 32):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(in_dim, 128), nn.ReLU(), nn.Linear(128, code_dim))
        self.decoder = nn.Sequential(nn.Linear(code_dim, 128), nn.ReLU(), nn.Linear(128, in_dim))

    def forward(self, x):
        z = self.encoder(x)
        return self.decoder(z), z

model = AutoEncoder()
x = torch.rand(64, 784)
recon, z = model(x)
loss = nn.functional.mse_loss(recon, x)
loss.backward()
print(z.shape, loss.item())

Autoencoders are also used for anomaly detection (high reconstruction error flags unusual inputs) but a reconstruction objective rewards copying fine detail, so the code is often a worse feature for downstream classification than one learned with a contrastive objective.

Contrastive learning

Contrastive methods shape the space directly: pull together vectors of items that should be similar (positives) and push apart the rest (negatives). Positives come from labels, from known pairs (a query and its clicked document, an image and its caption) or from two augmented views of the same example. Two losses dominate.

Triplet loss uses an anchor \(a\), a positive \(p\) and a negative \(n\) and a margin \(m\):

\[ \mathcal{L} = \max\left(0,\; d(a,p) - d(a,n) + m\right) \]

Most random triplets already satisfy the margin and give no gradient, so training depends on mining hard or semi-hard triplets. PyTorch provides nn.TripletMarginLoss.

InfoNCE (the loss behind CLIP and SimCLR-style training) treats the rest of the batch as negatives. For a batch of \(N\) matched pairs with normalised embeddings, similarity \(s_{ij} = z_i^{\top} z'_j / \tau\) and a temperature \(\tau\):

\[ \mathcal{L} = -\frac{1}{N}\sum_{i=1}^{N} \log \frac{\exp(s_{ii})}{\sum_{j=1}^{N} \exp(s_{ij})} \]

It is a cross-entropy over the batch where the correct "class" for row \(i\) is column \(i\). Larger batches provide more negatives, which is why contrastive pre-training likes large batches. The loss itself comes from Information Theory & Losses.

import torch
import torch.nn.functional as F

def info_nce(z_a: torch.Tensor, z_b: torch.Tensor, temperature: float = 0.07) -> torch.Tensor:
    """Symmetric InfoNCE for a batch of matched pairs (row i of z_a matches row i of z_b)."""
    z_a = F.normalize(z_a, dim=-1)
    z_b = F.normalize(z_b, dim=-1)
    logits = z_a @ z_b.T / temperature                  # (N, N) similarity matrix
    targets = torch.arange(z_a.size(0), device=z_a.device)
    return (F.cross_entropy(logits, targets) + F.cross_entropy(logits.T, targets)) / 2

z_text, z_image = torch.randn(16, 64), torch.randn(16, 64)
print(info_nce(z_text, z_image).item())                 # random vectors: log(16) = 2.77 or more on average

triplet = torch.nn.TripletMarginLoss(margin=1.0)
print(triplet(torch.randn(8, 64), torch.randn(8, 64), torch.randn(8, 64)).item())

Typical failure modes: false negatives (a "negative" that is really a positive, such as two images of the same class in one batch), representation collapse when nothing prevents all inputs mapping to one point (the reason negatives, stop-gradients or variance regularisers exist), and a temperature that is too high (blurred ranking) or too low (unstable training). The text embedding models in the AI section are trained this way; see Embeddings.

Pre-trained and contextual embeddings

Training embeddings from scratch needs a lot of data. The usual path is to reuse representations:

  1. Static vectors (word2vec, GloVe, fastText): one vector per word, cheap, now mostly a teaching tool and a baseline.

  2. Contextual embeddings from transformer encoders (BERT family and successors): the vector of a token depends on the whole sentence, so "bank" differs between sentences. A sentence or document vector is obtained by pooling token vectors (mean or a special token), and models trained with a contrastive sentence objective give far better vectors for similarity than raw BERT pooling.

  3. Task-specific features: the penultimate layer of an image or audio network is a useful embedding for similarity search and as input to a small classifier (see Transfer Learning & Foundation Models).

  4. Large LLM embeddings served by an API or an open model; compare cost, dimension and maximum input length before choosing (see Embeddings).

Rules that avoid common mistakes: embed queries and documents with the same model and the same version (vectors from different models live in unrelated spaces and cannot be compared); re-embed the corpus when you change models; follow any query or document instruction prefixes a model requires; and note that embeddings carry the biases of their training text (see Fairness & Responsible ML).

Embeddings for categorical and tabular data

High-cardinality categorical features (user id, product id, zip code) are poorly served by one-hot encoding. A neural network can learn one embedding per feature, concatenated with the numeric features and passed to dense layers; a rule of thumb for the dimension is a small fraction of the cardinality, for example the fast.ai heuristic min(600, round(1.6 * n_cat ** 0.56)), tuned on validation data. Handle unseen and rare categories with an explicit unknown bucket. The learned vectors can also be reused as input features for gradient-boosting models. For many tabular problems gradient boosting with ordinary encodings is competitive and simpler; see Tabular Data & Gradient Boosting and Feature Engineering. Recommender systems follow the same idea: user and item embeddings whose dot product predicts an interaction (matrix factorisation is the linear special case).

Inspecting embeddings

A 300-dimensional space cannot be drawn, so reduce it to 2 dimensions:

  • PCA is linear, deterministic and preserves global variance; start here (see Math for Machine Learning).

  • t-SNE and UMAP preserve local neighbourhoods. Cluster sizes, distances between clusters and cluster counts in these plots are not reliable; results change with perplexity or neighbour count and the random seed. Treat them as a way to spot problems, not as measurements.

Quantitative checks are better: nearest-neighbour inspection of a few items, retrieval metrics (recall at k) on labelled pairs, a linear probe (train a linear classifier on frozen embeddings and report accuracy), and clustering quality on labelled data. A quick PCA projection with scikit-learn:

import numpy as np
from sklearn.decomposition import PCA

rng = np.random.default_rng(0)
vectors = np.vstack([rng.normal(loc=0.0, size=(50, 64)), rng.normal(loc=3.0, size=(50, 64))])

coords = PCA(n_components=2, random_state=0).fit_transform(vectors)
print(coords.shape)                                   # (100, 2): ready for a scatter plot

Source: scikit-learn: PCA and TSNE

Pitfalls

  • Mixing embeddings from different models or versions in one index.

  • Forgetting padding_idx or mask_zero, so padding vectors are trained and pooled into averages.

  • Fitting the vocabulary (TextVectorization.adapt, a tokeniser) on test data; fit it on training data only.

  • Fine-tuning a huge pre-trained table with a large learning rate and destroying it; freeze first, then unfreeze with a small rate.

  • Using max_norm or sparse gradients without checking optimiser support.

  • Drawing conclusions from t-SNE distances or from a handful of cherry-picked analogies.

  • Comparing vectors with a measure different from the training objective.

  • Ignoring that embeddings may leak or encode sensitive attributes present in the training data.