Skip to content
E
Educatum

Explain the fundamental concept of embeddings in machine learning and how they represent information in a more compact form compared to raw input data.

Curated by Educatum AI teamLast updated:
Embeddings
Direct Answer

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 E:V→RdE: \mathcal{V} \to \mathbb{R}^d from discrete, sparse, or high-dimensional objects (tokens, categories, users, graph nodes, images) into a compact, continuous dd-dimensional vector space where d≪∣V∣d \ll |\mathcal{V}|.

Why embeddings outperform raw sparse encodings (such as one-hot vectors):

  1. Dimensionality Compression: A vocabulary of 50,00050{,}000 tokens encoded as one-hot vectors requires 50,00050{,}000-dimensional binary vectors with 49,99949{,}999 zeros. A learned embedding compresses each token into e.g. d=256d = 256 or 40964096 continuous floats—equivalent mathematically to selecting row ii of a weight matrix E∈R∣V∣×d\mathbf{E} \in \mathbb{R}^{|\mathcal{V}| \times d} without storing sparse zeros.
  2. Semantic Geometry: Every one-hot vector is strictly orthogonal to every other one-hot vector (ei⊤ej=0e_i^\top e_j = 0 and ∥ei−ej∥2=2\|e_i - e_j\|_2 = \sqrt{2} for all i≠ji \neq j), encoding zero notion of similarity. Learned embeddings organize concepts geometrically so related items have smaller Euclidean distance and higher cosine similarity.
  3. Generalization & Compositionality: Downstream neural layers can share statistical strength across synonyms or similar users/items and even reflect analogical directions (e.g., vking−vman+vwoman≈vqueen\mathbf{v}_{\text{king}} - \mathbf{v}_{\text{man}} + \mathbf{v}_{\text{woman}} \approx \mathbf{v}_{\text{queen}}).

Key Terms

  • Embedding Dimension (dd): Size of each dense vector; balances representational capacity against memory and overfitting risk.
  • One-Hot Encoding: Sparse VV-dimensional indicator vector with orthogonality between all distinct categories.
  • Embedding Lookup Matrix (E∈RV×d\mathbf{E} \in \mathbb{R}^{V \times d}): Trainable parameter table equivalent to a linear projection applied to a one-hot vector (ei=E⊤1ie_i = \mathbf{E}^\top \mathbf{1}_i).
  • Cosine Similarity: Measures directional alignment u⋅v∥u∥2∥v∥2∈[−1,1]\frac{u \cdot v}{\|u\|_2 \|v\|_2} \in [-1, 1]; 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 1−cos⁡θ1 - \cos\theta) 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}")
  • 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 E\mathbf{E} 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.