Vectors, dot products and norms
The geometry every model lives in
Every object a model touches is a vector: an image is a point in , a word becomes a 768-dimensional embedding, a user is a row of features. Dot products measure alignment, norms measure size, and together they define similarity, distance and projection — the operations behind neurons (4.1 From perceptron to MLP; universal approximation), kNN (3.4 k-Nearest Neighbors), attention scores (7.2 Scaled dot-product and multi-head attention, fully derived) and the cosine similarity that ranks documents in RAG (9.2 Embeddings deep dive).
You'll be able to
- Compute dot products, norms, angles and projections by hand and in NumPy
- Explain why a neuron's pre-activation is a dot product and what it measures
- Use cosine similarity and Euclidean distance appropriately and know when they agree
- State what happens to distances and angles in high dimensions and why it matters for embeddings
Key ideas
- A vector is both an arrow and a row of data; ML is geometry in high-dimensional spaces.
- Dot product = Σ xᵢyᵢ = ‖x‖‖y‖cos θ: it measures alignment, and a neuron's pre-activation is exactly this alignment score.
- Cosine similarity is the dot product of unit vectors; for normalized embeddings, cosine ranking and Euclidean-distance ranking coincide.
Show 4 more key ideas
- The ℓ₂ norm gives Euclidean length/distance; ℓ₁'s diamond-shaped ball is why ℓ₁ regularization yields sparsity; ℓ∞ bounds the largest coordinate.
- Projection onto v is (x·v / v·v) v — least squares and PCA are projections.
- In high dimensions random vectors are nearly orthogonal and distances concentrate; learned embeddings restore meaningful geometry.
- Cauchy–Schwarz |x·y| ≤ ‖x‖‖y‖ guarantees cosine similarity lives in [−1, 1].
Suggested path through this lesson
Two pictures of a vector
A vector is an ordered list of real numbers, written as a column:
Keep two pictures in mind at once. Geometrically, is an arrow from the origin to a point. As data, it is one row of a spreadsheet: a house is , a 28×28 grayscale digit is a point in , a token inside GPT-2 is a point in . Machine learning is geometry in spaces too big to draw, so every intuition you build in 2-D or 3-D is a tool you will reuse.
Vectors add component-wise, , and scale component-wise, . A linear combination is the fundamental way to build new vectors from old ones; the set of all linear combinations is the span. If no vector in a set is a combination of the others, the set is linearly independent; an independent set that spans the space is a basis, and the number of basis vectors is the dimension. The standard basis , is just one choice — embeddings live in a learned basis that is not aligned to any human-readable axis.
Intuition. A neural network layer outputs linear combinations of its inputs (then applies a nonlinearity). "Linear combination" is the verb of deep learning.
The dot product: alignment as a number
The dot product (inner product) of is
It has a geometric meaning that is the whole point:
where is the angle between the arrows. So the dot product is large and positive when the vectors point the same way, zero when they are orthogonal (), and negative when they oppose. Three consequences you will use constantly:
- A neuron is a dot product. The pre-activation measures how well the input aligns with the weight pattern ; the weights are a template, the dot product is a match score (4.1 From perceptron to MLP; universal approximation).
- Attention scores are dot products. In a transformer, how much token attends to token is before softmax (7.2 Scaled dot-product and multi-head attention, fully derived).
- Projection. The component of along a unit vector () is the scalar , and the projected vector is . For a general : . Least squares (3.2 Linear regression) and PCA (3.12 Dimensionality reduction: PCA, t-SNE and UMAP) are projection in disguise.
Cosine similarity removes length and keeps only direction:
This is how retrieval systems rank document chunks against a query (9.2 Embeddings deep dive): two texts "mean the same thing" when their embedding arrows point the same way, regardless of how long the texts are.
Norms: how big is a vector?
A norm assigns a length to a vector. The three you need:
| norm | formula | unit ball shape | where it appears |
|---|---|---|---|
| (Euclidean) | circle/sphere | distances, MSE, weight decay | |
| (Manhattan) | diamond | lasso, sparsity | |
| (max) | square | adversarial perturbation budgets |
They are all special cases of the norm . The shape of the unit ball is not a curiosity: because the ball has corners on the axes, an optimizer constrained by it tends to land on solutions with exact zeros — that is why regularization produces sparse models (3.6 Regularization and generalization).
A norm gives a distance: . Euclidean distance is what kNN uses (3.4 k-Nearest Neighbors). Dividing a vector by its norm, , puts it on the unit sphere; LayerNorm and RMSNorm (4.6 Initialization and normalization) are this idea applied to a layer's activations. Note the identity that connects distance and similarity for unit vectors: , so for normalized embeddings "nearest by Euclidean distance" and "most similar by cosine" rank identically (9.2 Embeddings deep dive).
Worked example
Let and .
- Dot product: .
- Norms: , .
- Angle: , so .
- Projection of onto : .
- and : , .
Math check. The Cauchy–Schwarz inequality is exactly the statement . Here . ✓
In NumPy:
import numpy as np
x, y = np.array([1., 2., 2.]), np.array([2., 0., 1.])
dot = x @ y # 4.0
cos = dot / (np.linalg.norm(x) * np.linalg.norm(y)) # 0.596
proj = (x @ y) / (x @ x) * x # [0.444, 0.889, 0.889]
High dimensions are strange (and useful)
Pick two random vectors in with independent standard-normal coordinates. Their cosine similarity has mean and standard deviation about : in two random directions are almost always within a few degrees of orthogonal. Two consequences:
- Distances concentrate. Nearest and farthest neighbours become nearly equidistant, which hurts naive kNN in raw high-dimensional spaces (3.4 k-Nearest Neighbors) and is why we learn embeddings in which the geometry is meaningful.
- There is room for many "almost orthogonal" directions. A 768-dimensional space can hold far more than 768 nearly-orthogonal directions, which is one reason a model can pack many concepts into one residual stream — the phenomenon called superposition in interpretability (8.11 Interpretability: what is happening inside).
Where this shows up later
- Neurons compute — 4.1 From perceptron to MLP; universal approximation; matrices stack many such dot products — 1.2 Matrices as transformations.
- Euclidean distance drives kNN and k-means — 3.4 k-Nearest Neighbors, 3.11 Clustering: k-means, GMMs/EM, DBSCAN and hierarchical; norms define regularizers — 3.6 Regularization and generalization and gradient clipping — 4.5 Optimizers and learning-rate schedules.
- Dot products are attention scores — 7.2 Scaled dot-product and multi-head attention, fully derived; cosine similarity ranks retrieved chunks — 9.2 Embeddings deep dive; normalization layers rescale activations — 4.6 Initialization and normalization.
Common pitfalls (4)
- Confusing the dot product (a scalar) with element-wise multiplication (a vector): x @ y vs x * y in NumPy.
- Comparing raw dot products of vectors with different lengths when you meant to compare directions — normalize first or use cosine.
- Assuming Euclidean distance is meaningful on unscaled features; a feature measured in millimetres will dominate one measured in metres.
- Treating orthogonal ('unrelated') as the same as opposite ('negatively related'); cos θ = 0 and cos θ = −1 are very different.
Recap: all 7 key points
- A vector is both an arrow and a row of data; ML is geometry in high-dimensional spaces.
- Dot product = Σ xᵢyᵢ = ‖x‖‖y‖cos θ: it measures alignment, and a neuron's pre-activation is exactly this alignment score.
- Cosine similarity is the dot product of unit vectors; for normalized embeddings, cosine ranking and Euclidean-distance ranking coincide.
- The ℓ₂ norm gives Euclidean length/distance; ℓ₁'s diamond-shaped ball is why ℓ₁ regularization yields sparsity; ℓ∞ bounds the largest coordinate.
- Projection onto v is (x·v / v·v) v — least squares and PCA are projections.
- In high dimensions random vectors are nearly orthogonal and distances concentrate; learned embeddings restore meaningful geometry.
- Cauchy–Schwarz |x·y| ≤ ‖x‖‖y‖ guarantees cosine similarity lives in [−1, 1].
Watch
The two pictures of a vector; watch before reading.
Read
Exercises
- By hand: five dot products
Compute , both norms, and for five pairs you invent in . Verify Cauchy–Schwarz each time. Expected: your cosines all lie in .
- NumPy: cosine similarity matrix
Create a random matrix
Eof shape (8, 16) (8 "embeddings"). Compute the 8×8 cosine-similarity matrix using one normalization step and one matrix product, with no Python loops. Check the diagonal is all ones. - Experiment: the curse of dimensionality
For sample 10,000 pairs of standard-normal vectors and plot the histogram of their cosine similarity. Expected: the spread shrinks like . Then compute the ratio (max distance − min distance)/min distance from one point to the rest and watch it collapse.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →