Vectors, Angles, and Projections

Dive into Deep Learning · §33.1

Vectors, Angles, and Projections
dot products · orthogonal shadows · Cauchy–Schwarz · subspaces & QR · high-dimensional cosines · hyperplanes

One Dot Product Classifies 92% of Test Images

Motivation

  • Three Geometric Operations in ML: Models compare representations (similarity), fit targets (least-squares projection), and separate classes (hyperplane boundaries).
  • A Concrete Test in \mathbb{R}^{784}: Each 28 \times 28 Fashion-MNIST image is a point in 784-dimensional space where no picture can be drawn.
  • The Simplest Classifier: Average all training t-shirts and all training trousers, then assign each test image to whichever class mean lies closer—a rule that reduces to a single dot product and reaches 92\% test accuracy.

np.float64(33.20917997376519)

Vectors as Points and as Displacements

Vector Geometry

  • Point Viewpoint: A vector \mathbf{v} = (3, 2) names a fixed coordinate location relative to the origin \mathbf{0}, turning a dataset of n examples into a cloud of n points in \mathbb{R}^d.
  • Direction Viewpoint: The same vector represents a displacement (3 steps right, 2 steps up) that can start anywhere; all parallel arrows of equal length represent the same vector.
  • The Dot Product Engine: Every geometric quantity in \mathbb{R}^d grows out of one symmetric operation (|\mathbf{u}| = \sqrt{\mathbf{u}\cdot\mathbf{u}}): \mathbf{u}^\top\mathbf{v} = \mathbf{u}\cdot\mathbf{v} = \sum_{i=1}^d u_i v_i

Tip-to-Tail Addition and Relative Displacement

Vector Geometry

  • Vector Addition (\mathbf{u} + \mathbf{v}): In the displacement view, adding two vectors means following arrow \mathbf{u} and then following arrow \mathbf{v} from its tip.
  • Vector Subtraction (\mathbf{u} - \mathbf{v}): Since \mathbf{u} = \mathbf{v} + (\mathbf{u} - \mathbf{v}), the difference \mathbf{u} - \mathbf{v} is the exact displacement arrow carrying point \mathbf{v} to point \mathbf{u}.
  • Euclidean Distance: The distance between two data points \mathbf{u}, \mathbf{v} \in \mathbb{R}^d is simply the length of their difference arrow, \|\mathbf{u} - \mathbf{v}\| = \sqrt{(\mathbf{u} - \mathbf{v})\cdot(\mathbf{u} - \mathbf{v})}.

Projection onto a Line: Closest Multiple

Orthogonal Projection

  • 1D Fitting Problem: Given \mathbf{v} = (1, 3) and a direction \mathbf{w} = (2, 1), which scalar multiple t\mathbf{w} comes closest to \mathbf{v}?
  • Quadratic Error Curve: Expanding the squared error yields a convex parabola in t: q(t) = \|\mathbf{v} - t\mathbf{w}\|^2 = \|\mathbf{w}\|^2 t^2 - 2(\mathbf{v}\cdot\mathbf{w})t + \|\mathbf{v}\|^2
  • Unique Minimum (q'(t^\star) = 0): Setting 2\|\mathbf{w}\|^2 t - 2(\mathbf{v}\cdot\mathbf{w}) = 0 gives t^\star = (\mathbf{v}\cdot\mathbf{w})/(\mathbf{w}\cdot\mathbf{w}). For our pair, t^\star = 5/5 = 1, giving shadow (2, 1) and residual \mathbf{r} = (-1, 2).

Orthogonality and Pythagoras in Any Dimension

Orthogonal Projection

  • Orthogonal Projection Formula: The closest multiple of \mathbf{w} \neq \mathbf{0} to \mathbf{v} is \operatorname{proj}_{\mathbf{w}}\mathbf{v} = \frac{\mathbf{v}\cdot\mathbf{w}}{\mathbf{w}\cdot\mathbf{w}}\mathbf{w}, leaving residual \mathbf{r} = \mathbf{v} - \operatorname{proj}_{\mathbf{w}}\mathbf{v} \perp \mathbf{w}.
  • Pythagoras’ Theorem (\mathbf{a}\cdot\mathbf{b} = 0): Cross terms vanish, so \|\mathbf{v}\|^2 = \|\operatorname{proj}_{\mathbf{w}}\mathbf{v}\|^2 + \|\mathbf{r}\|^2 (10 = 5 + 5).
  • Signed Shadow Length: Multiplying t^\star by \|\mathbf{w}\| gives (\mathbf{v}\cdot\mathbf{w})/\|\mathbf{w}\|.

Cauchy–Schwarz From a Right Triangle

Angles in High Dimensions

  • Cauchy–Schwarz Inequality: For all \mathbf{v}, \mathbf{w} \in \mathbb{R}^d, |\mathbf{v}\cdot\mathbf{w}| \le \|\mathbf{v}\|\,\|\mathbf{w}\|, with equality iff \mathbf{v} and \mathbf{w} are collinear.
  • One-Line Proof: Dropping \|\mathbf{r}\|^2 \ge 0 from Pythagoras gives \|\mathbf{v}\|^2 \ge \|\operatorname{proj}_{\mathbf{w}}\mathbf{v}\|^2 = (\mathbf{v}\cdot\mathbf{w})^2/\|\mathbf{w}\|^2.
  • Triangle Inequality: Bounding 2\mathbf{v}\cdot\mathbf{w} \le 2\|\mathbf{v}\|\|\mathbf{w}\| proves \|\mathbf{v} + \mathbf{w}\| \le \|\mathbf{v}\| + \|\mathbf{w}\|.

Defining Angles and Guarding Against Roundoff

Angles in High Dimensions

  • High-Dimensional Angle: Cauchy–Schwarz keeps the cosine ratio in [-1, 1], defining \theta = \arccos\!\left(\frac{\mathbf{v}\cdot\mathbf{w}}{\|\mathbf{v}\|\|\mathbf{w}\|}\right) \in [0, \pi].
  • Floating-Point Guard: Collinear vectors can round to 1 + 2.2\times 10^{-16}; always wrap ratios in np.clip(cos, -1, 1).
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

Span, Linear Independence, Basis, and Dimension

Subspaces

  • Span & Subspaces: The set of all linear combinations \operatorname{span}(\mathbf{v}_1, \ldots, \mathbf{v}_k) = \{\sum_{i=1}^k a_i \mathbf{v}_i\} is closed under addition and scaling, forming a subspace through the origin \mathbf{0}.
  • Linear Independence: Vectors \mathbf{v}_1, \ldots, \mathbf{v}_k are independent when no vector is redundant—the only combination giving \sum_i a_i \mathbf{v}_i = \mathbf{0} is a_1 = \cdots = a_k = 0.
  • Basis & Unique Coordinates: A basis of a subspace S is an independent spanning set; its vector count is the dimension \dim S, and every \mathbf{x} \in S has unique coordinates (a_1, \ldots, a_k).

Fitting a Line Is Projecting onto a Plane

Least Squares

  • Candidate Subspace in \mathbb{R}^3: Fitting C + Dt to \mathbf{y} = (6, 0, 0) at times \mathbf{t} = (0, 1, 2) seeks the closest vector C\mathbf{1} + D\mathbf{t} in the 2D plane S = \operatorname{span}(\mathbf{1}, \mathbf{t}).
  • Orthogonality Equations: The residual \mathbf{r} = \mathbf{y} - C\mathbf{1} - D\mathbf{t} must be perpendicular to the entire plane S, hence to both basis vectors (\mathbf{1}\cdot\mathbf{r} = 6 - 3C - 3D = 0 and \mathbf{t}\cdot\mathbf{r} = -3C - 5D = 0): 3C + 3D = 6 \implies C = 5, \; D = -3
  • Solution & Error Split: The best line 5 - 3t gives predicted vector (5, 2, -1) and residual \mathbf{r} = (1, -2, 1) with \|\mathbf{y}\|^2 = 36 = 30 + 6.

Subspace Projection Matrix P = QQᵀ

Least Squares

  • Orthonormal Basis Matrix \mathbf{Q} \in \mathbb{R}^{n \times k}: Columns \mathbf{q}_1, \ldots, \mathbf{q}_k span S with \mathbf{Q}^\top\mathbf{Q} = \mathbf{I}_k.
  • Unique Closest Point: \mathbf{P} = \mathbf{Q}\mathbf{Q}^\top projects onto S with \mathbf{x} - \mathbf{P}\mathbf{x} \perp S, minimizing \|\mathbf{x} - \mathbf{s}\|^2 = \|\mathbf{x} - \mathbf{P}\mathbf{x}\|^2 + \|\mathbf{P}\mathbf{x} - \mathbf{s}\|^2.
  • Projector Algebra: Idempotent (\mathbf{P}^2 = \mathbf{P}) and symmetric (\mathbf{P}^\top = \mathbf{P}).

Normal Equations vs. Orthonormal Projection

Least Squares

  • Normal Equations: \mathbf{A}^\top(\mathbf{y} - \mathbf{A}\hat{\mathbf{x}}) = \mathbf{0} \implies \mathbf{A}^\top\mathbf{A}\hat{\mathbf{x}} = \mathbf{A}^\top\mathbf{y}.
  • Why Solvers Prefer QR: Forming \mathbf{A}^\top\mathbf{A} squares \kappa(\mathbf{A}), whereas \mathbf{A} = \mathbf{Q}\mathbf{R} preserves conditioning.
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

Gram–Schmidt and the QR Factorization

Orthonormalization

  • Sequential Projection: Subtract projections onto \mathbf{q}_1, \ldots, \mathbf{q}_{j-1} and normalize: \mathbf{v}_j = \mathbf{a}_j - \sum_{i<j}(\mathbf{q}_i\cdot\mathbf{a}_j)\mathbf{q}_i, \mathbf{q}_j = \mathbf{v}_j/\|\mathbf{v}_j\|.
  • Worked 2 \times 2 Pair: \mathbf{a}_1 = (3, 4) \implies \mathbf{q}_1 = (0.6, 0.8); \mathbf{a}_2 = (1, 0) \implies \mathbf{v}_2 = (0.64, -0.48) \implies \mathbf{q}_2 = (0.8, -0.6).
  • Upper-Triangular \mathbf{A} = \mathbf{Q}\mathbf{R}: Reversing steps gives r_{ij} = \mathbf{q}_i\cdot\mathbf{a}_j (i \le j).

Gram–Schmidt by Hand vs. Householder QR

Orthonormalization

Comparing our two-step Gram–Schmidt orthogonalization against np.linalg.qr confirms that both construct the same orthonormal basis up to column sign flips:

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]]

Reflections in Floating Point: Numerical libraries compute \mathbf{A} = \mathbf{Q}\mathbf{R} using Householder reflections rather than classical Gram–Schmidt subtractions, preserving machine-precision orthogonality even when columns are nearly collinear.

Cosine Similarity in High-Dimensional Space

High-Dimensional Geometry

  • Scale-Invariant Direction Metric: Cosine similarity \cos\theta = (\mathbf{v}\cdot\mathbf{w})/(\|\mathbf{v}\|\|\mathbf{w}\|) \in [-1, 1] measures pure directional alignment.
  • Brightness Invariance: Dimming an image to 10\% changes Euclidean distance but leaves \cos\theta = 1.
  • Retrieval vs. Attention: Contrastive learning (SimCLR, CLIP) normalizes vectors, while attention uses \mathbf{q}\cdot\mathbf{k}/\sqrt{d}.

Random Directions in ℝᵈ Are Nearly Orthogonal

Concentration of Measure

  • Isotropic Baseline: Fix a unit vector \mathbf{u} \in \mathbb{R}^d and draw \mathbf{v} uniformly from the unit sphere. By rotational invariance, take \mathbf{u} = \mathbf{e}_1 so \cos\theta = v_1.
  • Mean and Variance: Sign symmetry gives \mathbb{E}[\cos\theta] = \mathbb{E}[v_1] = 0, and coordinate symmetry across \sum_{i=1}^d v_i^2 = 1 forces d\,\mathbb{E}[v_1^2] = 1: \operatorname{Var}(\cos\theta) = \mathbb{E}[v_1^2] = \frac{1}{d}
  • Concentration Spike: Typical random cosines scale as 1/\sqrt{d} (\approx 0.036 in \mathbb{R}^{784}), collapsing into a narrow spike around 0 (90^\circ).

Simulating Random vs. Real Image Cosines

Concentration of Measure

Normalizing standard Gaussian vectors confirms the 1/\sqrt{784} \approx 0.036 spread, whereas real Fashion-MNIST test images behave very differently:

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))

Simulating Random vs. Real Image Cosines (cont.)

Concentration of Measure

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))

Why Real Data Depart From the Isotropic Baseline

Data Geometry

  • Positive-Orthant Shift (\approx 0.60 \pm 0.18): Raw pixels in [0, 1]^{784} lie in the non-negative orthant where dot products are never negative.
  • Low Effective Dimension After Centering (\approx 0.00 \pm 0.34): Subtracting the mean image centers cosines at 0, but spread 0.34 matches d_{\text{eff}} = 1/0.34^2 \approx 8.6 dimensions.
  • Retrieval Benchmark Rule: Always compare cosines against random pairs from the same data distribution.

Why Dot-Product Attention Divides by √d

Transformer Geometry

  • Variance Growth (\operatorname{Var}(\mathbf{q}\cdot\mathbf{k}) = d): For independent unit-variance entries, d uncorrelated products q_i k_i add to standard deviation \sqrt{d}.
  • Preventing Softmax Saturation: At d = 64, raw scores have \sigma = 8, driving a 1\sigma gap to (0.9997, 0.0003); dividing by \sqrt{d} = 8 restores (0.73, 0.27).
  • Retrieval Threshold Across n Keys: Maximum background cosine among n random keys scales as \sqrt{2\ln n / d}.

Hyperplanes and Signed Distance to the Boundary

Linear Decision Boundaries

  • Hyperplane Equation: In \mathbb{R}^d, \{\mathbf{x} : \mathbf{w}\cdot\mathbf{x} + b = 0\} with normal \mathbf{w} \neq \mathbf{0} and offset b is a (d-1)-dimensional flat sheet partitioning space into two half-spaces (\gtrless 0).
  • Signed Distance Formula: Picking any \mathbf{x}_0 on the hyperplane (\mathbf{w}\cdot\mathbf{x}_0 = -b) and projecting \mathbf{x} - \mathbf{x}_0 onto \mathbf{w} gives: \text{dist}(\mathbf{x}) = \frac{\mathbf{w}\cdot(\mathbf{x} - \mathbf{x}_0)}{\|\mathbf{w}\|} = \frac{\mathbf{w}\cdot\mathbf{x} + b}{\|\mathbf{w}\|}
  • Geometric Margin: For label y \in \{-1, +1\}, the margin y(\mathbf{w}\cdot\mathbf{x} + b)/\|\mathbf{w}\| is positive when classified correctly and scale-invariant under (\mathbf{w}, b) \mapsto (c\mathbf{w}, cb).

Nearest-Mean Classification Is One Hyperplane

Linear Classifiers

  • Quadratic Cancellation: In \|\mathbf{x} - \bar{\mathbf{x}}_1\|^2 < \|\mathbf{x} - \bar{\mathbf{x}}_0\|^2, \|\mathbf{x}\|^2 cancels on both sides.
  • Perpendicular Bisector: Normal \mathbf{w} = \bar{\mathbf{x}}_1 - \bar{\mathbf{x}}_0 and midpoint offset b = -\mathbf{w}\cdot\tfrac{1}{2}(\bar{\mathbf{x}}_0 + \bar{\mathbf{x}}_1) reach 92\% accuracy on t-shirts vs. 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)

Signed-Distance Histogram and Class Overlap

Error Analysis

  • 1D Projection Along \mathbf{w}: Projecting all 2{,}000 test images onto the normal \mathbf{w} = \bar{\mathbf{x}}_1 - \bar{\mathbf{x}}_0 compresses each 784-pixel image to its signed distance (\mathbf{w}\cdot\mathbf{x} + b)/\|\mathbf{w}\| from the boundary.
  • Two Modes at \mp\|\mathbf{w}\|/2 \approx \mp 3.2: T-shirts form a broad hump (\sigma \approx 2.4) on the negative side and trousers form a sharper peak (\sigma \approx 1.7) on the positive side.
  • Tail Overlap (169 Errors): Because the boundary sits 1.4\sigma to 1.9\sigma from each class center, the tails cross zero (101 t-shirts and 68 trousers misclassified).

Why Nearest Mean Fails on High-Variance Pairs

Classifier Limitations

  • Signal-to-Spread Ratio: The midpoint rule looks only at class centroids \bar{\mathbf{x}}_0, \bar{\mathbf{x}}_1 and ignores how widely each cloud spreads along \mathbf{w}:
 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
  • From 92\% Down to 72\%: On visually similar garments (t-shirt vs. shirt, pullover vs. coat), the half-distance \|\mathbf{w}\|/2 shrinks to 0.6\sigma–1.0\sigma, slicing through both clouds.
  • Layers as Stacked Hyperplanes: A linear layer \mathbf{A}\mathbf{x} + \mathbf{b} evaluates m hyperplane scores in parallel (one per row), and learning via Fisher’s discriminant, softmax regression, or deep representations tilts normals away from high-variance directions.

Concept Check: Projections, Cosines & Hyperplanes

Concept Check

  1. Projection & Pythagoras: Project \mathbf{v} = (3, 2) onto \mathbf{w} = (2, 1), find the residual \mathbf{r}, and verify \|\mathbf{v}\|^2 = \|\operatorname{proj}_{\mathbf{w}}\mathbf{v}\|^2 + \|\mathbf{r}\|^2.
  2. Attention Scaling: In a Transformer head with dimension d = 100 and unit-variance query/key entries, what is the standard deviation of raw dot products \mathbf{q}\cdot\mathbf{k} before scaling?
  3. Hyperplane Row View: For \mathbf{A} = \left(\begin{smallmatrix}1&2\\-1&3\end{smallmatrix}\right) and \mathbf{x} = (2, -1), what signed distances does \mathbf{x} have to the two origin hyperplanes defined by the rows of \mathbf{A}?

Answers: 1. t^\star = \frac{8}{5} = 1.6, so \operatorname{proj}_{\mathbf{w}}\mathbf{v} = (3.2, 1.6) and \mathbf{r} = (-0.2, 0.4) with \mathbf{r}\cdot\mathbf{w} = 0 and 13 = 12.8 + 0.2. 2. \operatorname{Std}(\mathbf{q}\cdot\mathbf{k}) = \sqrt{d} = 10, which is why attention divides scores by \sqrt{100} = 10. 3. Row 1 gives \mathbf{a}_1\cdot\mathbf{x} = 0 (lies directly on hyperplane 1); Row 2 gives \mathbf{a}_2\cdot\mathbf{x} = -5, so signed distance is -5/\sqrt{10} \approx -1.58.

Summary: Vectors, Angles, and Projections

Key Takeaways

Concept Mathematical Formula Key Property / Deep Learning Role
Line Projection \operatorname{proj}_{\mathbf{w}}\mathbf{v} = \frac{\mathbf{v}\cdot\mathbf{w}}{\mathbf{w}\cdot\mathbf{w}}\mathbf{w} Residual \mathbf{r} = \mathbf{v} - \operatorname{proj}_{\mathbf{w}}\mathbf{v} \perp \mathbf{w}; Pythagoras \|\mathbf{v}\|^2 = \|\operatorname{proj}\|^2 + \|\mathbf{r}\|^2
Cauchy–Schwarz & Angle |\mathbf{v}\cdot\mathbf{w}| \le \|\mathbf{v}\|\|\mathbf{w}\|, \cos\theta = \frac{\mathbf{v}\cdot\mathbf{w}}{\|\mathbf{v}\|\|\mathbf{w}\|} Keeps cosine in [-1, 1] in any dimension; clip to [-1, 1] in float arithmetic
Subspace Projector \mathbf{P} = \mathbf{Q}\mathbf{Q}^\top (\mathbf{Q}^\top\mathbf{Q} = \mathbf{I}_k) Unique closest point in S; idempotent (\mathbf{P}^2 = \mathbf{P}) and symmetric (\mathbf{P}^\top = \mathbf{P})
Least Squares & QR \mathbf{A}^\top\mathbf{A}\hat{\mathbf{x}} = \mathbf{A}^\top\mathbf{y}, \mathbf{A} = \mathbf{Q}\mathbf{R} Gram–Schmidt / Householder QR avoids squaring \kappa(\mathbf{A}) in normal equations
Random Cosines in \mathbb{R}^d \mathbb{E}[\cos\theta] = 0, \operatorname{Var}(\cos\theta) = 1/d Random directions are within \pm 1/\sqrt{d} of orthogonal; attention scales by 1/\sqrt{d}
Hyperplane & Nearest Mean \text{dist}(\mathbf{x}) = \frac{\mathbf{w}\cdot\mathbf{x} + b}{\|\mathbf{w}\|}, \mathbf{w} = \bar{\mathbf{x}}_1 - \bar{\mathbf{x}}_0 Midpoint bisector achieves 92\% on t-shirts vs. trousers; linear layers stack m hyperplanes