Embeddings and Representation Learning
Imagine you must teach a neural network the relationship between "king," "queen," "man," and "woman." You must do this without ever telling it these words are related. One-hot vectors treat every word as equidistant from every other word. So "king" is no closer to "queen" than to "banana." Yet a system that recommends products, translates sentences, or ranks search results must know better. It must somehow know that "king" and "queen" share structure that "king" and "banana" lack. This is the core problem embeddings solve. They turn discrete, symbolic objects — words, users, product IDs, graph nodes, molecules — into dense vectors. A differentiable model can then reason about these vectors. The idea matters because almost nothing a deep network operates on is natively dense and continuous. Vocabulary indices, categorical features, and node identifiers are symbols with no inherent geometry. Embeddings manufacture that geometry by learning a mapping from symbols to points in . This mapping ensures distances and directions in the vector space encode meaningful relationships. These relationships include semantic similarity, co-occurrence statistics, or task-relevant proximity. Once entities live in a shared continuous space, more tools become available. The entire machinery of linear algebra, gradient descent, and neural computation can operate on them. This article builds on ideas from Autoencoders and Undercomplete and Regularized Autoencoders. Both are ways of compressing high-dimensional data into compact codes. Embeddings generalize that compression principle to discrete inputs. They replace a bottleneck layer with a lookup table. This table is optimized so that geometric structure reflects distributional structure. Distributional structure is the tendency of entities that appear in similar contexts to behave similarly. This is the distributional principle: "a word is characterized by the company it keeps." We cover the precise mathematical formulation of embedding layers. We examine the classic algorithms that popularized dense representations (word2vec, GloVe). We explain the mechanics of training via negative sampling. We present complexity and correctness arguments for why these methods recover meaningful geometry. We survey common failure modes. Finally, we trace the historical arc from distributional semantics to modern contextual and graph embeddings. This sets up the transition to Graph Neural Networks: An Introduction. There, embeddings become node-level, and message-passing enriches them with structural context.
- Embeddings map discrete symbols (words, IDs, nodes) to dense, trainable vectors that encode similarity geometrically.
- The distributional hypothesis — similar contexts imply similar meaning — is the statistical principle embeddings exploit.
- An embedding layer is a differentiable lookup table: , indexed and updated by gradient descent.
- word2vec (skip-gram/CBOW) and GloVe are landmark algorithms; negative sampling makes softmax over huge vocabularies tractable.
- Embedding tables cost memory; training cost per step is with negative sampling, not .
- Embeddings generalize far beyond words — to users, items, graph nodes, and categorical features — feeding directly into architectures like graph neural networks.
Embeddings replace symbolic identity with learned geometry, so that "distance in vector space" becomes a proxy for "similarity in meaning or function."
The idea
Formally, let be a discrete vocabulary of entities (words, item IDs, graph nodes). An embedding is a function that is typically implemented as a matrix , where row is the vector for entity . Unlike a hand-crafted feature map, is learned: its entries are parameters trained jointly with, or as a precursor to, a downstream task. The dimension (often 50–1024) is far smaller than (often –), so the embedding table performs a kind of compression analogous to the bottleneck of an autoencoder — except the "input" is a one-hot indicator rather than a rich signal, and the compression target is distributional co-occurrence rather than reconstruction of the input itself. The distributional hypothesis, articulated by linguists (Firth, Harris) well before deep learning, states that entities occurring in similar contexts tend to have similar meaning. This is the statistical principle that makes embeddings learnable at all: if the training objective rewards vectors that predict correct contexts (or co-occurrence statistics), then vectors for distributionally similar entities are pushed toward similar regions of space, purely as a byproduct of optimizing a predictive or reconstructive loss. No human ever labels "king" and "queen" as related; the geometry emerges from statistics. Two broad families realize this idea. Count-based methods (e.g., latent semantic analysis, GloVe) build an explicit co-occurrence matrix (entries = how often and co-occur) and factorize or regress on it directly, analogous to how an undercomplete autoencoder finds a low-rank code that best reconstructs high-dimensional input. Predictive methods (e.g., word2vec) never materialize the co-occurrence matrix; instead they train a lightweight neural network to predict context from target (or vice versa), and the learned weight matrix becomes the embedding table. Both families provably converge, under mild assumptions, toward embeddings whose inner products approximate a (shifted, scaled) pointwise mutual information matrix — this is the theoretical bridge connecting the two views, established rigorously by Levy & Goldberg (2014).
How it works
We walk through the skip-gram model with negative sampling (SGNS), the algorithm underlying word2vec, since it is the cleanest illustration of embedding mechanics and generalizes directly to non-textual entities (items, nodes, users).
Setup. Fix a window size . For each position in a corpus, the target word and each context word for form a training pair . Maintain two embedding matrices: for target (input) vectors and for context (output) vectors. The probability that word is a true context of word is modeled with a sigmoid of the dot product:
Negative sampling. Computing a softmax over the entire vocabulary for every pair is per update — prohibitive when is millions. Instead, SGNS samples "negative" words from a noise distribution (typically unigram frequency raised to the power , which smooths out very frequent words) and trains a binary classifier: is a real pair or a random pair? The loss for one true pair with negatives is:
This turns an expensive multi-class problem into cheap binary ones. ``` ALGORITHM SkipGramNegativeSampling(corpus, d, window, k, lr, epochs) Input: corpus sequence of tokens d embedding dimension window max context radius k number of negative samples per positive pair lr learning rate epochs number of passes over corpus Output: E, C |V| x d target and context embedding matrices V <- build_vocabulary(corpus) E <- random_init(|V|, d) # target embeddings C <- random_init(|V|, d) # context embeddings noise_dist <- unigram_freq(V) ** 0.75, normalized to sum to 1 for epoch in 1..epochs: for t in positions of corpus: window_size <- random_int(1, window) # dynamic window (as in word2vec) for j in -window_size..window_size, j != 0: if t + j out of corpus bounds: continue target <- corpus[t] context <- corpus[t + j]
# positive update score <- sigmoid(dot(E[target], C[context])) grad_common <- lr (1 - score) E[target] += grad_common C[context] C[context] += grad_common * E[target]
# negative updates for i in 1..k: neg <- sample(noise_dist) while neg == context: neg <- sample(noise_dist) score_neg <- sigmoid(dot(E[target], C[neg])) grad_neg <- lr (0 - score_neg) E[target] += grad_neg C[neg] C[neg] += grad_neg * E[target] return E, C ``` Notice the two update rules are gradient-ascent steps on and respectively — each derived from differentiating above with respect to and (or ). In production, the final word embedding is usually just (context vectors are discarded or averaged in). The same recipe generalizes immediately: replace "word" with "item" and "context" with "co-purchased items" to get item2vec; replace "word" with "graph node" and "context" with "nodes on a random walk" to get DeepWalk/node2vec — a direct bridge to Graph Neural Networks: An Introduction, where embeddings are refined further by aggregating neighbor information rather than relying solely on random-walk co-occurrence.
Complexity & correctness
Space. An embedding table for vocabulary size and dimension requires parameters and memory. This is unavoidable — you need at least one -dimensional vector per distinguishable entity — but it dominates model size in many systems: a 1M-word vocabulary with is 300 million floats (1.2 GB in float32), often larger than the rest of the network combined. Techniques like subword tokenization (byte-pair encoding), hashing tricks, and low-rank factorized embeddings (used in ALBERT) exist specifically to control this term.
Time, naïve softmax. A full softmax objective for predicting context word given target ,
requires summing over all vocabulary items for every single training pair, giving work per update — infeasible at web scale ( in the millions, billions of training pairs).
Time, negative sampling. SGNS replaces this with binary decisions (one true pair, sampled negatives), each costing for a dot product and its gradient. Total per-pair cost is , independent of . With typically 5–20, this is a –-fold speedup over full softmax for realistic vocabularies, at the cost of optimizing an approximate objective rather than the exact conditional log-likelihood.
Why the approximation is justified (correctness sketch). Negative sampling is not merely a heuristic hack — Levy & Goldberg (2014) showed that the SGNS objective, at its optimum (with the embedding dimension unconstrained), satisfies
where is the pointwise mutual information between and estimated from corpus co-occurrence counts. The derivation: differentiate the expected SGNS log-likelihood over the true joint distribution with respect to the free variable , set to zero, and solve — this reveals SGNS is implicitly performing a weighted, shifted matrix factorization of the PMI matrix. This is precisely what count-based methods like GloVe explicitly optimize for:
where is a weighting function that down-weights rare co-occurrences. The convergence of two independently derived algorithms — one predictive, one count-based — onto the same target quantity (a shifted, weighted PMI matrix) is strong theoretical evidence that embedding geometry is not an artifact of a particular training scheme but reflects a genuine statistical regularity in co-occurrence data.
Why the resulting geometry supports analogy arithmetic. The famous result follows heuristically from the PMI-factorization view: if "king" and "queen" differ from "man" and "woman" by a roughly consistent shift in co-occurrence log-odds with a set of "royalty" context words, and the mapping from PMI differences to embedding differences is approximately linear (guaranteed locally by the factorization objective), then vector offsets transfer between analogous pairs. This is an empirical regularity with a plausible linear-algebraic explanation, not a theorem — it holds well for frequent, well-separated relations and degrades for rare words or polysemous terms.
Tradeoffs. Predictive methods (word2vec) are cheaper per update and stream well over huge corpora without ever materializing ; count-based methods (GloVe) can exploit fast matrix factorization solvers and are more sample-efficient on smaller corpora since they use aggregate statistics rather than one context pair at a time. Both produce static embeddings: one vector per word type regardless of context, which cannot disambiguate "bank" (river) from "bank" (finance) — a limitation resolved by later contextual models (ELMo, BERT) that recompute embeddings per-token conditioned on the surrounding sequence.
Worked example
Consider a toy corpus with vocabulary and for visualizability. Suppose after training on a corpus rich in royalty and fruit contexts, we obtain (illustrative, rounded) embeddings:
| Word | ||
|---|---|---|
| king | 2.0 | 3.1 |
| queen | 2.3 | 3.0 |
| man | 1.9 | 0.4 |
| woman | 2.2 | 0.3 |
| apple | -3.0 | 1.1 |
| banana | -3.2 | 1.0 |
Trace the analogy computation step by step: 1. . 2. Add : . 3. Compare to — an exact match in this illustrative table, and in real trained embeddings typically the nearest neighbor by cosine similarity among all vocabulary vectors. Now trace why the geometry separates royalty from fruit. Cosine similarity between "king" and "queen":
extremely close, reflecting that "king" and "queen" appear in overlapping royal contexts (crown, throne, palace). Cosine similarity between "king" and "banana":
near zero/negative, reflecting near-disjoint context distributions. This mirrors the underlying training dynamic: "king" and "banana" almost never co-occur with the same context words, so negative sampling repeatedly pushes their dot product down (toward ), while "king" and "queen" share many true context pairs, repeatedly pushing their dot product up. The geometry is the accumulated residue of millions of such small pairwise nudges — exactly the gradient updates traced in the pseudocode above.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Treating embeddings as fixed "ground truth" features | Forgetting they were trained on a specific corpus/task | Poor transfer to domains with different word distributions (e.g., medical text) |
| Using too small (negative samples) | Cutting corners on compute | Noisy gradient estimates, slower/unstable convergence |
| Ignoring frequent-word dominance | Using raw unigram frequency as noise distribution | Stopwords like "the" flood every negative sample; use smoothing |
| Comparing embeddings from different training runs directly | Embedding spaces are only defined up to rotation | Absolute coordinates are meaningless; only relative geometry (angles, distances) transfers |
| Averaging static embeddings to represent polysemous words | Assuming one vector suffices per word type | "Bank" (river) and "bank" (finance) collapse into an uninterpretable average vector |
| Not freezing/handling out-of-vocabulary tokens at inference | Deploying with a fixed vocabulary trained offline | Crashes or silent degradation on unseen words; needs UNK token or subword fallback |
Pioneers & history
Distributional semantics predates deep learning by decades, rooted in structural linguistics, but its computational realization as trainable dense vectors is a product of the neural-network era. The person most associated with popularizing scalable neural word embeddings is Tomáš Mikolov, whose word2vec (2013) made the technique practical and famous through the analogy demonstrations that captured public imagination.
Origins · 1 minTomáš Mikolov and how this was discovered
Mikolov, working with colleagues at Google, showed that a shallow, almost trivially simple neural network — no hidden nonlinearity, just a linear projection and a softmax-like objective — could learn embeddings whose vector arithmetic solved analogy puzzles that had eluded far more complex NLP pipelines. The insight was not a new architecture but a new objective (skip-gram with negative sampling) paired with the empirical observation that distributional statistics, if optimized efficiently at massive scale, yield surprisingly rich linear structure. This combination of simplicity and scale became a template for much of subsequent representation learning.
Where this matters
Embeddings are now the substrate on which most large-scale machine learning systems operate. Search engines and recommender systems embed queries, documents, users, and items into shared vector spaces so that relevance and similarity reduce to nearest-neighbor search — the technology behind approximate nearest neighbor libraries (FAISS, ScaNN) that power retrieval at billion-item scale. Large language models begin every forward pass with a learned embedding lookup that converts token IDs into dense vectors before any transformer computation occurs; the embedding table is frequently among the largest single parameter blocks in the model. Graph-structured domains — social networks, molecule graphs, knowledge graphs — use node embeddings (DeepWalk, node2vec) as either standalone features or as the initialization layer feeding into Graph Neural Networks: An Introduction, where message passing further refines embeddings using explicit graph topology rather than co-occurrence statistics alone. Categorical features in tabular deep learning (user IDs, zip codes, product categories) are routinely embedded rather than one-hot encoded, dramatically shrinking both memory and the effective input dimensionality that downstream layers must process.
Ask the tutor: How does negative sampling's noise distribution exponent (0.75) affect which words get treated as "hard negatives" during training?
How is an embedding layer different from a one-hot encoding followed by a dense layer?
Mathematically they compute the same thing: multiplying a one-hot vector by a weight matrix simply selects one row. An embedding layer is the efficient implementation of this idea — instead of materializing a sparse one-hot vector and performing a full matrix multiply, it directly indexes the row corresponding to the input ID. This turns an operation into an lookup, and the gradient similarly only updates the row(s) actually accessed rather than the entire matrix. Conceptually they are identical; computationally the embedding layer avoids ever constructing the sparse vector, which matters enormously when is in the millions.
Why do embedding dimensions typically range from 50 to a few hundred, rather than being much larger or smaller?
Too small a dimension ( or ) forces many distinct concepts to be squeezed into too little geometric room, causing interference — unrelated words end up with nontrivial dot products purely due to lack of space, hurting downstream accuracy. Too large a dimension increases parameter count (), risks overfitting on rarer words with few training co-occurrences, and slows every downstream computation that consumes the embedding. Empirically, task performance on analogy and similarity benchmarks improves with up to a point (often 200–400 for word embeddings) and then plateaus or slightly degrades, mirroring a classic bias–variance tradeoff.
Are word2vec and GloVe still used in modern NLP systems, or have they been fully replaced?
Contextual embeddings from transformer models (BERT, GPT-family) have replaced static embeddings as the default for state-of-the-art NLP because they resolve polysemy and capture long-range dependencies. However, static embeddings remain useful where compute is constrained, interpretability matters, or the task is simple similarity/analogy retrieval rather than deep contextual understanding. The core algorithmic ideas — negative sampling, the distributional principle, the PMI-factorization connection — persist inside modern systems too, since the initial embedding layer of a transformer is trained with the same fundamental distributional signal, just optimized jointly with the rest of a much larger model.
How do embeddings for non-textual entities, like graph nodes or e-commerce items, get trained without a natural notion of a sentence?
The trick is to manufacture a sequence that plays the role of a sentence. DeepWalk and node2vec perform random walks over a graph, treating each walk as a "sentence" of node IDs and each node's neighbors within the walk as its "context" — then run skip-gram exactly as described for words. Similarly, item2vec treats a user's purchase or click sequence as a sentence and co-purchased or co-clicked items as context. The distributional hypothesis transfers directly: entities that appear in similar sequential or structural contexts are pushed to nearby points in the embedding space, regardless of whether those entities are words, products, or graph nodes.
What does it mean for embedding arithmetic like king − man + woman ≈ queen to "work," and how reliable is it really?
It means that certain semantic relations correspond approximately to consistent vector offsets, so that transporting an offset learned from one pair (king, queen) to another word (woman) lands near the analogous target (queen's counterpart). This is a genuine empirical regularity supported by the PMI-factorization theory, but it is not guaranteed to hold for every relation, especially rare words, multi-word relations, or highly ambiguous terms. In practice, analogy accuracy on curated benchmarks (like the Google analogy dataset) can exceed 70–80% for common semantic and syntactic relations, but drops substantially for rarer or culturally specific analogies, and the effect is considered an emergent regularity rather than a mathematically guaranteed property of the training objective.
How does representation learning via embeddings relate to what autoencoders do?
Both are instances of learning a compressed, information-preserving code for high-dimensional or high-cardinality data, and both rely on a bottleneck (the code dimension in embeddings, the latent dimension in an autoencoder) that forces the model to discard redundant information while retaining what's predictively useful. The key difference is the objective: an undercomplete autoencoder is trained to reconstruct its own continuous input, while an embedding table is trained to predict discrete co-occurrence relationships between symbols that have no native continuous representation to reconstruct. Both produce dense codes whose geometry reflects the statistical structure of the training distribution, making embeddings a natural generalization of autoencoding to symbolic, discrete domains.
Why do embeddings matter for the transition to graph neural networks?
Random-walk embedding methods like DeepWalk and node2vec are the direct predecessor to graph neural networks: both aim to produce a dense vector per graph node that captures its structural role. The limitation of pure embedding-table approaches is that they are transductive and static — they cannot generalize to unseen nodes and ignore node features entirely, relying only on co-occurrence in random walks. Graph neural networks address this by computing node embeddings dynamically through message passing, aggregating neighbor features at inference time, which allows them to generalize to new nodes and incorporate rich node attributes alongside graph topology.