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
Orthogonal Projection IS Linear Regression (OLS) — and adding +λI gives Ridge Regression!
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!
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!
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!
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ⱼ?
- 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.
Orthogonality () is Linear Algebra's ultimate superpower: orthogonal matrices invert for free (), orthogonal decomposition (QR) solves regression without numerical blow-up, and the global minimum of squared error happens precisely when the residual vector stands at to your feature space!
1. Orthonormal Bases & Gram–Schmidt Orthogonalization
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!
A square matrix whose columns are mutually perpendicular unit vectors ( if , else ) is called an orthogonal matrix, obeying the dream identity:
Why ML loves orthogonal matrices: Multiplying by preserves every length () and every angle (), and inverting is an instant transpose!
Worked Example 1 — Gram–Schmidt by Hand on Two Vectors
Turn and into an orthonormal pair :
- Normalize : .
- Subtract shadow of on :
- .
- .
- Normalize : .
- Verify: ! Stacking them gives !
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!
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
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!
In Linear Regression, must live in . To minimize , the residual must stand perpendicular to every column of :
Substituting gives , where the Hat (Projection) Matrix is:
- Symmetric: .
- Idempotent: (projecting an already-projected vector changes nothing!).
- Trace = Degrees of Freedom: . Diagonal measures data point 's leverage!
Solving OLS via QR (Better Than Normal Equations!)
Factor (, upper triangular). Plugging into cancels and : solved cleanly via back-substitution without ever squaring the condition number!
Zero calculus needed — pure 90° shadow geometry plus Ridge safety cushion!
Demand that the leftover error (y − Xw) has ZERO dot product with every feature column in X!
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
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!
Adding an penalty yields . In the SVD basis , Ridge multiplies each component by:
- Strong signal directions (): factor (nearly untouched!).
- Weak/collinear noise directions (): factor (aggressively suppressed, eliminating variance explosion!).
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?
With Ridge penalty λ = 4, compare the shrinkage factor σ²/(σ² + λ) for a strong direction σ = 10 versus a noisy direction σ = 0.5.
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because inverting a d × d matrix costs operations! When d = 20 tabular features, ops (microseconds → closed form wins!). When d = 1,000,000 parameters in a neural net, ops (impossible — and neural nets are nonlinear anyway → Gradient Descent wins!).
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.
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)