Embeddings: Meaning as Vectors
How neural networks turn words, tokens, products or images into dense vectors where distance means similarity. One-hot vs embeddings, word2vec, cosine similarity, vector analogies, and contextual embeddings.
Neural networks only do arithmetic on numbers, so every discrete thing — a word, a Token, a user, a product, a movie — has to become a Vector. An Embedding is a learned, dense vector (typically 64–4096 numbers) chosen so that similar things end up close together. Embeddings are the first layer of every language model, the core of semantic search and RAG, and the engine of recommender systems.
From one-hot to dense vectors
The naive encoding is one-hot: with a vocabulary of 50,000 words, each word is a 50,000-long vector with a single 1. It has two problems: it's huge and sparse, and every pair of words is equally different — the dot product of any two different one-hot vectors is 0, so “cat” is as far from “dog” as from “carburettor”. An embedding layer replaces this with a dense vector of, say, 300 numbers that the model learns.
- E
- the Embedding matrix (learned during training)
- ∈
- “is an element of / has the type”
- ℝ^(V × d)
- the set of real-valued matrices with V rows and d columns
- V
- vocabulary size (number of distinct tokens), e.g. 50,000
- d
- embedding dimension, e.g. 300
- embed(i)
- the vector for token id i
- E[i]
- row i of E
- onehot(i)
- a length-V vector of zeros with a single 1 at position i (One-hot encoding)
▸Worked example
Where does the meaning come from?
From the distributional hypothesis: “You shall know a word by the company it keeps” (J. R. Firth, 1957). Words that appear in similar contexts tend to have similar meanings — “coffee” and “tea” both appear near “cup”, “drink”, “hot”. If we train vectors to predict a word's context, words with similar contexts are pushed toward similar vectors. Embeddings can also be learned as a side effect of any task: the first layer of a sentiment classifier or a language model learns embeddings by backpropagation like any other weights.
word2vec
Mikolov et al. (2013) made this fast enough to train on billions of words[1]. word2vec has two variants: CBOW predicts a word from its surrounding words; skip-gram predicts the surrounding words from the centre word. Instead of a full softmax over the vocabulary, skip-gram with negative sampling turns it into a cheap binary task: tell real (word, context) pairs apart from k random “negative” pairs[2].
- maximize
- training adjusts the vectors to make this sum as large as possible (equivalently, minimize its negative)
- log
- natural logarithm; log of a probability near 1 is near 0, near 0 it goes to −∞
- σ
- Sigmoid (logistic function): turns a score into a probability
- v_c
- input vector of the centre word (a row of W)
- u_oᵀ v_c
- Dot product of the real context word's output vector u_o with v_c (ᵀ = transpose, i.e. row × column)
- Σ_{k=1..K}
- sum over the K negative (noise) samples
- −u_kᵀ v_c
- minus the score of noise word k: σ of it is the probability that the pair is fake
▸Worked example
GloVe (Pennington et al., 2014) reaches similar vectors by factorizing global word co-occurrence counts[3], and fastText adds sub-word pieces so it can build vectors for unseen or misspelled words (Bojanowski et al., 2016) — useful for morphologically rich languages like Indonesian (makan, makanan, dimakan, memakan).
Measuring similarity and vector arithmetic
- cos(a, b)
- Cosine similarity of vectors a and b (the cosine of the angle between them)
- a · b
- Dot product: multiply matching entries and add them up
- ‖a‖
- length (Euclidean norm) of a: √(a₁² + a₂² + …)
- ‖b‖
- length of b
- ∈ [−1, 1]
- the result always lies between −1 and 1
▸Worked example
Cosine similarity is the standard way to compare embeddings (if vectors are normalized to length 1, it equals the Dot product). word2vec vectors famously encode relations as directions: vector(“king”) − vector(“man”) + vector(“woman”) is closest to vector(“queen”); similar offsets appear for country → capital and verb tenses[1]. Caveats: the analogy search usually excludes the input words, and many analogies work far less cleanly than the famous examples suggest. Jay Alammar's illustrated guide walks through all of this visually[4].
- Clusters: drag to rotate and find the groups — animals, fruits, countries/capitals, royalty/gender, verbs. Which clusters sit close to each other, and why might that be?
- Nearest neighbours: click a word (e.g. an animal). The neighbour list is sorted by cosine similarity — check that the top ones are from the same cluster.
- Analogy: in the analogy panel compute king − man + woman. Watch the arrows: the “man → woman” offset is added to “king”, and the nearest word is highlighted.
- Country → capital: try a capital − its country + another country. Does the offset carry over? Try one where it fails, and think about why real embeddings are less tidy.
- Projection caveat: rotate until two clusters seem to overlap. In 3D they are separate — and real 300-D embeddings squeezed into 2D/3D (PCA, t-SNE) suffer the same distortions.
Static vs contextual embeddings
| Static (word2vec, GloVe) | Contextual (BERT, GPT hidden states) | |
|---|---|---|
| One vector per… | word type (“bank” always the same) | token occurrence (“river bank” ≠ “bank loan”) |
| Produced by | A lookup table | A deep network reading the whole sentence |
| Typical use | Lightweight NLP, features, teaching | Modern NLP, semantic search, RAG (sentence embeddings) |
Modern models still start with a static lookup table (token embeddings), but every Transformer layer mixes in context, so the hidden states are contextual. Sentence/document embeddings (e.g. from Sentence-Transformers models) pool these into one vector per text — the basis of semantic search and retrieval-augmented generation. The same idea works for any modality: CLIP (CLIP) embeds images and captions into a shared space.
- What it is
- Length of each embedding vector.
- ↑ If you increase it
- Can encode more fine-grained distinctions; parameters grow linearly (V × d) and so do storage and search cost in a vector database. With little data, extra dimensions are noisy and gains saturate.
- ↓ If you decrease it
- Smaller and faster, but unrelated items get squeezed together and similarity becomes less precise.
- Typical values
- word2vec: 100–300. Sentence embedding models: 384–1024. LLM token embeddings: 768–8192+.
- What it is
- How many words on each side of the centre word count as its context.
- ↑ If you increase it
- Captures broader, more topical similarity (“doctor” near “hospital”).
- ↓ If you decrease it
- Captures tighter, more syntactic/functional similarity (“doctor” near “nurse”, “surgeon”).
- Typical values
- 2–10; gensim default 5.
- What it is
- How many random “wrong” context words are contrasted with each real one.
- ↑ If you increase it
- Better vectors on small corpora, but slower training.
- ↓ If you decrease it
- Faster; on very large corpora a few negatives are enough.
- Typical values
- 5–20 for small datasets, 2–5 for large ones (Mikolov et al.).
from gensim.models import Word2Vec
import torch
import torch.nn as nn
# 1) Train word2vec (skip-gram + negative sampling) on tokenized sentences
sentences = [["the", "king", "rules", "the", "land"], ["the", "queen", "rules", "too"]] # use a real corpus!
w2v = Word2Vec(sentences, vector_size=100, window=5, min_count=1, sg=1, negative=5, epochs=20)
print(w2v.wv.most_similar("king", topn=3))
print(w2v.wv.most_similar(positive=["king", "woman"], negative=["man"], topn=1)) # needs a big corpus
# 2) A learned embedding layer inside a PyTorch model
emb = nn.Embedding(num_embeddings=50_000, embedding_dim=300)
ids = torch.tensor([[12, 512, 7]]) # (batch, seq_len) of token ids
vectors = emb(ids) # (1, 3, 300)
sim = nn.functional.cosine_similarity(vectors[0, 0], vectors[0, 1], dim=0)nn.Embedding lookup table[6].- Embeddings inherit biases from their training text: Bolukbasi et al. found analogies like “man : computer programmer :: woman : homemaker” in word2vec trained on news[5]. Audit before using them in decisions about people.
- Mixing models: vectors from two different embedding models live in different spaces — never compare them directly.
- Out-of-vocabulary words get no vector in word2vec/GloVe; use subword models (fastText, BPE-based models).
- Cosine vs dot product: if vectors aren't normalized, dot product favours long vectors (often frequent words). Use the metric the model was trained with.
- Trusting 2D plots: t-SNE/UMAP projections distort distances; check claims in the original space.
▸Go deeper: why embedding gradients are sparse, and what word2vec really learns
In one training step only the rows of E for tokens in the batch receive gradient — the rest are untouched. That's why embedding tables can be enormous (recommendation systems use billions of rows) and why nn.Embedding(sparse=True) with a sparse optimizer exists. Theoretically, Levy & Goldberg (2014) showed skip-gram with negative sampling implicitly factorizes a shifted pointwise mutual information (PMI) matrix of word–context counts — linking word2vec to older count-based methods and to GloVe[3].
Quiz
nn.Embedding(50000, 256) layer contain?References
- [1]Efficient Estimation of Word Representations in Vector SpacePaperMikolov, Chen, Corrado & Dean2013arxiv.org
- [2]Distributed Representations of Words and Phrases and their CompositionalityPaperMikolov et al.2013arxiv.org
- [3]GloVe: Global Vectors for Word RepresentationPaperPennington, Socher & Manning2014aclanthology.org
- [4]The Illustrated Word2vecArticleAlammar2019jalammar.github.io
- [5]Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word EmbeddingsPaperBolukbasi et al.2016arxiv.org
- [6]torch.nn.EmbeddingDocsPyTorchdocs.pytorch.org