Least Squares as Optimization#
Given a design matrix and labels , ordinary least squares (OLS) minimises:
Expanding (the is a convenient factor that cancels with the derivative of the square):
This is a convex quadratic in — the Hessian is , which is always PSD. The gradient is:
GD update: . Since the Hessian is constant, is -smooth with , the largest eigenvalue of the Gram matrix.
Worked example — :
Eigenvalues of : the characteristic polynomial is , so . So , , — well-conditioned.
Closed Form vs Iterative#
The OLS solution solves the normal equations:
When is invertible (i.e. has full column rank), this gives the exact minimiser in one linear solve.
So why ever use gradient descent?
- is huge: Computing costs . If , this is prohibitive — but computing for one sample is , which is why SGD (Week 6) shines.
- is huge: Inverting costs . If , the closed form is impossible — but a GD step is .
- Regularisation changes the game: Adding terms beyond (like in Week 10) breaks the closed form entirely.
The tradeoff: the closed form gives exact answers in one shot for small-to-moderate . Iterative methods trade exactness for scalability and flexibility.
Ridge Regression#
Adding regularisation gives ridge regression:
The gradient becomes , and the Hessian is .
The crucial effect: even if is nearly singular (some eigenvalues near zero), adding shifts all eigenvalues up by :
This guarantees strong convexity with and improves the condition number:
Regularisation makes GD converge faster — a happy synergy between statistical regularisation and optimisation efficiency.
The closed form is .
Condition Number and Convergence#
Recall from Week 3: for strongly convex , GD's convergence factor is .
Practical intuition — iterations needed to reach tolerance :
| Problem type | Iterations (approx) | |
|---|---|---|
| 1 | Perfectly spherical | 1 |
| 2–10 | Well-conditioned | 10–100 |
| 100 | Moderately ill-conditioned | 1,000+ |
| 10,000 | Ill-conditioned | 100,000+ |
| Very ill-conditioned | Intractable for plain GD |
When is large, we look to momentum (reduces effective to , Week 7), Newton/quasi-Newton methods (directly use Hessian to undo ill-conditioning), or adaptive methods (per-parameter step sizes, Week 8).
Numerical Example — vs #
Consider two least squares problems in , both with optimum :
- Well-conditioned: ,
- Ill-conditioned: ,
GD with on the ill-conditioned problem will shrink quickly (large gradient component) but very slowly (small gradient component). The iterates trace a zigzag down the narrow valley.
The condition number is the elongation of the contours. When the level sets are circles and GD heads straight for the minimum; at the same algorithm zigzags across a narrow valley and needs far more iterations.
Knowledge Check#
Given eigenvalues [1, 100] of X^T X, the condition number κ = ___.
The OLS objective f(w) = ½‖Xw−y‖² is convex because its Hessian X^T X is:
Browser lab: conditioning and convergence speed#
Run GD on LS with condition numbers , , and . Plot vs iteration on a log scale and compare convergence speed.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
d = 2
n = 200
kappas = [1, 10, 100]
fig, axes = plt.subplots(1, 3, figsize=(14, 4.5))
for ax, kappa in zip(axes, kappas):
diag = np.array([np.sqrt(kappa), 1.0])
w_true = rng.normal(size=d)
X = rng.normal(size=(n, d)) @ np.diag(diag)
y = X @ w_true
XTX = X.T @ X
L = np.linalg.eigvalsh(XTX).max()
eta = 1.0 / L
w = np.zeros(d)
K = 200
dists = [np.linalg.norm(w - w_true)]
for _ in range(K):
g = X.T @ (X @ w - y)
w = w - eta * g
dists.append(np.linalg.norm(w - w_true))
ax.semilogy(dists, linewidth=1.5)
ax.set_xlabel("Iteration")
ax.set_ylabel(r"$\|w_k - w^*\|$")
ax.set_title(f"$\\kappa \\approx {kappa}$")
ax.grid(True, alpha=0.3)
print(f"kappa={kappa:3d}: final distance to w* = {dists[-1]:.3e}")
plt.tight_layout()
plt.show()
print("Notice: larger κ means slower convergence — GD crawls along the shallow direction.")
Further Reading#
- Stephen Boyd & Lieven Vandenberghe, Introduction to Applied Linear Algebra (Cambridge University Press, 2018). Chapters 12–13 derive least squares and its data-fitting uses. Freely available at vmls-book.stanford.edu.
- Lloyd N. Trefethen & David Bau, Numerical Linear Algebra (SIAM, 1997). Lectures 11–12 cover least squares and the conditioning of the normal equations.
- Jorge Nocedal & Stephen Wright, Numerical Optimization (2nd ed., Springer, 2006). Chapter 10 is the reference treatment of linear least-squares problems.