Chapter 7 of 10 · ~22 min read & lab+55 XP
Chapter 7 · Linear Algebra

Orthogonality, Projections, Gram–Schmidt & Least Squares (OLS / Ridge)

Why orthonormal bases are magic (Qᵀ = Q⁻¹), Gram–Schmidt & QR factorization, Normal Equations, Hat Matrix H, and Ridge shrinkage

Why ML Engineers & Data Scientists Actually Need This

Orthogonal Projection IS Linear Regression (OLS) — and adding +λI gives Ridge Regression!

ML / AI Engineer

Every time you call `sklearn.linear_model.LinearRegression().fit(X, y)` or `Ridge(alpha=λ)`, under the hood it projects target vector y perpendicularly onto the column space of features X!

Data Scientist

Seeing OLS as a 90° sunlight shadow explains instantly why residuals e = y − ŷ are ALWAYS uncorrelated with every input feature (Xᵀe = 0) and why Ridge fixes collinearity!

Interview & Debug Edge

Deriving the Normal Equations `w = (XᵀX)⁻¹Xᵀy` in 2 lines purely from 'residual ⊥ features → Xᵀ(y − Xw) = 0' is a guaranteed jaw-dropper in ML interviews!

Step 0 · Test Your Gut Before Any Math!

In Ordinary Least Squares (OLS) Linear Regression with an intercept, you compute all prediction errors (residuals) e = y − ŷ. What is the dot product between the error vector e and ANY input feature column xⱼ?

What You Will Master in This Chapter
  • Identify orthogonal and orthonormal matrices (QᵀQ = I) and explain why they preserve vector lengths and angles.
  • Orthogonalize a set of vectors by hand using Gram–Schmidt (and see how that builds QR factorization X = QR).
  • Derive the OLS Normal Equations XᵀXw = Xᵀy both geometrically (Xᵀr = 0) and via calculus, plus the Hat Matrix H.
  • Explain geometrically and algebraically how Ridge regression (XᵀX + λI) shrinks small-singular-value directions.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“Projection (shadow) of y onto u”
Plain-English Meaning
Drop a straight 90° shadow from tip of y down onto arrow u — the closest reachable point along u!
Everyday Example
proj_u(y) = ((u · y) / (u · u)) · u.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Orthogonality (90∘90^\circ) is Linear Algebra's ultimate superpower: orthogonal matrices invert for free (Q−1=QTQ^{-1} = Q^T), orthogonal decomposition (QR) solves regression without numerical blow-up, and the global minimum of squared error happens precisely when the residual vector stands at 90∘90^\circ to your feature space!

1. Orthonormal Bases & Gram–Schmidt Orthogonalization

Everyday Story First (Zero Math Yet!)

Stand outside at high noon: the sun shines straight down and casts your shadow flat onto the ground. That shadow is your Orthogonal Projection! Why is it magical for Machine Learning? Because among ALL points on the ground, the spot directly underneath your head at 90° is the CLOSEST point to you (shortest possible error!).

Drag the angle below and see the 90° error line e ⊥ ŷ with your own eyes!

Step 1: Keep v₁q₁ = v₁ / ‖v₁‖First unit direction→Step 2: Subtract Shadowu₂ = v₂ − (q₁ᵀv₂)q₁Removes parallel part → u₂ ⊥ q₁→Step 3: Normalizeq₂ = u₂ / ‖u₂‖Orthonormal Q (QᵀQ = I)!
Figure 7.2 — Gram–Schmidt Orthogonalization: start with u₁, subtract v₂'s shadow onto u₁ to get an orthogonal u₂, then normalize both to unit length.

A square matrix QQ whose columns q1,…,qn\mathbf{q}_1, \dots, \mathbf{q}_n are mutually perpendicular unit vectors (qiTqj=1\mathbf{q}_i^T \mathbf{q}_j = 1 if i=ji=j, else 00) is called an orthogonal matrix, obeying the dream identity:

QTQ=I⟹Q−1=QTQ^T Q = I \quad \Longrightarrow \quad Q^{-1} = Q^T

Why ML loves orthogonal matrices: Multiplying by QQ preserves every length (∥Qx∥2=∥x∥2\|Q\mathbf{x}\|_2 = \|\mathbf{x}\|_2) and every angle ((Qx)T(Qy)=xTy(Q\mathbf{x})^T(Q\mathbf{y}) = \mathbf{x}^T\mathbf{y}), and inverting QQ is an instant O(1)O(1) transpose!

Worked Example 1 — Gram–Schmidt by Hand on Two Vectors

Turn v1=[3,4]T\mathbf{v}_1 = [3, 4]^T and v2=[2,1]T\mathbf{v}_2 = [2, 1]^T into an orthonormal pair {q1,q2}\{\mathbf{q}_1, \mathbf{q}_2\}:

  1. Normalize v1\mathbf{v}_1: ∥v1∥2=5  ⟹  q1=[0.6,0.8]T\|\mathbf{v}_1\|_2 = 5 \implies \mathbf{q}_1 = [0.6, 0.8]^T.
  2. Subtract shadow of v2\mathbf{v}_2 on q1\mathbf{q}_1:
    • q1Tv2=(0.6)(2)+(0.8)(1)=2.0\mathbf{q}_1^T \mathbf{v}_2 = (0.6)(2) + (0.8)(1) = 2.0.
    • u2=v2−2.0 q1=[2,1]T−[1.2,1.6]T=[0.8,−0.6]T\mathbf{u}_2 = \mathbf{v}_2 - 2.0\,\mathbf{q}_1 = [2, 1]^T - [1.2, 1.6]^T = [0.8, -0.6]^T.
  3. Normalize u2\mathbf{u}_2: ∥u2∥2=0.64+0.36=1.0  ⟹  q2=[0.8,−0.6]T\|\mathbf{u}_2\|_2 = \sqrt{0.64 + 0.36} = 1.0 \implies \mathbf{q}_2 = [0.8, -0.6]^T.
  • Verify: q1Tq2=(0.6)(0.8)+(0.8)(−0.6)=0\mathbf{q}_1^T \mathbf{q}_2 = (0.6)(0.8) + (0.8)(-0.6) = \mathbf{0}! Stacking them gives X=QRX = QR!
Hands-On Mini-Lab · Drop a Perpendicular Shadow Onto the Floor (OLS!)

Rotate data vector y below. The closest point on the line (your ML prediction ŷ) is ALWAYS directly underneath at a 90° right angle — making the residual error e = y − ŷ perpendicular to the line!

Shadow ŷ (Closest Fit!)Error e ⊥ ŷ
Try It Yourself

Apply Gram–Schmidt to v₁ = [1, 0]ᵀ and v₂ = [3, 4]ᵀ to find orthonormal q₁ and q₂.

2. Orthogonal Projection, Normal Equations & The Hat Matrix H

Everyday Story First (Zero Math Yet!)

When you have 10,000 houses and 5 features, no straight hyperplane passes through all 10,000 noisy prices (Xw = y has ZERO exact solutions!). So Linear Regression asks: "What is the CLOSEST reachable prediction ŷ = Xw in my feature plane?" Drop a 90° shadow! That forces Xᵀ(y − Xw) = 0, which rearranges in 1 line to XᵀXw = Xᵀy!

Column Space C(X)ŷ = Xŵ = Hyy (noisy observations)r = y − ŷ (90° ⊥ C(X))
Figure 7.1 — Least Squares Geometry: target y floats outside Column Space C(X); the optimal OLS prediction ŷ = Xŵ drops a 90° residual r ⊥ C(X).

In Linear Regression, y^=Xw\hat{\mathbf{y}} = X\mathbf{w} must live in C(X)\mathcal{C}(X). To minimize ∥y−Xw∥22\|\mathbf{y} - X\mathbf{w}\|_2^2, the residual r=y−Xw\mathbf{r} = \mathbf{y} - X\mathbf{w} must stand perpendicular to every column of XX:

XT(y−Xw)=0⟹XTXw∗=XTyX^T(\mathbf{y} - X\mathbf{w}) = \mathbf{0} \quad \Longrightarrow \quad \boxed{X^T X \mathbf{w}^* = X^T \mathbf{y}}

Substituting w∗=(XTX)−1XTy\mathbf{w}^* = (X^T X)^{-1} X^T \mathbf{y} gives y^=Hy\hat{\mathbf{y}} = H\mathbf{y}, where the Hat (Projection) Matrix is: H=X(XTX)−1XTH = X(X^T X)^{-1} X^T

  • Symmetric: HT=HH^T = H.
  • Idempotent: H2=HH^2 = H (projecting an already-projected vector changes nothing!).
  • Trace = Degrees of Freedom: tr(H)=p\text{tr}(H) = p. Diagonal HiiH_{ii} measures data point ii's leverage!

Solving OLS via QR (Better Than Normal Equations!)

Factor X=QRX = QR (QTQ=IQ^T Q = I, RR upper triangular). Plugging into XTXw=XTyX^T X \mathbf{w} = X^T \mathbf{y} cancels QTQ=IQ^T Q = I and RTR^T: Rw∗=QTyR \mathbf{w}^* = Q^T \mathbf{y} solved cleanly via back-substitution without ever squaring the condition number!

Formula Anatomy · Click Any Colored Piece to Decode It
Normal Equations & Ridge: w* = (XᵀX + λI)⁻¹ Xᵀy

Zero calculus needed — pure 90° shadow geometry plus Ridge safety cushion!

Geometric Origin: Error ⊥ Features

Demand that the leftover error (y − Xw) has ZERO dot product with every feature column in X!

In our example: Rearranges immediately to XᵀXw = Xᵀy!
Put it together with real numbers: Every single closed-form OLS & Ridge implementation in scikit-learn comes from this exact 1-line projection!
Try It Yourself

Fit y = w·x (no intercept) to x = [1, 2, 3]ᵀ and y = [2, 3, 7]ᵀ using w* = (xᵀy) / (xᵀx). Verify xᵀr = 0!

3. Ridge Regression: Selective Spectral Shrinkage

Everyday Story First (Zero Math Yet!)

How do you turn crooked, overlapping feature arrows into neat, 90°-perpendicular unit rulers (QR decomposition)? Gram–Schmidt: keep arrow #1, subtract arrow #2's shadow along arrow #1 so ONLY the perpendicular part remains, normalize both — done! That gives X = QR so solving regression becomes lightning-fast back-substitution Rw = Qᵀy!

OLS = 1.0 (no shrinkage)Singular Value σ (Noisy ← → Strong Signal)Ridge: σ² / (σ² + λ)• Small σ (noise) → shrunk to ~0• Large σ (signal) → preserved ~1
Figure 7.3 — Ridge Shrinkage Factor σ²/(σ² + λ): strong signal directions (large σ) stay near 1.0, while noisy low-variance directions (small σ) are smoothly damped toward 0.

Adding an L2L_2 penalty λ∥w∥22\lambda \|\mathbf{w}\|_2^2 yields (XTX+λI)wridge=XTy(X^T X + \lambda I)\mathbf{w}_{\text{ridge}} = X^T \mathbf{y}. In the SVD basis X=UΣVTX = U\Sigma V^T, Ridge multiplies each component ii by: shrinkagei=σi2σi2+λ\text{shrinkage}_i = \frac{\sigma_i^2}{\sigma_i^2 + \lambda}

  • Strong signal directions (σi2≫λ\sigma_i^2 \gg \lambda): factor ≈1\approx 1 (nearly untouched!).
  • Weak/collinear noise directions (σi2≪λ\sigma_i^2 \ll \lambda): factor ≈0\approx 0 (aggressively suppressed, eliminating variance explosion!).
Pause & Check · Quick Intuition Pulse

Pause & Check: Why does adding +λI (with λ > 0) in Ridge Regression ALWAYS make (XᵀX + λI) invertible, even if two feature columns are 100% identical?

Try It Yourself

With Ridge penalty λ = 4, compare the shrinkage factor σ²/(σ² + λ) for a strong direction σ = 10 versus a noisy direction σ = 0.5.

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Because inverting a d × d matrix costs O(d3)O(d^3) operations! When d = 20 tabular features, 203=8,00020^3 = 8{,}000 ops (microseconds → closed form wins!). When d = 1,000,000 parameters in a neural net, d3=1018d^3 = 10^{18} ops (impossible — and neural nets are nonlinear anyway → Gradient Descent wins!).

Interactive Visual Lab
Lab Challenge: Adjust slope w (or click Snap to OLS Optimum) until xᵀr ≈ 0 and MSE reaches its minimum!
Slope w (ŷ = w·x)w = 0.45
MSE Loss
3.556
xᵀr (Normal Eq)
30.95
Geometric Takeaway: Orthonormal matrices invert by transpose (Qᵀ = Q⁻¹); OLS minimizes squared error where Xᵀr = 0; Ridge selectively damps small-σ noisy directions via σ²/(σ² + λ).
Where This Powers Real ML, Deep Learning & GenAI

OLS, Ridge & IRLS (Logistic Regression)

Closed-form OLS, Ridge, and Newton/IRLS steps for GLMs all project targets orthogonally onto feature space.

CUPED Variance Reduction in A/B Testing

CUPED removes pre-experiment noise by projecting post-experiment metric Y orthogonally onto covariate X: Var(Y_cuped) = (1 − ρ²)Var(Y).

Double Machine Learning (Frisch–Waugh–Lovell)

Isolates causal treatment effects by projecting both outcome Y and treatment T orthogonally off confounders Z.

QR Solvers Inside NumPy, SciPy & R

`np.linalg.lstsq` uses QR/SVD orthogonalization so linear regression stays numerically accurate even on correlated columns.

Production NumPy & PyTorch Code Patterns
import numpy as np

rng = np.random.default_rng(42)
X = np.hstack([np.ones((100, 1)), rng.normal(size=(100, 3))])   # (100, 4)
y = X @ np.array([2.0, 1.5, -0.8, 0.4]) + rng.normal(0, 0.1, size=100)

# 1) OLS via QR decomposition (stably avoids forming X^T X!):
Q, R = np.linalg.qr(X)
w_qr = np.linalg.solve(R, Q.T @ y)

# 2) Ridge Regression — leave intercept column 0 UNPENALIZED!
P = np.eye(X.shape[1])
P[0, 0] = 0.0
w_ridge = np.linalg.solve(X.T @ X + 1.0 * P, X.T @ y)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Penalizing the intercept column in Ridge / Lasso
Best Practice: Set P[0, 0] = 0 (or center y and X first) so Ridge never shrinks the baseline prediction toward 0.
Trap #2: Forgetting to standardize features before Ridge
Best Practice: L2 penalty λΣw_j² depends on feature units — always standardize features to unit variance first!
Trap #3: Assuming residuals always sum to 0
Best Practice: Σ r_i = 1ᵀr = 0 holds ONLY when an intercept column of all 1s is included in X.
Chapter Mastery Check (+55 XP)
Score: 0 / 5
1For any orthogonal matrix Q (QᵀQ = I), what equals Q⁻¹?
2At the OLS optimum ŵ, what is Xᵀ(y − Xŵ)?
3If H = X(XᵀX)⁻¹Xᵀ is the projection (Hat) matrix, what equals H²?
4In Ridge regression (XᵀX + λI)w = Xᵀy, which directions get shrunk the MOST?
5Why does QR factorization (Rw = Qᵀy) beat forming XᵀXw = Xᵀy directly?

Apply What You Learned — Solve Matching Coding Problems