Vector Space
The mathematical arena where all numeric representations live. Learn what a vector space actually is, why geometry becomes useful for language, and how every embedding, attention score, and retrieval query operates within it.
Vector Space: The Scholar's Topographical Map of Human Meaning
Vector space is the infinite multi-dimensional landscape in the scholar's mind. Words that share meaning cluster into mountain ranges and continents (the "Animal" continent, the "Legal Term" archipelago). Because all concepts share this same geometry, moving in a specific direction (e.g. from present tense to past tense) applies universally across the entire territory.
IntroductionWhat is a vector space?
A vector space is the mathematical arena in which all of a model's numeric representations live. Every token embedding, every query, every key, every document chunk stored in a retrieval index — all of these are points in some vector space. Understanding the space is what makes all the arithmetic on top of it interpretable.
The problem
Raw text has no natural arithmetic. You cannot add two words or measure how far apart "king" and "queen" are without first converting them into numbers that live in a shared coordinate system.
The idea
Map every piece of text to a point in a high-dimensional coordinate system — a vector space — so that geometric operations like distance and similarity become meaningful comparisons.
- Vector = an ordered list of coordinates that locates a point
- Space = the full set of all possible such coordinates, plus a defined set of allowed operations
- Distance / similarity = the tools we use to compare points inside that space
WhyWhy geometry is useful for language
Once you have a vector space, geometric intuitions give you working tools for reasoning about language:
Closeness encodes similarity
Two representations that are close together were learned in similar contexts. The space itself is a compressed summary of co-occurrence patterns.
Direction encodes relationships
The classic example: the direction from man to king roughly equals the direction from woman to queen. Consistent directions capture relational structure.
Interpolation moves gradually
Moving a point along a line between two vectors produces representations that blend the two concepts — useful for controlled generation and latent diffusion.
Composition combines signals
Adding or averaging vectors can combine their encoded information — the foundation of mean-pooling for sentence embeddings and residual streams in transformers.
IntuitionA city map for learned representations
Imagine a city map where every landmark has precise coordinates. Two cafés placed near each other on the map are physically close in reality. A vector space is similar — except the "city" is built from training data, not geography.
- The coordinates are not hand-crafted. They are learned from billions of examples of how words appear near each other in text.
- "Nearby" in the space means similar according to learned co-occurrence context — not a perfect semantic definition, but a surprisingly useful proxy.
- The dimensions (axes) of the space do not correspond to human-interpretable concepts like "is a mammal" or "has legs". They are abstract features discovered by gradient descent.
- 2D diagrams of vector spaces — including the famous king/queen/man/woman one — are projections. Real models operate in 768 to 8192 dimensions. The 2D picture is a teaching device, not the actual space.
TheoryFour concepts to keep separate
These four terms are often used interchangeably but have distinct roles:
| Term | What it is | Question it answers |
|---|---|---|
| Vector | An ordered list of real numbers, e.g. $[0.9, 0.1, 0.8]$ | "Where is this point located?" |
| Point | A location in the space identified by its vector coordinates | "What does this specific representation correspond to?" |
| Vector space | The complete coordinate system plus a defined set of legal operations (add, scale, measure) | "What can I do with these coordinates?" |
| Metric / similarity | A rule for measuring how close two points are — dot product, cosine, Euclidean, etc. | "How do I compare two points?" |
Choosing the wrong metric for a space (e.g. Euclidean distance on unnormalised embeddings of very different magnitudes) gives unreliable results even though the vectors themselves are correct.
How It WorksEmbedding lookup and space operations
In a transformer, the embedding layer is a learned matrix $E \in \mathbb{R}^{V \times d}$ where $V$ is vocabulary size and $d$ is the embedding dimension. Looking up a token is just selecting a row:
Once you have the vectors, the operations inside the model are straightforward linear algebra:
- Addition $x + y$: combine two representations (residual stream, mean pooling)
- Scaling $\alpha x$: amplify or shrink a representation
- Dot product $x \cdot y = \sum_i x_i y_i$: measure alignment (attention scores)
- Euclidean distance $\|x - y\|_2$: straight-line gap between two points (clustering, k-NN retrieval)
MathematicsCore operations and their roles
Four operations cover most of what happens inside a model's use of vector space:
Worked ExampleToy vectors and manual calculations
Use these invented 3D vectors as a learning exercise. The specific numbers don't correspond to any real embedding — they are chosen to illustrate how operations reveal geometric relationships.
Toy vectors (3D): cat = [0.9, 0.1, 0.8] dog = [0.9, 0.3, 0.9] tiger = [0.9, 0.8, 0.0] car = [0.0, 0.6, 0.0]
The numbers show: cat–dog are more aligned than cat–tiger, and cat–car are nearly orthogonal. That's the geometry encoding learned relationships — without any explicit programming of "animal similarity".
Visualize + Hands-onMermaid diagram and interactive similarity demo
A toy 2D projection of the vectors above. Remember: this is a visualization device only — the actual space has far more dimensions.
2D projection of toy vectors — teaching visualization only, not a real embedding space
Interactive similarity demo
Enter two comma-separated vectors below (same number of dimensions). The demo computes dot product, magnitudes, and cosine similarity.
cat=[0.9,0.1,0.8] vs car=[0.0,0.6,0.0] to see near-zero cosine similarity, or cat vs dog=[0.9,0.3,0.9] to see high similarity.CodePython: dot product, magnitude, cosine similarity
A minimal implementation of the three core vector-space operations. This is pure Python with no dependencies — focus is on understanding the mechanics before reaching for NumPy or a vector library.
def dot(a: list[float], b: list[float]) -> float:
"""Dot product: sum of element-wise products.
Measures how much two vectors 'point in the same direction'.
Large positive → strongly aligned. Near zero → nearly orthogonal.
"""
assert len(a) == len(b), "Vectors must have the same dimension"
return sum(ai * bi for ai, bi in zip(a, b))
def magnitude(a: list[float]) -> float:
"""Euclidean norm (length) of a vector.
Used to normalise vectors and to compute Euclidean distance.
"""
return sum(ai ** 2 for ai in a) ** 0.5
def cosine_similarity(a: list[float], b: list[float]) -> float:
"""Cosine similarity: dot product divided by both magnitudes.
Range: [-1, 1]. 1 = identical direction. 0 = orthogonal. -1 = opposite.
Insensitive to vector length — only measures angle.
"""
mag_a = magnitude(a)
mag_b = magnitude(b)
if mag_a == 0 or mag_b == 0:
return 0.0
return dot(a, b) / (mag_a * mag_b)
# ── Toy examples ─────────────────────────────────────────────────────────────
cat = [0.9, 0.1, 0.8]
dog = [0.9, 0.3, 0.9]
car = [0.0, 0.6, 0.0]
print(f"dot(cat, dog) = {dot(cat, dog):.4f}") # 1.5600
print(f"dot(cat, car) = {dot(cat, car):.4f}") # 0.0600
print(f"cosine(cat, dog) = {cosine_similarity(cat, dog):.4f}") # ≈ 0.9864
print(f"cosine(cat, car) = {cosine_similarity(cat, car):.4f}") # ≈ 0.0534
# ── With NumPy (production style) ─────────────────────────────────────────────
import numpy as np
cat_np = np.array([0.9, 0.1, 0.8])
dog_np = np.array([0.9, 0.3, 0.9])
dot_prod = np.dot(cat_np, dog_np)
cos_sim = np.dot(cat_np, dog_np) / (np.linalg.norm(cat_np) * np.linalg.norm(dog_np))
print(f"NumPy cosine(cat, dog) = {cos_sim:.4f}")
What this shows
How dot product, magnitude, and cosine similarity are computed from first principles. The manual version makes the formula transparent; NumPy is what you'd use in real code.
How to extend
For real embeddings, use sentence-transformers or openai.embeddings to obtain vectors, then apply these same operations at scale with NumPy or PyTorch.
CompareDot product vs cosine vs Euclidean
Magnitude: ||v|| = 1.11
🔍 Behind-the-Scenes: How High-D Spaces Collapse into 2D Coordinates
Dimensionality reduction algorithms preserve geometric neighborhoods:
- PCA (Principal Component Analysis): Rotates high-D space to find axes of maximum variance ($\vec{w}_1, \vec{w}_2$) via eigenvector decomposition of the covariance matrix.
- t-SNE / UMAP: Converts Euclidean distances to probabilities and minimizes Kullback-Leibler divergence to keep local clusters intact on a 2D canvas.
| Metric | What it measures | Sensitivity to magnitude | Typical use |
|---|---|---|---|
| Dot product $x \cdot y$ | Alignment × magnitude of both vectors | Yes — large vectors give large scores | Attention scores $QK^\top$; bilinear similarity |
| Cosine similarity $\frac{x \cdot y}{\|x\|\|y\|}$ | Angle between vectors (direction only) | No — normalises out magnitude | Semantic sentence comparison; RAG retrieval |
| Euclidean distance $\|x - y\|_2$ | Straight-line gap in space | Yes — sensitive to both direction and scale | k-NN clustering; some vector database indices |
| Manhattan distance $\|x - y\|_1$ | Sum of absolute per-dimension differences | Yes | Sparse vector settings; sometimes faster at scale |
ApplyReal-world applications of vector space
Embeddings
Words, sentences, images, and code are all mapped to vectors in a shared or domain-specific space. The quality of the space determines downstream task performance.
Retrieval-Augmented Generation (RAG)
Queries and document chunks are embedded into the same space. Retrieval = find the nearest neighbours to the query vector. The ranking is purely geometric — closest cosine distance wins.
Vector Databases
Pinecone, Weaviate, Chroma, Qdrant — all store high-dimensional vectors and answer "find me the k most similar vectors to this query" using approximate nearest-neighbour algorithms (HNSW, IVF).
Attention Mechanism
Queries $Q$ and keys $K$ are compared using $\frac{QK^\top}{\sqrt{d_k}}$ — a scaled dot product over the vector space. The result determines which values $V$ to mix — all purely via geometry.
LimitationsWhat vector space geometry cannot guarantee
- Geometry is only as good as the representation: The distances and directions in the space reflect the training objective, not an absolute semantic truth. A model trained on biased data produces a biased space.
- High similarity ≠ equivalent meaning: Words that appear in similar contexts get close vectors, but context similarity is not the same as meaning equivalence. "Not bad" and "good" may both appear near "acceptable" for contextual reasons.
- Static embeddings and polysemy: A word like "bank" has multiple senses. In a static embedding (word2vec, GloVe) it gets one averaged vector that conflates all senses. Contextual models (BERT, LLaMA) help — but the representational tradeoff remains.
- Individual dimensions are not interpretable: Unlike one-hot encoding where each dimension has a defined meaning, learned embedding dimensions are distributed features. You cannot look at dimension 42 and know what it represents.
- Curse of dimensionality: In very high-dimensional spaces, distances between random points concentrate around a single value — almost every pair of points appears "equally far apart". This makes intuitions from 2D or 3D geometry unreliable.
Common mistake
"If two words are close in the embedding space, they must mean the same thing."
Better mental model
"Closeness reflects similar learned context patterns. Same ballpark, not same definition. Always verify with downstream tasks."
Feynman ChallengeCan you explain it simply?
Explain vector space to someone who knows what coordinates are on a map, but nothing about machine learning. Use the "city of learned representations" analogy — but be careful about its limits:
- The "city" has hundreds of dimensions, not just the two on a map
- Locations are learned from data — not assigned by a human cartographer
- Proximity means "similar learned context" — not "same meaning"
- "Directions" through the city can encode relational structure (man → king ≈ woman → queen)
- The operations — addition, dot product, cosine — are the tools we use to navigate and compare
Common misconceptions to address:
- "The vector space is a database of word meanings" — No: it is a geometric environment whose structure reflects training co-occurrence, not a hand-labelled dictionary.
- "Nearby vectors are synonyms" — No: they share contextual patterns, not necessarily semantic equivalence.
- "I can read the meaning of each dimension axis" — No: dimensions are abstract distributed features, not interpretable slots like "is an animal".
- "Distance always gives the ranking I want" — No: the choice of metric (cosine vs Euclidean vs dot) matters enormously, and the right choice depends on how the embeddings were trained.
- "All vector spaces are the same" — No: different models, objectives, and training corpora produce very different spaces even at the same dimensionality.
BuildThree mini-projects to cement your understanding
🔨 Mini-Projects
1 · Vector space explorer
Write a small Python script that takes two user-provided vectors (as comma-separated floats), then prints: dot product, magnitude of each, cosine similarity, Euclidean distance, and a label ("very similar / similar / unrelated") based on cosine thresholds.
2 · Analogy explorer
Load GloVe 50D or word2vec pretrained embeddings. Test the king − man + woman ≈ queen analogy using cosine nearest-neighbour search. Record 5 analogies that work and 2 that fail. Explain why each succeeds or fails geometrically.
3 · Semantic search toy
Embed 20 short sentences using sentence-transformers. Given a query sentence, return the top-3 most similar by cosine similarity. Compare the results with a keyword (TF-IDF) search on the same sentences and note the differences.
SummaryEverything in one place
- Vector space: A high-dimensional coordinate system where every representation is a point. Defined by coordinates (vectors) and allowed operations (add, scale, dot product, distance).
- Vectors: Ordered lists of real numbers that locate a point. Learned from data via gradient descent; individual dimensions are not interpretable.
- Geometry is the mechanism: Closeness encodes contextual similarity, directions encode relational structure, dot products drive attention, cosine similarity drives retrieval.
- Core metrics: Dot product (attention), cosine similarity (semantic comparison, RAG), Euclidean distance (clustering, k-NN). Choose based on how the space was trained.
- Limits: The geometry reflects training data, not absolute meaning. High similarity ≠ equivalence. Dimensions are not interpretable. High-dimensional spaces behave counter-intuitively.
- Connects to: Embeddings (what lives in the space), Attention (QK dot products), Similarity (how to compare), Distance (how to measure gaps), RAG (retrieval as nearest-neighbour search).
Vector
Ordered list of coordinates locating a point in the space.
Space
The full coordinate system + set of allowed operations.
Geometry
The actual mechanism behind attention, retrieval, and comparison.
Next
→ Distance (Euclidean, Manhattan, L-norms) → Similarity (dot, cosine, Jaccard) → Embeddings in depth
