Explain the fundamental concept of embeddings in machine learning and how they represent information in a more compact form compared to raw input data.
Embeddings map discrete, high-dimensional inputs—such as words, subwords, users, or items—into low-dimensional, dense continuous vectors learned directly from data. Unlike orthogonal one-hot vectors that treat every category as equidistant, embeddings place semantically related items at smaller Euclidean distances and higher cosine similarities. This compact representation captures latent structure and enables neural networks to generalize across rare or related entities.
Study Card: Understanding Embeddings in Machine Learning
Direct Answer
An embedding is a learned mapping from discrete, sparse, or high-dimensional objects (tokens, categories, users, graph nodes, images) into a compact, continuous -dimensional vector space where .
Why embeddings outperform raw sparse encodings (such as one-hot vectors):
- Dimensionality Compression: A vocabulary of tokens encoded as one-hot vectors requires -dimensional binary vectors with zeros. A learned embedding compresses each token into e.g. or continuous floats—equivalent mathematically to selecting row of a weight matrix without storing sparse zeros.
- Semantic Geometry: Every one-hot vector is strictly orthogonal to every other one-hot vector ( and for all ), encoding zero notion of similarity. Learned embeddings organize concepts geometrically so related items have smaller Euclidean distance and higher cosine similarity.
- Generalization & Compositionality: Downstream neural layers can share statistical strength across synonyms or similar users/items and even reflect analogical directions (e.g., ).
Key Terms
- Embedding Dimension (): Size of each dense vector; balances representational capacity against memory and overfitting risk.
- One-Hot Encoding: Sparse -dimensional indicator vector with orthogonality between all distinct categories.
- Embedding Lookup Matrix (): Trainable parameter table equivalent to a linear projection applied to a one-hot vector ().
- Cosine Similarity: Measures directional alignment ; higher values indicate stronger similarity.
Example
Consider representing a 50,000-word vocabulary:
- One-hot vectors assign zero overlap between
"king"and"queen", and equal distance between"king"and"apple". - After training an embedding model on text co-occurrence,
"king"and"queen"share latent dimensions for royalty and human nouns. Consequently, the Euclidean distance (or cosine distance ) between"king"and"queen"is much smaller, and their cosine similarity is significantly higher, than between"king"and"apple".
Code Implementation
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
vocab = ["king", "queen", "man", "woman", "apple", "banana"]
word_to_idx = {w: i for i, w in enumerate(vocab)}
# Multi-label co-occurrence targets (symmetric neighborhood indicator in [0, 1])
# Royal/person words co-occur strongly with each other; fruits co-occur with each other.
co_occurrence = torch.tensor([
[1.0, 1.0, 1.0, 0.8, 0.0, 0.0], # king
[1.0, 1.0, 0.8, 1.0, 0.0, 0.0], # queen
[1.0, 0.8, 1.0, 1.0, 0.1, 0.0], # man
[0.8, 1.0, 1.0, 1.0, 0.0, 0.1], # woman
[0.0, 0.0, 0.1, 0.0, 1.0, 1.0], # apple
[0.0, 0.0, 0.0, 0.1, 1.0, 1.0], # banana
], dtype=torch.float32)
torch.manual_seed(42)
embedding_dim = 16
emb_layer = nn.Embedding(len(vocab), embedding_dim)
proj_head = nn.Linear(embedding_dim, len(vocab))
optimizer = optim.AdamW(list(emb_layer.parameters()) + list(proj_head.parameters()), lr=5e-2)
bce_logits = nn.BCEWithLogitsLoss() # Proper loss for multi-label co-occurrence targets
indices = torch.arange(len(vocab))
for _ in range(150):
logits = proj_head(emb_layer(indices))
loss = bce_logits(logits, co_occurrence)
optimizer.zero_grad()
loss.backward()
optimizer.step()
with torch.no_grad():
embs = emb_layer.weight
sim_king_queen = F.cosine_similarity(embs[word_to_idx["king"]], embs[word_to_idx["queen"]], dim=0).item()
sim_king_apple = F.cosine_similarity(embs[word_to_idx["king"]], embs[word_to_idx["apple"]], dim=0).item()
sim_apple_banana = F.cosine_similarity(embs[word_to_idx["apple"]], embs[word_to_idx["banana"]], dim=0).item()
print(f"Embedding matrix shape: {embs.shape}")
print(f"Cosine sim(king, queen): {sim_king_queen:.4f}")
print(f"Cosine sim(apple, banana): {sim_apple_banana:.4f}")
print(f"Cosine sim(king, apple): {sim_king_apple:.4f}")
Related Concepts
- Dimensionality Reduction (PCA, UMAP, t-SNE): Unsupervised compression/visualization methods versus task- or self-supervised neural embeddings.
- Static vs. Contextual Embeddings: Fixed token lookup tables (
nn.Embedding, Word2Vec) versus Transformer hidden states modulated by context. - Weight Tying: Reusing the token embedding matrix as the output softmax head in LLMs reduces parameter count significantly.
- Vector Databases & ANN Search: Embeddings enable sub-linear semantic search (HNSW, IVF-PQ) across billions of documents and multimodal assets.