Linear Regression

Dive into Deep Learning · §2.1

Linear Regression: Theory, Geometry & Stochastic Optimization
affine model · squared loss · normal equations · orthogonal projection · minibatch SGD · Gaussian MLE

Predicting Continuous Quantities From Features

Motivation & Problem Formulation

Regression predicts a continuous numerical target from observed covariates:

  • Concrete task: Estimate the sale price y \in \mathbb{R} of a house (150\text{ m}^2, built 20\text{ years} ago) from a training record of n historical sales \{(\mathbf{x}^{(i)}, y^{(i)})\}_{i=1}^n.
  • Features and labels: Each example i is described by a feature vector \mathbf{x}^{(i)} = (x_1^{(i)}, \ldots, x_d^{(i)})^\top \in \mathbb{R}^d and an observed scalar target y^{(i)} \in \mathbb{R}.
  • Core assumption: On average, the target varies as an affine combination of the features plus unmodeled measurement noise.

Fitting a plane to historical sales yields a closed-form pricing rule that generalizes immediately to any unseen house \mathbf{x}.

The Affine Model: Weights and Bias

The Model Class

\hat{y} = w_1 x_1 + \cdots + w_d x_d + b = \mathbf{w}^\top \mathbf{x} + b

  • Marginal slopes (\mathbf{w} \in \mathbb{R}^d): With w_{\textrm{area}} = 3{,}000\text{ \$/m}^2 and w_{\textrm{age}} = -1{,}000\text{ \$/yr}, each extra square meter adds \$3{,}000 while each year of age subtracts \$1{,}000.
  • Intercept / bias (b \in \mathbb{R}): With b = \$50{,}000, our 150\text{ m}^2, 20-year-old house is priced at \$480{,}000; keeping b frees the fitted hyperplane from the origin \mathbf{x} = \mathbf{0}.

Vectorizing Across a Dataset With the Design Matrix

Matrix Formulation

\hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b = \tilde{\mathbf{X}}\tilde{\mathbf{w}}

  • Shape alignment: Multiplying design matrix \mathbf{X} \in \mathbb{R}^{n \times d} by column vector \mathbf{w} \in \mathbb{R}^{d \times 1} yields \mathbf{X}\mathbf{w} of shape (n, 1), and broadcasting adds b across all n rows.
  • Absorbing the bias: Appending a ones column \tilde{\mathbf{X}} = [\mathbf{X}, \mathbf{1}] \in \mathbb{R}^{n \times (d+1)} reduces the affine map to a single matrix product \tilde{\mathbf{X}}\tilde{\mathbf{w}}.

The Squared Error Loss Function

Measuring Misfit

We quantify how closely predictions \hat{y}^{(i)} match observed targets y^{(i)} by averaging half the squared vertical residuals across the training set:

L(\mathbf{w}, b) = \frac{1}{2n} \sum_{i=1}^{n} \bigl(\hat{y}^{(i)} - y^{(i)}\bigr)^2

  • Residual (r^{(i)} = \hat{y}^{(i)} - y^{(i)}): The signed vertical gap between the predicted point on the line and the observed data point.
  • Why the factor of 1/2: Purely algebraic convenience—it cancels the factor of 2 that drops down upon differentiation, leaving \operatorname{argmin}_{\mathbf{w}, b} L(\mathbf{w}, b) unchanged.
  • Why divide by n: Normalizing by sample size keeps the numerical magnitude of the loss and its gradients invariant when dataset size changes.

Pitfall: Squared Loss Sensitivity to Outliers

Statistical Failure Mode

x = np.arange(1.0, 21.0)
y = 2 * x
y[5] = 10000                            # corrupt a single label
w_sq = (x * y).sum() / (x * x).sum()    # squared-loss minimizer
w_grid = np.linspace(0, 30, 3001)       # slopes 0, 0.01, ..., 30
mae = np.abs(w_grid[:, None] * x - y).mean(axis=1)
w_mae = w_grid[mae.argmin()]            # MAE minimizer on the grid
print(f'true w: 2.00, squared loss: {w_sq:.2f}, MAE: {w_mae:.2f}')
true w: 2.00, squared loss: 22.88, MAE: 2.00
  • Quadratic pull vs. unit vote: Corrupting a single label to 10{,}000 yanks the least-squares slope from 2.00 to 22.88, whereas mean absolute error (\frac{1}{n}\sum_i |\hat{y}^{(i)} - y^{(i)}|) bounds each outlier’s subgradient to \pm 1 and preserves w = 2.00.

Closed-Form Solution: The Normal Equations

Analytic Optimization

In augmented notation \tilde{\mathbf{X}} = [\mathbf{X}, \mathbf{1}] \in \mathbb{R}^{n \times (d+1)}, the empirical loss is a convex quadratic bowl L(\tilde{\mathbf{w}}) = \frac{1}{2n}\|\tilde{\mathbf{X}}\tilde{\mathbf{w}} - \mathbf{y}\|_2^2:

\nabla_{\tilde{\mathbf{w}}} L(\tilde{\mathbf{w}}) = \frac{1}{n}\tilde{\mathbf{X}}^\top\bigl(\tilde{\mathbf{X}}\tilde{\mathbf{w}} - \mathbf{y}\bigr) = \mathbf{0} \quad\Longleftrightarrow\quad \tilde{\mathbf{X}}^\top \tilde{\mathbf{X}}\, \hat{\tilde{\mathbf{w}}} = \tilde{\mathbf{X}}^\top \mathbf{y}

  • Pythagorean decomposition: For any candidate \tilde{\mathbf{w}}, expanding \|\mathbf{y} - \tilde{\mathbf{X}}\tilde{\mathbf{w}}\|_2^2 around a solution \hat{\tilde{\mathbf{w}}} yields \|\mathbf{y} - \tilde{\mathbf{X}}\hat{\tilde{\mathbf{w}}}\|_2^2 + \|\tilde{\mathbf{X}}(\hat{\tilde{\mathbf{w}}} - \tilde{\mathbf{w}})\|_2^2 because the cross term (\mathbf{y} - \tilde{\mathbf{X}}\hat{\tilde{\mathbf{w}}})^\top\tilde{\mathbf{X}} vanishes identically.
  • Uniqueness condition: When the d + 1 columns of \tilde{\mathbf{X}} are linearly independent (requiring n \geq d + 1), the Gram matrix \tilde{\mathbf{X}}^\top\tilde{\mathbf{X}} is strictly positive definite and \hat{\tilde{\mathbf{w}}} = (\tilde{\mathbf{X}}^\top\tilde{\mathbf{X}})^{-1}\tilde{\mathbf{X}}^\top\mathbf{y} is unique.
  • Collinearity (d > n or duplicate features): When \tilde{\mathbf{X}}^\top\tilde{\mathbf{X}} is singular, infinitely many weight vectors achieve the exact same minimum loss; lstsq returns the minimum-norm solution \tilde{\mathbf{X}}^\dagger \mathbf{y} via QR or SVD.

Worked Example & Numerical Pitfall of Matrix Inversion

Normal Equations in Code

X = torch.tensor([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])  # rows (1, input)
y = torch.tensor([[1.0], [1.0], [0.0]])
w_hat = torch.linalg.lstsq(X, y).solution
r = X @ w_hat - y                                       # errors
print('w_hat:', tuple(round(float(v), 4) for v in w_hat[:, 0]))
print('r:', tuple(round(float(v), 4) for v in r[:, 0]))
print(f'max |X^T r|: {float((X.T @ r).abs().max()):.0e}')
w_hat: (1.1667, -0.5)
r: (0.1667, -0.3333, 0.1667)
max |X^T r|: 2e-07
  • Why never form inv(X.T @ X): Multiplying \mathbf{X}^\top\mathbf{X} squares the condition number \kappa(\mathbf{X}^\top\mathbf{X}) = \kappa(\mathbf{X})^2; dedicated solvers (lstsq) factorize \mathbf{X} directly via QR or SVD in O(nd^2) flops.

Geometric View: Least Squares as Orthogonal Projection

Why They Are Called the “Normal” Equations

In observation space \mathbb{R}^n, varying \tilde{\mathbf{w}} \in \mathbb{R}^{d+1} sweeps out a (d+1)-dimensional flat subspace—the column space \operatorname{col}(\tilde{\mathbf{X}}):

  • Closest point in a subspace: The noisy \mathbf{y} \in \mathbb{R}^n almost never lies in \operatorname{col}(\tilde{\mathbf{X}}); minimizing \|\mathbf{y} - \tilde{\mathbf{X}}\tilde{\mathbf{w}}\|_2^2 finds the closest point \hat{\mathbf{y}} = \tilde{\mathbf{X}}\hat{\tilde{\mathbf{w}}}.
  • Orthogonality of the residual: The shortest segment from \mathbf{y} to the subspace is perpendicular (normal) to it, so \mathbf{r} = \hat{\mathbf{y}} - \mathbf{y} satisfies: \tilde{\mathbf{X}}^\top \mathbf{r} = \mathbf{0}
  • Zero-sum residuals: Because the bias column \mathbf{1} lies in \operatorname{col}(\tilde{\mathbf{X}}), \mathbf{1}^\top\mathbf{r} = \sum_{i=1}^n r^{(i)} = 0 holds for every least-squares fit with an intercept.

Why Deep Learning Uses Minibatch SGD Instead

From Closed Form to Iterative Optimization

  • Cubic parameter scaling (O(nd^2 + d^3)): At d = 10^8 parameters, storing a d \times d Gram matrix would require 40\text{ petabytes} of RAM.
  • Dataset redundancy (n \gg |\mathcal{B}|): Full-batch GD reads all n = 10^7 examples before moving once, whereas |\mathcal{B}| = 64 random examples already point in nearly the same descent direction.
  • Non-analytic deep models: Cross-entropy and nonlinear hidden layers admit no closed-form normal equations.

Minibatch Stochastic Gradient Descent Mechanics

The Workhorse Update Rule

\mathbf{w} \leftarrow \mathbf{w} - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}_t} \mathbf{x}^{(i)} \bigl(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\bigr)

  • Error-driven correction: Each example i \in \mathcal{B}_t pulls \mathbf{w} along -\mathbf{x}^{(i)} in proportion to its residual r^{(i)} = \hat{y}^{(i)} - y^{(i)}.
  • Unbiased estimator: Uniform sampling gives \mathbb{E}[\nabla L_{\mathcal{B}_t}] = \nabla L with standard error \propto 1/\sqrt{|\mathcal{B}|}; (\mathbf{w}, b) are learned parameters while (\eta, |\mathcal{B}|) are hyperparameters.

Gradient Noise Ball and Learning-Rate Scaling

Stochastic Dynamics

Even at the exact empirical minimizer \hat{\mathbf{w}} where the full-batch gradient \nabla L(\hat{\mathbf{w}}) = \mathbf{0}, individual noisy examples have nonzero residuals r^{(i)} \neq 0:

  • Full-batch GD (black): Computes the exact gradient over all n examples per step, marching smoothly across elliptical contours into \hat{\mathbf{w}}.
  • Minibatch SGD (color): Descends rapidly in n / |\mathcal{B}| cheap steps per epoch, then fluctuates perpetually inside a terminal noise ball around \hat{\mathbf{w}}: \mathbb{E}\bigl[\|\mathbf{w}_t - \hat{\mathbf{w}}\|_2^2\bigr] \propto \frac{\eta\,\sigma^2}{|\mathcal{B}|}
  • Controlling the radius: Quartering \eta (right panel) or quadrupling |\mathcal{B}| halves the noise ball radius; decaying \eta_t \to 0 converges to \hat{\mathbf{w}}.

Vectorization: Python Loops vs. Matrix Kernels

Systems Performance

loop = seconds(lambda: [X[i:i + 1] @ w + b for i in range(n)])
vectorized = seconds(lambda: X @ w + b)
print(f'one example at a time: {loop * 1e3:8.3f} ms')
print(f'all examples at once:  {vectorized * 1e3:8.3f} ms')
print(f'speedup: {loop / vectorized:.0f}x')
one example at a time:   11.358 ms
all examples at once:     0.024 ms
speedup: 482x
  • Eliminating dispatch overhead: Looping in Python pays interpreter and kernel-launch latency 1,000 times, whereas X @ w + b launches one compiled BLAS/GPU kernel (remember to synchronize asynchronous GPU streams when timing).

Probabilistic Foundation: The Gaussian Noise Model

Why Squared Error?

In 1809, Gauss asked what probability distribution of measurement errors \epsilon makes least squares the most probable parameter estimate:

  • Additive Gaussian noise (y = \mathbf{w}^\top \mathbf{x} + b + \epsilon with \epsilon \sim \mathcal{N}(0, \sigma^2)): p(y \mid \mathbf{x}; \mathbf{w}, b) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\Bigl(-\frac{(y - \mathbf{w}^\top \mathbf{x} - b)^2}{2\sigma^2}\Bigr)

  • Homoscedastic normal scatter: Every conditional density p(y \mid \mathbf{x}) is a Gaussian bell curve centered on the regression line \mathbf{w}^\top\mathbf{x} + b with constant standard deviation \sigma.

  • Light quadratic tails: Because (y - \hat{y})^2 sits inside \exp(-\cdot / 2\sigma^2), a 5\sigma residual has density e^{-12.5} \approx 4 \times 10^{-6} of the peak.

Gaussian Maximum Likelihood Yields Least Squares

Statistical Derivation

For n independent observations \{(\mathbf{x}^{(i)}, y^{(i)})\}_{i=1}^n, the conditional dataset likelihood factors into \prod_{i=1}^n p(y^{(i)} \mid \mathbf{x}^{(i)}; \mathbf{w}, b). Maximizing likelihood is equivalent to minimizing the negative log-likelihood (NLL):

-\log p(\mathbf{y} \mid \mathbf{X}; \mathbf{w}, b) = \frac{n}{2}\log(2\pi\sigma^2) + \frac{1}{2\sigma^2}\sum_{i=1}^n \bigl(y^{(i)} - \mathbf{w}^\top \mathbf{x}^{(i)} - b\bigr)^2

  • Invariance to \sigma^2: The first term \frac{n}{2}\log(2\pi\sigma^2) is a constant independent of (\mathbf{w}, b).
  • Exact equivalence: The second term is \frac{n}{\sigma^2} L(\mathbf{w}, b), our empirical squared error loss scaled by the positive constant n / \sigma^2.

The MLE Loss Recipe: Minimizing the squared error loss produces the exact maximum-likelihood estimator (\hat{\mathbf{w}}_{\textrm{MLE}}, \hat{b}_{\textrm{MLE}}) under additive homoscedastic Gaussian noise, regardless of the noise variance \sigma^2.

Designing Losses From Alternative Noise Distributions

Beyond Gaussian Noise

Replacing the Gaussian noise density p(\epsilon) \propto \exp(-l(\epsilon)) systematically derives robust and domain-specific regression losses via -\log p(y \mid \mathbf{x}):

  • Laplace noise \to \ell_1 Absolute Error: Heavy exponential tails p(\epsilon) = \frac{1}{2\tau}e^{-|\epsilon|/\tau} yield l(\hat{y}, y) = |\hat{y} - y|, whose subgradient \operatorname{sign}(\hat{y} - y) \in \{\pm 1\} bounds the pull of any outlier.
  • Huber loss (smooth + robust): Splices a quadratic bowl \frac{1}{2}r^2 for small residuals (|r| \leq \delta) onto linear slopes \delta(|r| - \delta/2) for large residuals (|r| > \delta).
  • Poisson counts (y \in \{0, 1, \ldots\}): Modeling rate \log \nu(\mathbf{x}) = \mathbf{w}^\top\mathbf{x} + b yields convex NLL l = \nu(\mathbf{x}) - y\log\nu(\mathbf{x}).

Linear Regression as a Single-Layer Neural Network

Bridge to Deep Learning

In the language of neural networks, linear regression is a single artificial neuron—a fully connected (dense) layer with d inputs and 1 linear output unit:

  • Input layer (x_1, \ldots, x_d): Holds the d raw feature coordinates (not counted in layer depth because it holds no tunable parameters).
  • Synaptic weights and output (o_1): Every input node x_j connects to the output node o_1 with weight w_j, computing o_1 = \sum_{j=1}^d w_j x_j + b.
  • Why stack layers later: Composing multiple affine layers without nonlinearities collapses into a single affine map; inserting elementwise activations in the MLP chapter unlocks universal approximation.

Concept Check: Orthogonality, Noise Balls & Likelihood

Check Your Understanding

Work out these three questions from first principles before revealing the solutions:

  1. Zero-sum residuals: Why do the residuals r^{(i)} = \hat{y}^{(i)} - y^{(i)} of every least-squares fit with a bias b satisfy \sum_{i=1}^n r^{(i)} = 0?
  2. Batch size vs. noise ball: If you increase the minibatch size from |\mathcal{B}| = 32 to |\mathcal{B}| = 128 at a fixed learning rate \eta, how does the steady-state squared distance \mathbb{E}[\|\mathbf{w}_t - \hat{\mathbf{w}}\|_2^2] change, and what learning rate restores the original noise ball?
  3. Outlier likelihood ratio: Under unit-scale noise, how much less likely is a residual of \epsilon = 10 than \epsilon = 1 under \mathcal{N}(0, 1) versus Laplace p(\epsilon) = \frac{1}{2}e^{-|\epsilon|}?

Answers:

  1. The augmented design matrix \tilde{\mathbf{X}} = [\mathbf{X}, \mathbf{1}] contains the all-ones column \mathbf{1}, so the normal equations \tilde{\mathbf{X}}^\top\mathbf{r} = \mathbf{0} enforce \mathbf{1}^\top\mathbf{r} = \sum_{i=1}^n r^{(i)} = 0.
  2. Because \mathbb{E}[\|\mathbf{w}_t - \hat{\mathbf{w}}\|_2^2] \propto \eta / |\mathcal{B}|, quadrupling |\mathcal{B}| cuts the squared distance by 4\times (halving the ball’s radius); scaling the learning rate linearly to 4\eta restores the original ratio \eta / |\mathcal{B}|.
  3. Gaussian ratio: e^{-(10^2 - 1^2)/2} = e^{-49.5} \approx 3 \times 10^{-22} (virtually impossible, forcing the line to tilt). Laplace ratio: e^{-(10 - 1)} = e^{-9} \approx 1.2 \times 10^{-4} (rare but plausible, so the slope ignores the outlier).

Summary & Key Takeaways

Summary

Concept Mathematical Form Computational Cost / Scaling Role & Practical Takeaway
Affine Model \hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b = \tilde{\mathbf{X}}\tilde{\mathbf{w}} O(nd) flops per full dataset pass Single fully connected layer; bias b frees the hyperplane from the origin
Squared Error Loss L(\mathbf{w}, b) = \frac{1}{2n}\|\mathbf{X}\mathbf{w} + b - \mathbf{y}\|_2^2 O(n) reduction over residuals Exact MLE under \mathcal{N}(0, \sigma^2) noise; sensitive to heavy-tailed outliers
Normal Equations \tilde{\mathbf{X}}^\top\tilde{\mathbf{X}}\hat{\tilde{\mathbf{w}}} = \tilde{\mathbf{X}}^\top\mathbf{y} O(nd^2 + d^3) via QR/SVD (lstsq) Orthogonal projection of \mathbf{y} onto \operatorname{col}(\tilde{\mathbf{X}}); infeasible for large d
Minibatch SGD \tilde{\mathbf{w}} \leftarrow \tilde{\mathbf{w}} - \frac{\eta}{|\mathcal{B}|}\tilde{\mathbf{X}}_{\mathcal{B}}^\top(\tilde{\mathbf{X}}_{\mathcal{B}}\tilde{\mathbf{w}} - \mathbf{y}_{\mathcal{B}}) O(|\mathcal{B}|d) flops per step, independent of n Unbiased gradient with variance \propto 1/|\mathcal{B}|; settles in noise ball \propto \eta/|\mathcal{B}|
Robust Alternatives \ell_1: \|\hat{\mathbf{y}} - \mathbf{y}\|_1 / n; Huber l_\delta O(|\mathcal{B}|d) per subgradient step Derived from Laplace MLE; bounds each outlier’s gradient contribution to \pm 1