Charan | AI Journey › 01 · Vectors › Vector Space
⚡ 3D Simulator
AI Journey · Understand Language

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.

🟡 GOOD 15 Study Phases Vectors Prerequisite: Vector Dimensions → Similarity
🧙‍♂️ The Wise Scholar's Metaphor The Semantic Globe ($\mathbb{R}^d$)
⏮️ 00 · Math & Foundations Hub →

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.

01

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.

Key idea:
  • 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
Raw text→ Tokens→ Token IDs→ Vectors→ Vector space→ Model math
02

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.

Key idea: Geometry is not a metaphor here — it is the actual mechanism. Attention weights are literally dot products, and retrieval systems literally sort by distance.
03

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.
Note: The city map analogy captures proximity well but misleads on scale. A 768-dimensional space has geometric properties that are deeply counterintuitive compared to 2D or 3D space — see the Limitations section for more.
04

TheoryFour concepts to keep separate

These four terms are often used interchangeably but have distinct roles:

TermWhat it isQuestion 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.

05

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:

E ∈ ℝ^(V × d) — one row per vocabulary entry id = 4127 — token "king" vector = E[4127] — the d-dimensional coordinate of "king"

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)
Token ID→ Embedding row E[id]→ Point in ℝd→ Compare / transform
Tip: The same vector space formalism applies at every layer of a transformer — not just at token embedding time. The residual stream is a point moving through the same high-dimensional space as the model adds information layer by layer.
06

MathematicsCore operations and their roles

Four operations cover most of what happens inside a model's use of vector space:

add Addition: $\mathbf{x} + \mathbf{y} = [x_1+y_1,\; x_2+y_2,\; \ldots,\; x_d+y_d]$. Used in residual connections and mean pooling. Combines information additively.
scale Scalar multiplication: $\alpha \mathbf{x} = [\alpha x_1,\; \alpha x_2,\; \ldots,\; \alpha x_d]$. Stretches or compresses a direction. Used in attention score scaling $(\frac{1}{\sqrt{d_k}})$ to stabilise gradients.
dot Dot product: $\mathbf{x} \cdot \mathbf{y} = \sum_{i=1}^{d} x_i y_i$. Measures aligned magnitude. Large positive value = vectors pointing in similar directions. Used for attention scores: $\text{score}(Q, K) = QK^\top$.
dist Euclidean distance: $\|\mathbf{x} - \mathbf{y}\|_2 = \sqrt{\sum_{i=1}^{d}(x_i - y_i)^2}$. Straight-line gap. Sensitive to magnitude — large vectors can appear far apart even when pointing in the same direction.
07

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]
cat·dog $\mathbf{cat} \cdot \mathbf{dog} = (0.9)(0.9) + (0.1)(0.3) + (0.8)(0.9) = 0.81 + 0.03 + 0.72 = \mathbf{1.56}$ — high dot product, vectors point in similar directions
cat·car $\mathbf{cat} \cdot \mathbf{car} = (0.9)(0.0) + (0.1)(0.6) + (0.8)(0.0) = 0 + 0.06 + 0 = \mathbf{0.06}$ — near-zero dot product, vectors are nearly orthogonal
cat·tiger $\mathbf{cat} \cdot \mathbf{tiger} = (0.9)(0.9) + (0.1)(0.8) + (0.8)(0.0) = 0.81 + 0.08 + 0 = \mathbf{0.89}$ — intermediate alignment

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".

Note: These vectors are invented for illustration. In a real 768-dimensional embedding, the relationships are encoded across hundreds of abstract dimensions and cannot be read directly from any one value.
08

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.

quadrantChart title Toy 2D Vector Space (x = dim 1, y = dim 3) x-axis Low Dim-1 --> High Dim-1 y-axis Low Dim-3 --> High Dim-3 quadrant-1 Top-right quadrant-2 Top-left quadrant-3 Bottom-left quadrant-4 Bottom-right cat: [0.9, 0.8] dog: [0.9, 0.9] tiger: [0.9, 0.0] car: [0.0, 0.0]

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.

Click Compute to see results.
Try: 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.
09

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.

Python
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.

10

CompareDot product vs cosine vs Euclidean

🧭 Live Lab: 2D Semantic Vector Space & Cluster Projector
Explore Semantic Clusters (Animals, Tech, Royalty) and Angle Projections
Click any point to inspect its vector coordinates & semantic neighbors
Inspected Vector
"cat" (Animal)
Coordinates: [x: 0.85, y: 0.72]
Magnitude: ||v|| = 1.11
Closest Neighbors:
Semantic proximity = short angle $\theta$ and high cosine similarity.
🔍 Behind-the-Scenes: How High-D Spaces Collapse into 2D Coordinates

Dimensionality reduction algorithms preserve geometric neighborhoods:

  1. 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.
  2. t-SNE / UMAP: Converts Euclidean distances to probabilities and minimizes Kullback-Leibler divergence to keep local clusters intact on a 2D canvas.
MetricWhat it measuresSensitivity to magnitudeTypical 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
Study goal: Be able to explain why cosine similarity is preferred for normalised sentence embeddings, and why raw dot product is used inside attention without additional normalisation (apart from the $\frac{1}{\sqrt{d_k}}$ scale).
11

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.

Pattern: Almost every modern AI system that "compares" or "retrieves" is computing a geometric similarity in a learned vector space. Mastering vector space = mastering the common thread across RAG, search, recommendation, and attention.
12

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.
Better mental model: A vector space is a learned, approximate, geometrically useful representation — not a ground-truth semantic database. High cosine similarity is evidence of contextual overlap, not proof of meaning equivalence.

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."

13

Feynman ChallengeCan you explain it simply?

Feynman Mastery Check

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
10-second explanation: A vector space is a high-dimensional coordinate system where every AI representation is a point. Points close together had similar training contexts. Geometric operations — dot product, cosine distance — are how the model compares and combines those representations.

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.
14

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.

15

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

This page 0:00
This session 0:00
Total (all pages) 0:00
Today 0:00
▶ Running
📊 View all study stats →
0:00 studying