Embedding Geometry and Analogies
Consider a simple question: what word relates to queen the way man relates to king? A human answers instantly. A machine must find this relationship in numbers alone. Word embeddings represent each word as a dense vector. Remarkably, the geometry of these vectors encodes semantic relationships as directions and distances. This article explores what happens after training. Once you have vectors from Negative Sampling and Training Word2Vec or GloVe, what structure do they actually have? What can you legitimately do with it? The stakes are real. Search engines rank documents by cosine similarity between query and passage embeddings. Recommendation systems cluster items in embedding space. Translation systems align embedding spaces across languages. Every one of these systems inherits whatever geometric structure the training corpus imprinted onto the vectors. This structure may be useful or harmful. Understanding embedding geometry is not a mathematical curiosity. It is a prerequisite for building, debugging, and auditing production NLP systems. The famous demonstration that vector arithmetic can solve analogies — king − man + woman ≈ queen — sparked enormous excitement. Embeddings seemed to offer a semantic calculus. But the same geometry that captures "Paris is to France as Tokyo is to Japan" also captures something else. It captures "doctor is to man as nurse is to woman," reflecting societal biases baked into training text. The tool that makes embeddings useful is the same tool that makes their failures measurable. To a degree, it also makes those failures correctable. This article gives a precise account of embedding geometry. It covers how cosine similarity and vector offsets work mathematically. It explains why the analogy task succeeds as often as it does, with honest statistics on how often that really is. It shows how bias manifests as measurable geometric asymmetry. It also covers debiasing techniques built directly on this geometry. It closes by pointing toward Contextual Embeddings, where a single static vector per word is no longer enough.
- Word embeddings place semantically related words close together, measured by cosine similarity rather than raw distance.
- The analogy task `a : b :: c : ?` is solved by vector arithmetic: find the word closest to `vec(b) − vec(a) + vec(c)`.
- This works because embedding training tunes vectors so that consistent relational offsets emerge across word pairs.
- Analogy accuracy is real but overstated by early benchmarks; performance drops sharply outside curated categories.
- Human bias in text becomes measurable geometric bias in embeddings — e.g. a gender axis correlates with occupation words.
- Debiasing methods (hard debiasing, subspace projection) edit the geometry directly, with real but partial success.
Embedding spaces encode semantic and relational structure as geometric regularities — directions, distances, and offsets — which makes them both powerfully useful and measurably biased.
The idea
An embedding assigns each word in a vocabulary a vector , typically with between 50 and 300. Training via Negative Sampling and Training Word2Vec or the co-occurrence factorization of GloVe arranges these vectors so that words appearing in similar contexts end up close together. "Geometry" here means the study of that arrangement: which directions correspond to which meanings, how distance relates to similarity, and whether relationships between word pairs are systematically encoded as consistent vector offsets. The primary similarity measure is cosine similarity, not Euclidean distance:
Cosine similarity measures the angle between two vectors, ignoring their magnitude. This matters because word frequency strongly affects vector length during training — frequent words tend to have larger norms — but frequency is not the semantic property we want to measure. Two vectors pointing in nearly the same direction are treated as similar regardless of how long they are, which normalizes away this frequency artifact. The analogy task asks: given a relationship exemplified by the pair , and a third word , find such that exhibits the same relationship. Formally, , e.g. man : king :: woman : queen. The vector-offset method, sometimes called 3CosAdd, proposes:
The intuition: if the relationship "male → royal-female-equivalent" is encoded as a roughly consistent offset vector across many word pairs, then adding that offset to a new word's vector should land near the analogous target. This only works because embedding training does not merely cluster synonyms — it also linearizes certain relational structure, so that "capital-of," "plural-of," and "gender-swap" each correspond, approximately, to a single translation vector usable across many word pairs.
How it works
Step 1 — Cosine similarity for nearest neighbors. Given a query vector, rank all vocabulary vectors by cosine similarity to find the most similar words. This underlies "find synonyms" and retrieval-style applications.
Step 2 — Vector offset for analogies. Compute and search for the nearest neighbor, excluding the three input words themselves (a critical, easily-missed step — without it, the algorithm frequently just returns ).
Step 3 — 3CosMul, a refinement. The additive method has a known failure mode: one large term in the sum can dominate and swamp the others. Levy and Goldberg's multiplicative variant instead computes
using a small (e.g. 0.001) to avoid division by zero. This balances the three similarity terms multiplicatively rather than additively, empirically improving analogy accuracy.
Step 4 — Bias measurement. Define a bias direction, e.g. (or an averaged version over several such pairs via PCA). Project any word vector onto to get a scalar bias score; words like nurse or engineer will show measurable projections along this axis even though gender is not part of their dictionary meaning.
Step 5 — Debiasing. Neutralize non-gendered words by removing their component along , and equalize gendered pairs (like grandmother/grandfather) so they are equidistant from neutral words, preserving the useful part of the relationship while erasing the harmful leakage. ```text function NEAREST(query_vec, V, k, exclude={}): scores = [] for w in V: if w in exclude: continue s = cosine(query_vec, vec[w]) scores.append((s, w)) sort scores descending by s return top k entries function ANALOGY_3COSADD(a, b, c, V):
# a : b :: c : ? target = vec[b] - vec[a] + vec[c] return NEAREST(target, V, k=1, exclude={a, b, c}) function ANALOGY_3COSMUL(a, b, c, V, eps=0.001): best_word, best_score = None, -infinity for d in V: if d in {a, b, c}: continue num = cosine(vec[d], vec[b]) * cosine(vec[d], vec[c]) den = cosine(vec[d], vec[a]) + eps
# shift cosines to [0,2] first in practice, to keep them positive score = num / den if score > best_score: best_score, best_word = score, d return best_word function BIAS_SCORE(w, bias_direction): return dot(vec[w], bias_direction) / norm(bias_direction) function DEBIAS_NEUTRALIZE(w, bias_direction, neutral_set): if w not in neutral_set: return vec[w] proj = (dot(vec[w], bias_direction) / dot(bias_direction, bias_direction)) * bias_direction return normalize(vec[w] - proj) ``` The exclusion set in `NEAREST` is not a minor detail — omitting it is the single most common bug when reimplementing analogy solvers, since itself is almost always the closest vector to when and are similar in magnitude.
Complexity & correctness
Time complexity. Computing cosine similarity between two -dimensional vectors is . A brute-force nearest-neighbor search over vocabulary size costs per query. For (typical pretrained vocabularies) and , this is roughly floating-point operations per analogy query — feasible but non-trivial at scale. In production, approximate nearest neighbor structures (e.g. HNSW graphs, locality-sensitive hashing, or inverted files with product quantization) reduce this to roughly or better in practice, trading a small accuracy loss for large speedups. 3CosMul has the same asymptotic cost as 3CosAdd, since it computes the same three cosine similarities per candidate, only combining them differently.
Space complexity. Storing all vectors requires floats — around 480 MB for , in 32-bit floats. Precomputing vector norms once ( extra space) lets cosine similarity be computed as a single dot product plus lookups rather than recomputing norms per query.
Correctness of the offset method — why it should work at all. This is not a proven theorem but a consequence of the training objective's structure, and it is worth being precise about the argument rather than just asserting the result. In skip-gram with negative sampling, the training objective pushes high for observed (word, context) pairs and low for sampled negatives. Analyses of word2vec (Levy & Goldberg, 2014) show this is implicitly factorizing a shifted pointwise mutual information (PMI) matrix: the dot product approximates , where is the number of negative samples. Now consider a relation like "capital of." If -like statistics behave consistently across many country–capital pairs — because the corpus co-occurrence patterns of "France, capital, Paris" resemble those of "Japan, capital, Tokyo" in aggregate — then the linear structure of the PMI matrix (and hence the factorized embeddings) will encode this consistency as an approximately constant offset vector. The vector offset is only meaningful to the extent that the relation's log-probability structure really is translation-invariant across pairs in the corpus. When it is (frequent, well-attested, symmetric relations like capital-of or plural-of), the offset method works well. When the relation is rare, asymmetric, or lexically inconsistent (irregular plurals, obscure professions), the linear approximation breaks down and accuracy drops sharply — this is an honest limitation, not a bug to be patched.
Why cosine, not Euclidean distance. Word frequency correlates with vector norm because frequent words receive many more gradient updates during training. If we used Euclidean distance , a rare word could appear "far" from a related common word purely due to differing magnitudes, even when perfectly aligned in direction. Cosine similarity divides out this magnitude effect, isolating the semantically meaningful angular component. Formally, for vectors normalized to unit length, , so ranking by cosine similarity and ranking by Euclidean distance on normalized vectors are equivalent — the distinction only matters when vectors are not pre-normalized, which is the typical raw output of training.
Worked example
Take pretrained GloVe-style vectors (illustrative values, dimensions truncated to 4 for hand-tracing; real vectors use 50–300 dimensions):
| word | vector (4-dim illustrative) | ‖v‖ |
|---|---|---|
| man | (0.6, 0.1, 0.3, 0.2) | 0.72 |
| king | (0.7, 0.6, 0.3, 0.2) | 0.98 |
| woman | (0.5, 0.1, 0.7, 0.2) | 0.89 |
| queen | (0.6, 0.6, 0.7, 0.2) | 1.13 |
| apple | (0.1, 0.9, 0.0, 0.3) | 0.95 |
Step 1 — compute the offset.
Step 2 — compare to candidates via cosine similarity. The target vector is compared against every vocabulary word except {man, king, woman}. Against queen = :
(In this illustrative example queen is chosen to exactly equal the target, giving perfect similarity — in real embeddings the match is close, not exact.) Against apple = :
Step 3 — rank and select. queen scores 1.0, apple scores 0.62. queen wins decisively — this is exactly the intended behavior, and it illustrates why the exclusion set matters: without excluding `woman`, note that would also need checking, and for vectors this close in construction, an unexcluded input can sometimes outscore the true answer.
A harder case, showing the limitation. Try Tokyo : Japan :: Berlin : ? (expected: Germany). If the corpus discusses Tokyo and Japan with different surrounding syntax than Berlin and Germany (e.g. one pair appears mostly in travel contexts, the other in historical/political contexts), the offset will not equal closely, and the nearest neighbor to the computed target may be a nearby European city or a generic "country" vector rather than Germany specifically. Published analogy benchmarks report accuracy well above 50% on curated syntactic and common semantic categories (word2vec's original paper reports around 60–70% on its combined test set), but accuracy on rarer or looser semantic relations — rather than the tightly curated capital/country and morphological categories that dominate standard benchmarks — is substantially lower, often below 30%. The gap matters: it is easy to over-generalize from a benchmark built almost entirely from the relation types embeddings are best at.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting to exclude from the search | is very often the closest vector to since the offset is small relative to 's own magnitude | Always exclude the three input words before ranking neighbors |
| Using Euclidean distance instead of cosine | Feels like the "default" distance metric | Normalize vectors or explicitly use cosine; frequency-driven magnitude differences distort raw distance |
| Treating analogy accuracy as proof of "understanding" | High accuracy on curated relation categories creates an illusion of general reasoning | Test on diverse, non-curated relation types before generalizing claims |
| Assuming one offset vector generalizes across all instances of a relation | Some relations (capital-of) are far more linear than others (profession-of) | Report per-category accuracy, not a single aggregate number |
| Ignoring bias direction leakage into "neutral" words | Word co-occurrence statistics reflect societal patterns, not just meaning | Explicitly measure projection onto known bias directions before deployment |
| Debiasing only the axis you tested and declaring the space "fixed" | Bias is multi-dimensional; removing one linear direction leaves correlated bias intact | Treat debiasing as harm reduction, not elimination; re-audit regularly |
Pioneers & history
Origins · 1 minTomas Mikolov and how this was discovered
Mikolov led the team that popularized skip-gram and CBOW models and, crucially, demonstrated the linear analogy structure in their vectors — the observation that made "king − man + woman ≈ queen" a widely cited symbol of what neural word representations could do.
Where this matters
Search and retrieval systems use cosine similarity over embeddings to rank documents, products, and passages, treating query and document embeddings as points in the same geometric space. Recommendation engines position items and users in shared embedding spaces so that "nearby" means "relevant." Machine translation systems have used cross-lingual embedding alignment — literally rotating one language's embedding space onto another's — exploiting the assumption that relational geometry (king-queen, man-woman style offsets) is roughly preserved across languages. Fairness auditing tools built on the Word Embedding Association Test (WEAT) directly measure the geometric bias described here, quantifying how strongly occupation or trait words align with gender or racial identity directions, informing dataset curation and model审计 decisions before deployment. All of this groundwork — static, one-vector-per-word geometry — is also the direct motivation for Contextual Embeddings, where models like BERT and GPT assign a word a different vector depending on its sentence, precisely because a single fixed direction cannot capture how "bank" shifts between "river bank" and "savings bank."
Ask the tutor: How would embedding geometry and the analogy task need to change for a language with rich morphology, where a single "word" can take dozens of inflected forms?
Does the man-king-woman-queen analogy actually always work perfectly?
No. It works reliably as a textbook demonstration because it was chosen (and is often re-chosen) precisely because it works well. Real analogy benchmarks show substantial variation across relation categories — near-perfect on some morphological patterns, much weaker on loose semantic relations. The published aggregate numbers on classic benchmarks (roughly 60–70% for well-tuned word2vec models) already mix strong and weak categories together, so a single headline number understates how uneven performance actually is across relation types.
Why do embeddings encode bias at all if they're "just" trained on word co-occurrence?
Embeddings learn statistical regularities in text, and text reflects the society that produced it, including its historical and ongoing biases. If "engineer" co-occurs more often with masculine pronouns and "nurse" with feminine pronouns in the training corpus, the model has no mechanism to distinguish "this is a linguistic pattern to encode" from "this is a bias to avoid" — it optimizes purely for predictive co-occurrence statistics. Bias in embeddings is a direct, faithful reflection of bias in the input distribution, not a separate malfunction.
What exactly does "hard debiasing" do to the vector space?
It identifies a bias subspace (e.g. via PCA over several gender-defining pairs like he/she, man/woman), then for words defined as gender-neutral, projects out their component along that subspace so their vectors have zero bias-direction component. For inherently gendered word pairs (grandmother/grandfather), it additionally equalizes them so they sit symmetrically around the neutral words, preserving the meaningful gender contrast while removing its leakage into unrelated words like "engineer" or "nurse."
Is 3CosMul strictly better than 3CosAdd?
Empirically, 3CosMul tends to outperform 3CosAdd on standard analogy benchmarks, particularly because it avoids the failure mode where one large additive term dominates the sum and the search effectively ignores one of the three input words. However, 3CosMul is not universally superior; it introduces a hyperparameter (the epsilon term) and can behave unpredictably when cosine similarities are near zero or negative, requiring careful shifting into a positive range before the multiplicative combination is meaningful.
Can embedding geometry capture relations that are not symmetric, like "is-a" hierarchies?
Poorly, in general. Vector offsets are a linear, symmetric-ish mechanism, well-suited to relations where the offset from A to B looks similar across many (A,B) pairs. Hierarchical or asymmetric relations (hypernymy, entailment, "is-a") do not naturally correspond to a single consistent translation vector, since the relation is directional and often many-to-one. Specialized methods (order embeddings, hyperbolic embeddings, Poincaré embeddings) were developed specifically because standard Euclidean/cosine geometry struggles with this kind of structure.
How does this relate to what comes after static embeddings?
Static embeddings assign exactly one vector per word type, so "bank" has a single vector no matter the sentence. All the geometry described here — offsets, cosine neighborhoods, bias directions — is computed on that single fixed vector. Contextual Embeddings instead compute a different vector for each occurrence of a word, conditioned on surrounding context, which changes how "similarity" and "analogy" must be redefined, since there is no longer one fixed point per word to do arithmetic on.
Why does the analogy method fail more often on rare words?
Rare words receive far fewer gradient updates during training, so their vectors are noisier estimates of their "true" semantic position, and any single co-occurrence pattern can disproportionately influence their final direction. Since the offset method depends on consistent, well-averaged relational structure across many training examples, sparse word pairs simply lack the statistical support to produce a reliable linear offset, making both similarity rankings and analogy answers less trustworthy for infrequent vocabulary.