21.1 Vectors, Angles, and Projections
Throughout the Basics chapters, we represented every input as a vector: an image became a list of pixel values, and a word became an embedding. At heart, machine learning models perform three geometric operations on these vectors. They compare them, as when we measure whether two embeddings are similar; they fit them, as when we seek the combination of features that best matches a set of targets; and they separate them, as when a classifier decides which side of a boundary an input falls on. In the two-dimensional plane, each of these operations is a familiar picture of lengths, angles, and shadows. Real inputs, however, live in spaces of hundreds or thousands of dimensions that nobody can draw. Do those geometric pictures still mean anything there?
Telling t-shirts from trousers offers a concrete test. Each Fashion-MNIST image (Section 3.2) is a list of pixel intensities, so it is a point in . Consider the simplest rule imaginable: compute the average t-shirt and the average pair of trousers, and assign each new image to whichever average lies closer. In the plane, "closer" is something we can check by eye; in , it becomes a calculation requiring a single dot product per image. On the test images from these two classes, this rule is right about of the time. The fact that such a simple rule works so well tells us that the two clouds of points sit well apart, and that geometric notions like distance remain meaningful even where we cannot see them.
What carries the geometry of the plane into arbitrary dimensions is the dot product. Lengths are square roots of dot products, the shadow of one vector onto another is a ratio of dot products, and the angle between two vectors is defined directly from them. We develop this geometry in three stages. First, we study a pair of vectors: projection onto a line, the angle between them, and the Cauchy–Schwarz inequality, which Section 1.3 proved algebraically and which we prove again here from a right triangle. Second, we introduce the language of subspaces (span, independence, basis, and dimension) that the rest of the chapter relies on, and we solve least squares as a projection, with the QR factorization as our computational tool. Third, we take these ideas to high-dimensional images, asking how similar unrelated vectors are in and reading a linear classifier as a hyperplane.
Three results stand out above the rest: the residual of a projection is orthogonal to the line or subspace we project onto, which is what makes the projection the closest point; Cauchy–Schwarz, which ensures that angles remain well defined in any dimension; and the typical scale of the cosine between random directions in . Aside from loading the dataset, all code in this section is plain NumPy and runs identically across frameworks.
21.1.1 Vectors and Their Geometry#
21.1.1.1 Points and Directions#
We can picture a vector in two complementary ways. Viewed as a point, marks the location units to the right of the origin and units up. This viewpoint turns an entire dataset into a cloud of points, turning a classification task such as separating t-shirts from trousers into a geometric problem of separating two clouds. Viewed as a direction (or displacement), the same vector instructs us to move steps right and steps up. Because a displacement can start anywhere, all of the parallel arrows in Figure 21.1.1 represent the same vector.
Two ways to read a vector: as a point with coordinates (left), or as a direction, an arrow that can start anywhere, so every arrow shown represents the same vector (right).
The direction viewpoint makes vector addition immediate: follow the first arrow, then follow the second from its tip, as shown in Figure 21.1.2.
Vector addition visualized tip to tail: follow the first arrow, then follow the second from where the first ends.
Subtraction works the same way. Because , the difference is simply the displacement arrow that carries us from the point to the point .
Everything else in this section grows out of a single operation, the dot product introduced in Section 1.3. Given two vectors , it multiplies their corresponding entries and sums the results:
Since the dot product is symmetric, , we often write it as : using the dot when we picture two arrows and the transpose when the product sits inside a matrix expression. For and , we have , and the squared length of is .
21.1.1.2 Projection onto a Line#
How much of a vector points along another vector ? Equivalently, which scalar multiple comes closest to ? This is the simplest fitting problem in linear algebra: we approximate using a single direction and seek the best coefficient .
Let us test this on our pair and by trying a few values of . At , the error has squared length . At , the error is with squared length ; at , it is , again with squared length . The minimum occurs at , giving the closest point . We call the remaining error the residual. Here the residual is , and notice its dot product with : . The shortest error meets the line at a right angle. Even better, the squared lengths satisfy a right-triangle relation: , the closest point has squared length , the residual has squared length , and .
This pattern holds in every dimension.
Proposition (orthogonal projection). Let . The multiple of closest to is
and the residual satisfies .
Proof. We minimize the squared error as a function of . Expanding the dot product of with itself yields a quadratic in ,
Because its leading coefficient is positive, has a unique minimum where its derivative vanishes, namely at . Substituting gives (21.1.2). Checking the residual, we find .
For our example, , which reaches its minimum value of at , confirming our trial values. We call the projection, or shadow, of onto . The projection captures the part of aligned with , while the residual captures the part at right angles to it. Notice why we required : the zero vector defines no direction, and setting would divide by zero.
That right angle is the reason squared lengths add cleanly. Two vectors and are orthogonal whenever . Expanding the squared length of their sum then gives Pythagoras' theorem,
In any dimension, orthogonal components add in squared length with no cross term. Applying this to the decomposition gives , which is in our example.
We will also need the length of the shadow together with a sign indicating whether it points in the same direction as or opposite to it. Multiplying the coefficient by gives this signed length:
In our example it equals , the length of . This signed length will reappear at the end of the section as the signed distance from a point to a hyperplane. Figure 21.1.3 illustrates the entire geometry.
(a) The projection (shadow) of onto is ; the residual meets at a right angle, so . (b) The Cauchy–Schwarz equality case: is collinear with and the residual vanishes.
21.1.1.3 Cauchy–Schwarz and the Angle#
In dimensions there is no protractor. Can "the angle between two images" still mean anything? Surprisingly, the answer comes from a much simpler question: can the shadow of a vector ever be longer than the vector itself? Panel (a) of Figure 21.1.3 says no, because the shadow is a leg of a right triangle whose hypotenuse is . Pythagoras' theorem turns that picture into a proof that works in every dimension.
Proposition (Cauchy–Schwarz). For all vectors ,
with equality if and only if and are collinear (one is a scalar multiple of the other).
Proof. If , both sides vanish and the vectors are collinear. Otherwise, split into its projection onto and its orthogonal residual . By Pythagoras' theorem (21.1.3),
Multiplying both sides by and taking square roots yields the inequality. Equality holds precisely when , meaning . Conversely, if , then .
In plain terms, a vector's shadow is never longer than the vector itself, and matches its length only when nothing is left over in the residual. Where Section 1.3 proved Cauchy–Schwarz algebraically, here it falls straight out of panel (a) of Figure 21.1.3, with panel (b) showing the equality case.
Now we can define angles in any dimension. In the plane, the law of cosines gives (Section 1.3). In we have no physical triangle to measure, so we turn this identity into a definition. For nonzero vectors , the angle between them is
Because is defined only on , this formula makes sense only if the ratio lies inside that interval, and Cauchy–Schwarz guarantees that it always does. Thus the angle is well defined in every dimension, and the planar dot-product formula now holds everywhere as an immediate consequence:
The two equality cases of Cauchy–Schwarz correspond to (vectors pointing in the same direction) and (vectors pointing in opposite directions).
A natural objection arises: does this algebraic definition agree with the angle a protractor would actually measure? It does. Any two vectors lie inside a single plane (or a line, if they are collinear), and inside that plane ordinary geometry applies. Projection gives us rectangular coordinates for that plane: set and, provided , set . These two vectors have unit length and are orthogonal, so dot products of their combinations behave just like dot products in . In this coordinate system, and . The angle a protractor measures between these two planar arrows has cosine , matching (21.1.6). For our worked pair and , we get , so .
For nonzero vectors, orthogonality means . Defining orthogonality via has the minor convenience of including the zero vector as well: it is orthogonal to every vector, even though no angle is defined for it.
Turning (21.1.6) into code takes only two lines, with one
practical safeguard worth noticing. Let us test it on our worked pair and on a
deliberately tricky collinear pair, and
, whose true cosine is and whose true angle is . For the
collinear pair, we also print the raw cosine minus and the unclipped
arccos.
def angle(v, w):
cos = v @ w / (np.linalg.norm(v) * np.linalg.norm(w))
return np.arccos(np.clip(cos, -1, 1)) # roundoff can push |cos| past 1
v = np.array([1e8 + 1, 3, 7])
cos = v @ (3 * v) / (np.linalg.norm(v) * np.linalg.norm(3 * v))
with np.errstate(invalid='ignore'): # silence the warning for nan
print(angle(np.array([1., 3]), np.array([2., 1])), cos - 1,
np.arccos(cos), angle(v, 3 * v))
0.7853981633974484 2.220446049250313e-16 nan 0.0
The first number is , matching the angle of our
worked pair. The remaining three values show why np.clip is essential. In
exact arithmetic, Cauchy–Schwarz keeps the ratio inside . In
floating-point arithmetic, rounding can nudge it past the boundary by one unit
in the last place: here the collinear pair yields ,
causing np.arccos to return nan. Clipping to restores the right
answer, .
Cauchy–Schwarz also shows that the length of a sum never exceeds the sum of the lengths. Expanding and bounding the cross term by via (21.1.5) yields the triangle inequality, , just as in Section 1.3.
21.1.2 Subspaces and Least Squares#
21.1.2.1 Span, Bases, and Subspaces#
Suppose we measure a quantity three times, at , and want to fit the best straight line to our data. Stack the measurements into a vector , collect the times in , and let . Evaluating the line at the three times produces the vector . Finding the best line therefore means finding the vector of the form that lies closest to . As and vary over all real numbers, these candidate vectors sweep out a plane through the origin in . Projection onto a line handled a single direction; to handle planes and their higher-dimensional counterparts, we need a small set of standard terms. Readers already comfortable with span, bases, and subspaces can skip straight to the next subsection, where we finish the line fit.
A weighted sum is called a linear combination of . The collection of all such combinations is their span,
In (Figure 21.1.4), the span of a single nonzero vector is the line through the origin along its direction, while the span of two vectors not lying on a common line through the origin is the entire plane. In our line-fitting problem, the set of all candidate fits is .
Left: the span of a single nonzero vector is the set of all its scalar multiples, forming a line through the origin and thus a one-dimensional subspace. Right: two vectors not on a common line through the origin span the whole plane; the dashed parallelogram resolves as , with unique coordinates because and are linearly independent.
Notice that a span is always closed under addition and scalar multiplication: adding two linear combinations, or scaling one by a real number, produces another linear combination. Any nonempty set of vectors with these two closure properties is called a subspace. Every subspace must contain the zero vector (just multiply any element by ), which means a line or plane that misses the origin is not a subspace. In , the only subspaces are the origin alone, the lines through the origin, and itself; in , planes through the origin join the list.
A list of vectors that spans a subspace can contain redundancies. Whenever one vector already lies in the span of the others, we can drop it without shrinking the span. A list of vectors is linearly independent when no such redundancy exists, meaning that the only linear combination equal to is the trivial one with every . Our vectors and are linearly independent: vanishes only when .
A basis of a subspace is a linearly independent list of vectors that spans it. The familiar vectors and form the standard basis of , though the slanted pair in Figure 21.1.4 is an equally good basis. A fundamental theorem of linear algebra (which we use without proof) states that every basis of a given subspace has the same number of vectors; that shared count is the subspace's dimension. This gives a crisp meaning to the in "-dimensional space": has dimension because is a basis. Likewise, our candidate line fits form a two-dimensional subspace of .
Linear independence is what gives every point in a subspace unique coordinates. If is a basis of a subspace , then every can be written as in only one way. At least one representation exists because the basis spans . If two representations existed with coefficients and , subtracting them would give , and independence forces for every .
Once we fix a basis, a -dimensional subspace behaves just like : each point is uniquely named by its coefficient tuple . For our line fit, those coordinates are simply the intercept and the slope .
21.1.2.2 Projection onto a Subspace#
Let us return to the line fit with concrete measurements . We want the point in the plane closest to . When we projected onto a single line, the closest point left a residual orthogonal to that line. Projecting onto a plane should leave a residual orthogonal to the entire plane, and therefore orthogonal to both and (a fact we prove in a moment). Setting both dot products to zero gives two linear equations in two unknowns:
Subtracting the first equation from the second yields , so and . The best-fitting line is . Its predicted values at are , leaving the residual . Both orthogonality checks hold: and . Pythagoras' theorem again splits the squared length of cleanly: . By comparison, projecting onto alone yields the constant fit (the sample mean), whose residual has squared length . Allowing a slope along reduces the squared error from down to . Figure 21.1.5 shows this projection in .
Least squares as projection: the measurements lie outside the plane of candidate lines ; the closest point in the plane is (the line ), and the residual is perpendicular to both and .
To state and prove the general result cleanly, it helps to choose a basis whose vectors are mutually orthogonal and have unit length. A basis of a subspace is orthonormal when every vector satisfies and distinct vectors satisfy . Every finite spanning list admits such a basis: Section 21.1.2.3 constructs one using nothing more than projection onto a line. If we place these basis vectors as the columns of an matrix , orthonormality takes the compact form , because entry of is . Throughout this chapter, we reserve the letter for a matrix with orthonormal columns. The following proposition is the workhorse result that the rest of the chapter draws on most.
Proposition (projection onto a subspace). Let have orthonormal columns spanning , and set . Then for every : (i) , and the residual is orthogonal to every vector of ; (ii) is the unique closest point of to ; (iii) and .
Proof. For (i), is a linear combination of the columns of , so it lies in . Multiplying the residual on the left by gives
so the residual is orthogonal to every column , and therefore to every linear combination of them. For (ii), take any and write . Since lies in while is orthogonal to , Pythagoras' theorem (21.1.3) gives
with equality only when . For (iii), , and .
Conversely, the orthogonality condition in (i) uniquely identifies the closest point. If some leaves a residual orthogonal to , then the difference both lies in and is orthogonal to , hence orthogonal to itself, which forces . That is why solving the two orthogonality equations in our line fit was guaranteed to produce the closest point.
Each half of property (iii) has a clear geometric meaning. The identity says that projecting a second time changes nothing, since the first projection already landed in . Symmetry, , is what makes the projection orthogonal. A matrix satisfying without symmetry is an oblique projector: it maps vectors into its column space along a slanted direction and generally misses the closest point (3). In the one-dimensional case , taking the single unit column reduces directly to our earlier line projection (21.1.2).
Our line fit is one example of least squares, the optimization problem at the heart of linear regression. Let be a data matrix whose rows are examples and whose columns are features, and let be the vector of targets. Least squares seeks the coefficient vector that minimizes the squared error:
As varies over all coefficient vectors, traces out the span of the columns of , known as its column space . Least squares therefore asks for the point in closest to . By our projection proposition, that point is the one whose residual is orthogonal to every column of . Writing this orthogonality condition as produces the normal equations,
These are the matrix form of the system we solved by hand: for the line fit, gives and . Whenever the columns of are linearly independent, is invertible and the optimal coefficients are unique. Even when the columns are dependent, the fitted vector remains unique because it is still the closest point in , though more than one coefficient vector can produce it.
In code, we therefore have two ways to compute the fit : solve the
normal equations directly, or project using .
To obtain , we call np.linalg.qr, which builds an orthonormal
basis for the column space of a matrix with independent columns (we will
construct one by hand in the next subsection).
A = np.array([[1., 0], [1, 1], [1, 2]]) # columns 1 and t
y = np.array([6., 0, 0])
x_hat = np.linalg.solve(A.T @ A, A.T @ y) # normal equations
Q, R = np.linalg.qr(A) # orthonormal basis of col(A)
P = Q @ Q.T
r = y - P @ y
print(x_hat.round(6), (P @ y).round(6), r.round(6))
print(np.linalg.norm(P @ P - P), np.linalg.norm(Q.T @ r))
[ 5. -3.] [ 5. 2. -1.] [ 1. -2. 1.]
1.962615573354719e-16 0.0
Both routes recover our hand calculation: the coefficients and , the projected values , and the residual . The two check norms on the second line vanish up to floating-point roundoff, confirming and .
On a tiny, well-behaved problem like this, the two methods agree completely. When the columns of are nearly dependent, however, forming squares the problem's condition number, its sensitivity to rounding errors (as we will show in Section 21.5.3.2). For that reason, production least-squares solvers avoid the normal equations and work with an orthonormal basis of the column space instead.
21.1.2.3 Gram–Schmidt and QR#
How do we actually build an orthonormal basis? By repeated projection. Given two linearly independent vectors, keep the direction of the first and subtract from the second its shadow along the first. By our projection proposition, whatever remains is orthogonal to the first vector.
Let us carry this out on and . Normalizing gives . The shadow of onto is . Subtracting it leaves , a vector of length that is indeed orthogonal to (). Normalizing this remainder gives . Reading the steps in reverse writes each original vector in terms of the new orthonormal basis:
In matrix notation, this is , where , , and collects the dot products . Notice why is upper triangular: by construction, each depends only on .
Extending this idea to any linearly independent list gives the Gram–Schmidt process. We process the vectors in order: for each , subtract its projections (21.1.2) onto the unit vectors already constructed, and normalize the remainder to obtain . The result is both an orthonormal basis for and the QR factorization , where has orthonormal columns and is upper triangular with positive diagonal entries. Linear independence is essential for the factorization, because a vector that already lies in the span of its predecessors leaves a zero remainder that cannot be normalized. If we only want an orthonormal basis for the span, we can simply skip any vector with a zero remainder and continue. Every finite spanning list therefore yields an orthonormal basis, justifying the existence claim we relied on earlier.
Numerical libraries compute the QR factorization using a different algorithm
based on reflections, which behaves much better in floating-point arithmetic.
Its output matches Gram–Schmidt only up to signs: negating a column of
together with the corresponding row of leaves the
product untouched. When has independent
columns, those sign flips are the only ambiguity. Let us compare our two-step
Gram–Schmidt calculation against np.linalg.qr and verify that they produce
the same columns up to sign.
a1, a2 = np.array([3., 4]), np.array([1., 0])
q1 = a1 / np.linalg.norm(a1)
v = a2 - (q1 @ a2) * q1 # remove the shadow on q1
q2 = v / np.linalg.norm(v)
Q_qr, R_qr = np.linalg.qr(np.stack([a1, a2], axis=1))
print(np.stack([q1, q2], axis=1).round(6))
print(Q_qr.round(6))
print(R_qr.round(6))
[[ 0.6 0.8]
[ 0.8 -0.6]]
[[-0.6 -0.8]
[-0.8 0.6]]
[[-5. -0.6]
[ 0. -0.8]]
Gram–Schmidt produces and , while np.linalg.qr
returns the negatives of both columns along with diagonal entries and
in : the same basis and, up to sign, the same dot products
, , and we found by hand. In floating point, the order in which
we perform the subtractions also matters. On nearly dependent columns, the
formulation above, known as classical Gram–Schmidt, gradually loses
orthogonality (5).
21.1.3 Similarity in High Dimensions#
Up to this point, every result came with a picture in or
. Now we move to spaces where no picture is possible, asking how
similar two real images are and what similarity we should expect between
unrelated vectors by pure chance. We load the Fashion-MNIST dataset
(Section 3.2) through d2l.FashionMNIST as NumPy arrays,
flattening each image into a -pixel row scaled to .
data = d2l.FashionMNIST()
X_train = data.train.data.numpy().reshape(-1, 784) / 255
y_train = data.train.targets.numpy()
X_test = data.val.data.numpy().reshape(-1, 784) / 255
y_test = data.val.targets.numpy()
X_train.shape, X_test.shape((60000, 784), (10000, 784))
Each of these images is now a point in .
21.1.3.1 Cosine Similarity#
The ratio inside (21.1.6) is the cosine similarity (Section 1.3),
Cosine similarity compares directions while ignoring lengths: an image and a copy of it dimmed to brightness sit far apart in Euclidean distance, yet their cosine similarity is still .
That scale invariance makes cosine similarity the standard metric for nearest-neighbor retrieval over embeddings and for contrastive learning objectives such as SimCLR (Chen et al., 2020), which align the directions of embeddings produced from two views of the same image. The attention layer of the original transformer makes a different choice: it uses the unnormalized dot product scaled by (for reasons we derive shortly), so vector lengths remain informative there. Many later models normalize queries and keys first (Section 11.1.2.5), which turns the score back into a scaled cosine.
21.1.3.2 Near-Orthogonality of Random Directions#
Suppose we pick two unrelated images or two unrelated embeddings. What cosine similarity should we expect between them purely by chance? Without a baseline, we cannot judge whether an observed cosine is meaningfully large. The cleanest baseline is a direction chosen uniformly at random on the unit sphere, with no preference for any region of space.
Proposition (near-orthogonality). Fix a unit vector and let be drawn uniformly from the unit sphere in . Then satisfies
Proof. Because the uniform distribution on the sphere is invariant under rotations, we may rotate coordinates so that ; then . The distribution is also unchanged by sign reversal , so . By symmetry, every coordinate has the same second moment . Since , taking expectations yields , and therefore . The tail bound follows immediately from Chebyshev's inequality, (Section 1.6).
The typical cosine between two random directions is therefore of order . In , the standard deviation is , meaning two random directions in image space are almost always within a few degrees of orthogonal. Chebyshev's inequality bounds the probability of seeing by , whereas the true probability is under . Chebyshev is loose because it uses only the variance; sharper exponential bounds appear in Section 24.9.
Low dimensions look completely different (Figure 21.1.6). In the plane (), the angle between a fixed direction and a random one is uniform on , so landing within radians of orthogonal is just as likely as landing within radians of collinear (about each). Yet the cosine piles up near , because flattens out near and : the probability that is about , compared with only for . In , the cosine is uniform on , a classical result known to Archimedes. Starting at , the density peaks at ; by it forms a bell of width , and by it has narrowed into a sharp spike of width roughly .
Histograms of the cosine between independent random unit vectors in dimensions , , and . In , the cosine piles up near even though the angle is uniform. By it forms a bell around , and by it concentrates into a narrow spike of width , matching the proposition.
Let us check this isotropic baseline in by simulation. Because a standard Gaussian vector's distribution is rotationally invariant, normalizing it produces a uniformly random unit vector. In the same cell, we also estimate a variance we will need for attention in a moment: the variance of for independent standard normal vectors in dimensions.
rng = np.random.default_rng()
d = 784
U = rng.standard_normal((10000, d))
U /= np.linalg.norm(U, axis=1, keepdims=True)
V = rng.standard_normal((10000, d))
V /= np.linalg.norm(V, axis=1, keepdims=True)
q, k = rng.standard_normal((10000, 64)), rng.standard_normal((10000, 64))
np.std((U * V).sum(axis=1)), 1 / np.sqrt(d), np.var((q * k).sum(axis=1))(np.float64(0.03602372011587368),
np.float64(0.03571428571428571),
np.float64(65.51162136338216))
The empirical standard deviation matches , and the variance of the unnormalized dot product is close to , the dimension.
Real data, however, rarely look isotropic. Do two unrelated Fashion-MNIST images behave like nearly orthogonal vectors? Let us sample random pairs of test images and measure their cosines, first on the raw pixels and then after subtracting the mean training image.
def cosines(A, B):
"""Cosine similarity between corresponding rows of A and B."""
return (A * B).sum(axis=1) / (np.linalg.norm(A, axis=1)
* np.linalg.norm(B, axis=1))
i, j = rng.integers(0, len(X_test), (2, 5000))
mean_image = X_train.mean(axis=0)
raw = cosines(X_test[i], X_test[j])
centered = cosines(X_test[i] - mean_image, X_test[j] - mean_image)
raw.mean(), raw.std(), centered.mean(), centered.std()(np.float64(0.592208289545085),
np.float64(0.17608271528452482),
np.float64(-0.004695197414552555),
np.float64(0.3390460995081151))
Not even close. Raw images have an average cosine around with a standard deviation of roughly , nowhere near . The reason is simple: pixel intensities are non-negative, so every image lives in the same positive orthant of , making negative dot products impossible. Subtracting the mean image centers the cosines at , yet their standard deviation, about , is still nearly ten times the isotropic value. By our proposition, a spread of corresponds to random directions in only eight or nine dimensions ( lies between and ). Judged by their cosines, the centered images behave like a cloud living in fewer than ten dimensions rather than , an early glimpse of the low-rank structure we will study in Section 21.5. Practically, this means a cosine counts as large only when it stands out above the spread of unrelated pairs from the same dataset; training an embedding model is what pushes related pairs above that background.
21.1.3.3 The Scale of Attention Scores#
Dot-product attention (Section 10.2) scores a query against keys using and passes those scores through a softmax (Vaswani et al., 2017). A brief variance calculation explains where the comes from. Suppose all entries of and are mutually independent with mean and variance . Each product then has mean and variance , and distinct terms are uncorrelated because for . The variances of the terms therefore add:
Thus the raw dot products have standard deviation , which grows with the head dimension; dividing by restores unit variance. Without that scaling, the softmax saturates into near-one-hot weights. For , raw scores have standard deviation , and two scores separated by receive softmax weights and ; dividing by brings the weights back to a healthy and . Geometry gives the exact same scaling: each vector has length roughly , while the cosine between unrelated directions is roughly , so their dot product has typical magnitude .
Near-orthogonality does not, however, make unrelated keys harmless when there are many of them. Although any single unrelated cosine has scale , the largest cosine among independent keys grows, to leading order, like . In a large retrieval index, that worst-case background match is several times larger than , so a relevant key must clear a much higher bar, which is what training arranges (1 puts concrete numbers on this effect).
21.1.4 Hyperplanes and Decision Boundaries#
A linear classifier asks two geometric questions about an input : which side of a decision boundary does it fall on, and how far is it from that boundary? Throughout this section, we write the boundary as .
21.1.4.1 Hyperplanes and Signed Distance#
In the plane, this equation defines a straight line, and a quick example shows the roles of and . Take and . The points satisfying form the line . Every point on this line satisfies , so its shadow onto has the same signed length (21.1.4):
Geometrically, the line runs perpendicular to and crosses it at signed position , at distance from the origin.
Nothing changes in higher dimensions. A hyperplane in is a set with ; we call its normal vector and its offset. It is simply a shifted copy of the subspace , which has dimension (Section 21.2.2.2): a line in , a plane in , and a -dimensional flat sheet inside image space. The hyperplane partitions into two half-spaces, and . Adjusting translates the hyperplane parallel to itself along without tilting it.
How far is an arbitrary point from the hyperplane? Pick any point lying on the hyperplane, so . The distance from to the hyperplane is the signed length of the shadow of the displacement onto the normal , giving the signed distance
Notice that drops out completely: the signed distance depends only on , , and . It is positive on the side points toward, negative on the opposite side, and zero on the hyperplane itself. In our planar example, the origin sits at signed distance , while the point has score , placing it at signed distance on the positive side; its closest point on the line is . The point scores and lies directly on the line (Figure 21.1.7).
The hyperplane with normal . Left: for and , the hyperplane is the line at distance from the origin; the point lies at signed distance on the side points toward, and the shaded half-plane is . Right: in three dimensions the same equation defines a plane.
For a labeled example with , we also want to know whether it falls on the correct side. Multiplying the signed distance by the label defines the margin, , which is positive when the classification is right and grows larger the deeper the point sits inside its own half-space. Rescaling for any leaves both the hyperplane and the margin unchanged, while multiplying the raw score by . Any learning objective that maximizes the raw score must therefore constrain the scale of .
21.1.4.2 The Nearest-Mean Classifier#
Which hyperplane should we pick to separate two classes? The simplest rule requires no iterative training at all: assign to the class whose mean lies closer. Remarkably, this rule is itself a single hyperplane. Let and denote the two class means. Expanding both squared distances, the quadratic term cancels on both sides:
Using the identity , the final inequality becomes with
So "nearest mean" is just the perpendicular bisector hyperplane: its normal points from one mean to the other, and it cuts directly through their midpoint. There is no threshold to tune by hand, and the rule is invariant to uniform pixel rescaling: multiplying every pixel by sends and , scaling every score by without changing a single prediction (2 extends this invariance to rotations and translations, and constructs a per-pixel rescaling that does change predictions).
Before testing this classifier on t-shirts and trousers, let us inspect the two class means and compute the angle between them.
X0, X1 = X_train[y_train == 0], X_train[y_train == 1] # t-shirts, trousers
mean_0, mean_1 = X0.mean(axis=0), X1.mean(axis=0)
d2l.show_images([mean_0.reshape(28, 28), mean_1.reshape(28, 28)], 1, 2,
titles=['mean t-shirt', 'mean trousers'], cmap='Greys')
np.degrees(angle(mean_0, mean_1))np.float64(33.20917997376519)

Both mean images are blurry yet immediately recognizable. They sit only about apart (a cosine of ), far from orthogonal, because both garments occupy the bright center of the frame. Seeing the two means so close in angle might make us pessimistic, but the nearest-mean classifier does not require orthogonal means; it relies only on their difference. Let us evaluate it on all test images of t-shirts and trousers.
w = mean_1 - mean_0
b = -w @ (mean_0 + mean_1) / 2
mask = (y_test == 0) | (y_test == 1)
X2, y2 = X_test[mask], y_test[mask]
predictions = X2 @ w + b > 0 # True: trousers
np.mean(predictions == (y2 == 1))np.float64(0.9155)
The rule classifies about of the test images correctly, putting only of the on the wrong side. All we did was average each class and check which side of one hyperplane each test image falls on.
To understand where the remaining errors come from, we compress every test image to a single number, its signed distance (21.1.11) to the boundary, and plot the histogram for each class.
dist = (X2 @ w + b) / np.linalg.norm(w) # signed distance to boundary
bins = np.linspace(dist.min(), dist.max(), 51)
counts = [np.histogram(dist[y2 == c], bins)[0] for c in (0, 1)]
top = max(counts[0].max(), counts[1].max())
d2l.plot([bins[:-1]] * 2 + [[0, 0]], counts + [[0, top]], 'signed distance',
'number of images', fmts=('-', 'm--', 'k:'),
legend=['t-shirts', 'trousers', 'boundary'], figsize=(5, 3))The two classes form distinct modes whose tails cross the boundary. T-shirts form a broad hump centered around , while trousers form a sharper peak near with a long tail stretching toward zero. On average, each class sits near the signed distance of its training mean, . Let us quantify this picture by computing each class's standard deviation along and counting how many examples land on the wrong side.
(dist[y2 == 0].std(), dist[y2 == 1].std(),
int((dist[y2 == 0] > 0).sum()), int((dist[y2 == 1] < 0).sum()))(np.float64(2.356225995048113), np.float64(1.6627004538100882), 101, 68)
Along , t-shirts have a standard deviation of about and trousers about , with t-shirts and trousers misclassified. Because each class center lies less than two standard deviations from the boundary, an error rate of several percent is entirely expected. Notice the built-in limitation of the midpoint rule: it looks only at the two class means and has no way to account for the size or shape of either cloud. What happens when we apply it to harder pairs that look much more alike, such as t-shirts versus shirts or pullovers versus coats?
# t-shirt/trouser, t-shirt/shirt, pullover/coat
for a, c in [(0, 1), (0, 6), (2, 4)]:
m_a = X_train[y_train == a].mean(axis=0)
m_c = X_train[y_train == c].mean(axis=0)
w_ac, b_ac = m_c - m_a, -(m_c - m_a) @ (m_a + m_c) / 2
pair = (y_test == a) | (y_test == c)
acc = np.mean((X_test[pair] @ w_ac + b_ac > 0) == (y_test[pair] == c))
dist_ac = (X_test[pair] @ w_ac + b_ac) / np.linalg.norm(w_ac)
sd_a, sd_c = (dist_ac[y_test[pair] == k].std() for k in (a, c))
names = data.text_labels([a, c])
print(f'{names[0]:>8} vs {names[1]:<9}accuracy {acc:.3f} '
f'||w||/2 {np.linalg.norm(w_ac) / 2:.2f} '
f'std along w {sd_a:.2f}, {sd_c:.2f}')
T-shirt vs trouser accuracy 0.915 ||w||/2 3.23 std along w 2.36, 1.66
T-shirt vs shirt accuracy 0.786 ||w||/2 1.86 std along w 1.77, 2.38
pullover vs coat accuracy 0.716 ||w||/2 1.24 std along w 1.88, 2.09
Accuracy drops sharply: t-shirts versus shirts falls to about , and pullovers versus coats falls to about . The remaining columns explain why. Each training mean sits at distance from the boundary, and what governs overlap is that distance measured in units of each class's standard deviation along . For t-shirts and trousers, the gap is to standard deviations. For the two harder pairs, it shrinks to just to standard deviations, so a boundary placed at the midpoint slices straight through the bulk of both classes. The cure is to tilt away from directions along which the classes vary widely, which is the idea behind Fisher's linear discriminant (4). Softmax regression goes a step further by learning both the tilt and the offset directly from data, while a deep network transforms the inputs themselves into a representation where the classes become nearly separable by a single hyperplane.
21.1.4.3 Layers as Stacked Hyperplanes#
A linear neural network layer runs many hyperplane tests in parallel. Entry of the matrix-vector product is the dot product of row of with , a score against the normal , and adding a bias vector turns each entry into a hyperplane score. For instance, the ten-class softmax layer of Section 3.1 on Fashion-MNIST stores ten normals and ten offsets. Because it predicts the class with the highest score, the decision boundary separating classes and is the hyperplane where their two scores tie.
To see this concretely, take our chapter's running matrix and the input . Row one yields , meaning lies directly on the hyperplane through the origin with normal . Row two yields , placing on the negative side of the hyperplane with normal at signed distance . Stacking both results gives .
Viewing row by row reveals a linear layer as a stack of hyperplane tests, yet it leaves two essential questions unanswered: which inputs does the transformation collapse to zero, and when can its action be inverted? Reading the very same product column by column answers both questions in Section 21.2.
21.1.5 Summary#
The dot product extends lengths, angles, and projections from the plane to any dimension using the exact same formulas. Projecting onto a line or subspace produces the unique closest point, characterized by a residual orthogonal to the target space; from this single geometric fact follow the Cauchy–Schwarz inequality (which makes high-dimensional angles well defined) and the normal equations of least squares. The Gram–Schmidt process converts any spanning list into an orthonormal basis, yielding the factor of the QR factorization. While random directions in are nearly orthogonal with typical cosines of order , real image datasets are far from isotropic, so an observed cosine is meaningful only relative to unrelated pairs from the same distribution. Finally, the nearest-mean classifier defines a single hyperplane bisecting the two class means: it reaches about accuracy on t-shirts versus trousers, but drops to – on visually similar pairs where class spread along the boundary normal matters.
21.1.6 Exercises#
-
[code] Cosines between random vectors.
- Sample pairs of independent random unit vectors in dimensions by normalizing standard Gaussian vectors, and compute the cosine of each pair. Compare the empirical standard deviation with the prediction from the near-orthogonality proposition, and report the largest observed.
- A retrieval system compares one query against keys and returns the key with the largest cosine. Model the query and keys as independent random unit vectors in dimensions. Compute the maximum of the cosines for , , and , and compare it with , the leading-order estimate for the maximum of independent Gaussian draws of variance . How large a cosine does an unrelated key achieve as the top match among keys? How should a threshold for declaring two embeddings related scale with and ?
-
Nearest means and invariance. The nearest-mean rule assigns to class when , where and .
- Suppose every training and test image undergoes the same transformation , where , is square with , and is a fixed vector, and we recompute the class means and . Show that no prediction changes, and connect this to the rescaling , discussed in the text.
- Standardizing each pixel to unit variance replaces by for a positive diagonal matrix . Construct two class means and a test point in whose predicted class flips under such a .
- With classes under the nearest-mean rule, show that the region assigned to class is the intersection of the half-spaces for , and find . Compare this with the pairwise boundaries of a softmax layer: which choice of weights and biases makes a softmax layer reproduce the nearest-mean classifier?
-
Orthogonal and oblique projectors.
- Let satisfy and . Show that for every , lies in the column space of and is orthogonal to it. Deduce via Pythagoras' theorem that is the closest point in the column space, without invoking an orthonormal basis.
- The matrix satisfies but is not symmetric. For , compute and the orthogonal projection of onto the same column space (the first coordinate axis), along with the distance of each from . Along what direction does project points?
- Show that any matrix with decomposes every as , with the first term in the column space of and the second in its null space . Show that these two subspaces are orthogonal if and only if .
-
[code] Tilting the boundary. ● The mean-difference normal ignores how the images in each class spread around their mean. Let be the average of the two within-class covariance matrices on the training set. Fisher's linear discriminant (Fisher, 1936) selects the normal maximizing
the squared separation between the projected class means divided by the within-class variance of the projections. When is positive definite ( for all ), its inverse exists and the maximizer is . (This problem uses the matrix inverse from Section 21.2.2.3, positive definiteness from Section 21.3.2.2, and the condition number from Section 21.5.3.2.)
- Show that for every . When , apply Cauchy–Schwarz to show that maximizes .
- Using the arrays
X0andX1of t-shirts and trousers from the text, compute and let be the average pixel variance. For these images, has a condition number of about because some border pixels are nearly constant. For , form the regularized normal , place the boundary at the midpoint of the two means, and evaluate both training and test accuracy. Next, hold out training images per class, recompute and the class means on the remaining images, select by validation accuracy on the held-out set, and replot the signed-distance histogram using that . - Why does align with as ? Why scale the regularizer by instead of adding a fixed multiple of ?
-
[code] Gram–Schmidt in floating point. ● The Gram–Schmidt process can be executed in two algebraically equivalent orders. Classical Gram–Schmidt (CGS) computes by normalizing , as in our two-vector example. Modified Gram–Schmidt (MGS) initializes , updates sequentially for , and then normalizes .
- Show that CGS and MGS produce identical vectors in exact arithmetic.
- Implement both algorithms and run them on the Hilbert matrices
with entries for ,
whose columns are nearly linearly dependent. Plot the Frobenius norm
against for CGS, MGS,
and
np.linalg.qr. For each method, at what does fail to act as a projector, as measured by ? - Apply the CGS subtraction step twice to each column, running the second pass on the vector left by the first. How close to orthonormal are the resulting columns compared with a single pass of CGS and with MGS? Explain the improvement by comparing the size of the components along entering the first pass versus those entering the second.
-
[extended] Packing nearly orthogonal directions. ●● Although accommodates at most mutually orthogonal directions, it can pack vastly more directions whose pairwise cosines stay small. Elhage et al. (2022) use this geometry to explain how a layer of width can represent more than features in superposition as nearly orthogonal directions. Their features are sparse: each activates on only a small fraction of inputs, so only a few need to be read out at once. Let be unit vectors in , stacked as the rows of , and let denote their worst pairwise interference.
- Expand in coordinates and show that it equals , the sum of squared entries of the matrix . Bound this sum below using its diagonal terms together with Cauchy–Schwarz in the form , noting that . Bound the original sum above by to derive the Welch bound (Welch, 1974):
Evaluate this bound for with and .
- A union bound over all pairs shows that independent random directions keep for on the order of (Section 24.9). For and , compute for random unit vectors and compare it against the Welch bound.
- Reduce directly by optimization: minimize for an even power such as via gradient steps on , renormalizing every row after each step. For and , plot against for random vectors, optimized vectors, and the Welch bound.
- Use these curves to estimate, for each , the largest for which optimized directions keep . How does this capacity grow with compared with the random-direction rate ? How would your conclusions change if some features were more important than others, or if many features activated simultaneously?