2.1 Linear Regression

Suppose you want to estimate the sale price of a house from its floor area and age. Unlike classification, which assigns an input to a discrete category, regression predicts a continuous numerical quantity. Finding a rule that maps quantitative inputs to a numerical output has a distinguished two-century pedigree. In 1805, Adrien-Marie Legendre published the method of least squares to determine comet orbits from noisy astronomical sightings (Legendre, 1805); four years later, Carl Friedrich Gauss grounded least squares in probability theory by asking what distribution of measurement errors makes the least-squares fit the most probable one, arriving at the Gaussian distribution (Gauss, 1809) (having already used the method in 1801 to relocate the newly discovered dwarf planet Ceres after it vanished behind the sun's glare).

Today, regression powers everything from clinical risk scoring and demand forecasting to the bounding-box heads of object detectors. Better still, linear regression, where the prediction is an affine combination of the inputs, introduces nearly every core concept of deep learning in a setting simple enough to analyze completely by hand. Viewed as a computational graph, linear regression is a single artificial neuron: a fully connected layer with one output unit. In this section, we formulate the model and the squared loss, solve it both analytically via the normal equations and iteratively via minibatch stochastic gradient descent (the workhorse optimizer of deep learning), benchmark vectorized array operations against Python loops, and connect the loss function to maximum-likelihood estimation under different noise distributions.

import time
import numpy as np
import torch

2.1.1 The Model and the Loss#

2.1.1.1 Features and Labels#

To estimate a house's sale price from its area (in square meters) and age (in years), we collect a training dataset of historical sales. Each house in that record is an example (or data point, sample, or instance). The quantity we aim to predict, here the price, is the label (or target), while the measurable attributes on which we base the prediction (area and age) are the features (or covariates).

Suppose our dataset contains nn examples. We index them by i∈{1,…,n}i \in \{1, \ldots, n\}, writing x(i)=(x1(i),x2(i))⊤∈R2\mathbf{x}^{(i)} = (x_1^{(i)}, x_2^{(i)})^\top \in \mathbb{R}^2 for the feature vector of the ithi^{\textrm{th}} house and y(i)∈Ry^{(i)} \in \mathbb{R} for its observed sale price. More generally, when each example is described by dd features, x(i)∈Rd\mathbf{x}^{(i)} \in \mathbb{R}^d, and the full dataset is the collection of pairs {(x(1),y(1)),…,(x(n),y(n))}\{(\mathbf{x}^{(1)}, y^{(1)}), \ldots, (\mathbf{x}^{(n)}, y^{(n)})\}.

2.1.1.2 The Linear Model#

Every supervised learning method starts with a model class: a parameterized family of functions mapping features to predictions. The linear assumption posits that the target can be approximated by a weighted sum of the features plus an offset:

price=warea⋅area+wage⋅age+b.(2.1.1)\textrm{price} = w_{\textrm{area}} \cdot \textrm{area} + w_{\textrm{age}} \cdot \textrm{age} + b. \tag{2.1.1}

Here wareaw_{\textrm{area}} and wagew_{\textrm{age}} are the weights, and bb is the bias (also called the offset or intercept). Each weight sets the marginal influence of its feature—how much the predicted price changes per extra square meter of floor space, holding age fixed—while the bias bb anchors the prediction when all features are zero. Even if no real house has zero area, keeping bb is essential: without it, the fitted plane is forced to pass through the origin, severely restricting the functions our model can express. Strictly speaking, (2.1.1) is an affine function of the features (a linear map plus a constant translation), though machine learning universally refers to it as a linear model.

With dd features, the model's prediction y^\hat{y} (where the hat distinguishes an estimate from the observed label yy) takes the form

y^=w1x1+⋯+wdxd+b=w⊤x+b,(2.1.2)\hat{y} = w_1 x_1 + \cdots + w_d x_d + b = \mathbf{w}^\top \mathbf{x} + b, \tag{2.1.2}

where w=(w1,…,wd)⊤∈Rd\mathbf{w} = (w_1, \ldots, w_d)^\top \in \mathbb{R}^d collects the weights into a single column vector. Whenever we evaluate the model across all nn examples at once, we stack the feature vectors x(i)\mathbf{x}^{(i)} as the rows of the design matrix X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} and the predictions y^(i)\hat{y}^{(i)} into the column vector y^∈Rn\hat{\mathbf{y}} \in \mathbb{R}^n:

y^=Xw+b,(2.1.3)\hat{\mathbf{y}} = \mathbf{X} \mathbf{w} + b, \tag{2.1.3}

where the scalar bias bb is added to every component of Xw\mathbf{X}\mathbf{w} via broadcasting (Section 1.1.3.2). Figure 2.1.1 shows the shapes involved. Searching for the best linear predictor now reduces to finding the parameters (w,b)∈Rd×R(\mathbf{w}, b) \in \mathbb{R}^d \times \mathbb{R} that make y^\hat{\mathbf{y}} match the observed labels y=(y(1),…,y(n))⊤\mathbf{y} = (y^{(1)}, \ldots, y^{(n)})^\top as closely as possible. Even when the true relationship between features and labels is only approximately linear and is contaminated by unmeasured factors and measurement noise, a linear model frequently provides a fast, interpretable, and surprisingly competitive baseline.

Figure 2.1.1:

The shapes in y^=Xw+b\hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b, drawn for n=6n = 6 examples and d=3d = 3 features. Each row of X\mathbf{X} is one example and produces one entry of y^\hat{\mathbf{y}} (shaded); w\mathbf{w} holds one weight per column, and the scalar bb is broadcast to all nn entries.

2.1.1.3 The Squared Loss#

Before we can search for the best parameters, we need a quantitative measure of how badly any candidate (w,b)(\mathbf{w}, b) misses the observed labels. A loss function assigns a nonnegative penalty to the gap between prediction y^\hat{y} and truth yy, vanishing when the two agree. For regression, the standard choice is the squared error:

l(i)(w,b)=12(y^(i)−y(i))2.(2.1.4)l^{(i)}(\mathbf{w}, b) = \frac{1}{2} \left(\hat{y}^{(i)} - y^{(i)}\right)^2. \tag{2.1.4}

The factor of 12\frac{1}{2} is purely a cosmetic convenience: it cancels the factor of 22 that drops down when we differentiate the square, leaving the location of the minimum unchanged. Because the difference y^(i)−y(i)\hat{y}^{(i)} - y^{(i)} is squared, overestimates and underestimates of equal magnitude are penalized symmetrically, while large misses are penalized much more heavily than small ones: a prediction off by 33 incurs nine times the loss of a prediction off by 11. Geometrically (Figure 2.1.2), each residual y^(i)−y(i)\hat{y}^{(i)} - y^{(i)} is the vertical distance between the data point and the regression line, and 2 l(i)2\,l^{(i)} is the area of the square built on that vertical segment.

Figure 2.1.2:

Fitting a line to data by minimizing the sum of squared vertical residuals.

To score (w,b)(\mathbf{w}, b) across the entire training set of nn examples, we average the per-example losses to form the empirical loss (or cost / objective):

L(w,b)=1n∑i=1nl(i)(w,b)=1n∑i=1n12(w⊤x(i)+b−y(i))2=12n∥Xw+b−y∥22.\begin{aligned} L(\mathbf{w}, b) &= \frac{1}{n} \sum_{i=1}^n l^{(i)}(\mathbf{w}, b) = \frac{1}{n} \sum_{i=1}^n \frac{1}{2}\left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right)^2 \\ &= \frac{1}{2n} \|\mathbf{X}\mathbf{w} + b - \mathbf{y}\|_2^2. \end{aligned}

Dividing by nn puts the objective on a per-example scale, so that doubling the dataset size does not double the numerical magnitude of the loss or its gradients. Training the model means solving the optimization problem

w∗,b∗=argmin⁡w, b L(w,b).(2.1.5)\mathbf{w}^*, b^* = \operatorname*{argmin}_{\mathbf{w},\, b}\ L(\mathbf{w}, b). \tag{2.1.5}

Because errors are squared, a prediction off by 1010 incurs a hundred times the penalty of a prediction off by 11, so a single corrupted label can dominate the fit. To see how severely, let us place twenty points on the line y=2xy = 2x, corrupt a single label to y(6)=10,000y^{(6)} = 10{,}000 (as a data-entry typo might), and fit a line through the origin y^=wx\hat{y} = wx in two ways: first by the closed-form squared-loss minimizer w=∑ix(i)y(i)/∑i(x(i))2w = \sum_i x^{(i)} y^{(i)} / \sum_i (x^{(i)})^2, and second by minimizing the mean absolute error 1n∑i∣wx(i)−y(i)∣\frac{1}{n}\sum_i |w x^{(i)} - y^{(i)}| over a fine grid of candidate slopes:

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

A single corrupted point out of twenty yanks the squared-loss slope from 2.002.00 all the way to 22.8822.88, while the absolute-error slope does not budge from 2.002.00. Under squared loss, one error of nearly 10,00010{,}000 overwhelms the combined pull of all nineteen clean points; under absolute error, its pull grows only linearly, so the nineteen clean points easily outvote it. Which behavior is desirable depends on what kind of noise we expect in our labels, a question we answer from first principles in Section 2.1.3.

2.1.2 Minimizing the Loss#

How do we find (w∗,b∗)(\mathbf{w}^*, b^*) when there are dd features and nn examples? Linear regression is one of the very few models in machine learning that admits both an exact closed-form formula and a scalable iterative optimizer. Comparing the two reveals why deep learning overwhelmingly favors iterative gradient methods.

2.1.2.1 The Normal Equations#

First, we can absorb the scalar bias bb into the weight vector by appending a constant column of 11s to the design matrix: each input becomes (x(i),1)⊤∈Rd+1(\mathbf{x}^{(i)}, 1)^\top \in \mathbb{R}^{d+1} and the parameter vector becomes (w,b)⊤∈Rd+1(\mathbf{w}, b)^\top \in \mathbb{R}^{d+1} (or equivalently, we can center both X\mathbf{X} and y\mathbf{y} by their sample means; see Exercise 1). Writing X\mathbf{X} and w\mathbf{w} in this augmented notation, the loss is simply

L(w)=12n∥y−Xw∥22.(2.1.6)L(\mathbf{w}) = \frac{1}{2n} \|\mathbf{y} - \mathbf{X}\mathbf{w}\|_2^2. \tag{2.1.6}

We can find its global minimum by pure algebra, completing the square without taking a derivative, whenever X⊤X\mathbf{X}^\top\mathbf{X} is invertible (which holds if and only if the columns of X\mathbf{X} are linearly independent, requiring n≥dn \geq d). Define w^=(X⊤X)−1X⊤y\hat{\mathbf{w}} = (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}, so that X⊤Xw^=X⊤y\mathbf{X}^\top\mathbf{X}\hat{\mathbf{w}} = \mathbf{X}^\top\mathbf{y}. Adding and subtracting Xw^\mathbf{X}\hat{\mathbf{w}} inside the norm and expanding the square yields

∥y−Xw∥22=∥(y−Xw^)+X(w^−w)∥22=∥y−Xw^∥22+∥X(w^−w)∥22+2(y−Xw^)⊤X(w^−w).(2.1.7)\begin{aligned} \|\mathbf{y} - \mathbf{X}\mathbf{w}\|_2^2 &= \|(\mathbf{y} - \mathbf{X}\hat{\mathbf{w}}) + \mathbf{X}(\hat{\mathbf{w}} - \mathbf{w})\|_2^2 \\ &= \|\mathbf{y} - \mathbf{X}\hat{\mathbf{w}}\|_2^2 + \|\mathbf{X}(\hat{\mathbf{w}} - \mathbf{w})\|_2^2 + 2(\mathbf{y} - \mathbf{X}\hat{\mathbf{w}})^\top\mathbf{X}(\hat{\mathbf{w}} - \mathbf{w}). \end{aligned} \tag{2.1.7}

Look at the cross term at the end:

(y−Xw^)⊤X=(X⊤y−X⊤Xw^)⊤=0⊤.(\mathbf{y} - \mathbf{X}\hat{\mathbf{w}})^\top\mathbf{X} = (\mathbf{X}^\top\mathbf{y} - \mathbf{X}^\top\mathbf{X}\hat{\mathbf{w}})^\top = \mathbf{0}^\top.

It vanishes identically for every w\mathbf{w}. What remains is a sum of two nonnegative squared norms. The first term, ∥y−Xw^∥22\|\mathbf{y} - \mathbf{X}\hat{\mathbf{w}}\|_2^2, does not depend on w\mathbf{w} at all; the second term, ∥X(w^−w)∥22\|\mathbf{X}(\hat{\mathbf{w}} - \mathbf{w})\|_2^2, is zero if and only if w=w^\mathbf{w} = \hat{\mathbf{w}} (since X\mathbf{X} has full column rank). Thus w^\hat{\mathbf{w}} is the unique global minimizer. We could reach the same equation via calculus by setting the gradient ∇wL(w)=−1nX⊤(y−Xw)\nabla_{\mathbf{w}} L(\mathbf{w}) = -\frac{1}{n}\mathbf{X}^\top(\mathbf{y} - \mathbf{X}\mathbf{w}) to zero, producing the classic normal equations:

X⊤X w∗=X⊤y,orw∗=(X⊤X)−1X⊤y.(2.1.8)\mathbf{X}^\top \mathbf{X}\, \mathbf{w}^* = \mathbf{X}^\top \mathbf{y}, \qquad \textrm{or} \qquad \mathbf{w}^* = (\mathbf{X}^\top \mathbf{X})^{-1}\mathbf{X}^\top \mathbf{y}. \tag{2.1.8}

When the columns of X\mathbf{X} are linearly dependent (for instance, when two features are redundant or when d>nd > n), X⊤X\mathbf{X}^\top\mathbf{X} is singular: a least-squares minimizer still exists, but infinitely many weight vectors achieve the same minimum loss (Exercise 6).

In code, you should almost never form (X⊤X)−1(\mathbf{X}^\top\mathbf{X})^{-1} explicitly; dedicated least-squares solvers (lstsq) use QR or SVD factorizations that are far more numerically stable at a similar cost. Let us verify the normal equations on the three-point line model from Section 1.4 with inputs 0,1,20, 1, 2, labels 1,1,01, 1, 0, and augmented rows (1,input)(1, \textrm{input}), so that w^=(w1,w2)⊤=(7/6,−1/2)⊤\hat{\mathbf{w}} = (w_1, w_2)^\top = (7/6, -1/2)^\top holds the intercept first and the slope second. We also check that the residual vector r=Xw^−y=(1/6,−1/3,1/6)⊤\mathbf{r} = \mathbf{X}\hat{\mathbf{w}} - \mathbf{y} = (1/6, -1/3, 1/6)^\top satisfies X⊤r=0\mathbf{X}^\top\mathbf{r} = \mathbf{0} up to float32 precision:

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

2.1.2.2 Least Squares as Projection#

Why are these called the normal equations? The identity (2.1.7) with the vanishing cross term is literally the Pythagorean theorem in Rn\mathbb{R}^n (Figure 2.1.3). As w\mathbf{w} ranges over Rd\mathbb{R}^d, the possible prediction vectors y^=Xw\hat{\mathbf{y}} = \mathbf{X}\mathbf{w} sweep out a dd-dimensional subspace of Rn\mathbb{R}^n: the column space (or span) of X\mathbf{X}. Usually the observed label vector y∈Rn\mathbf{y} \in \mathbb{R}^n does not lie in that subspace, because no linear combination of the dd feature columns reproduces all nn noisy observations.

Figure 2.1.3:

Least squares as orthogonal projection in Rn\mathbb{R}^n. The column space of X\mathbf{X} contains every prediction vector Xw\mathbf{X}\mathbf{w}; the closest point to y\mathbf{y} is the orthogonal projection y^=Xw^\hat{\mathbf{y}} = \mathbf{X}\hat{\mathbf{w}}, whose residual y−y^\mathbf{y} - \hat{\mathbf{y}} is perpendicular (normal) to every column of X\mathbf{X}.

Minimizing ∥y−Xw∥22\|\mathbf{y} - \mathbf{X}\mathbf{w}\|_2^2 means finding the point y^=Xw^\hat{\mathbf{y}} = \mathbf{X}\hat{\mathbf{w}} in the column space of X\mathbf{X} that lies closest to y\mathbf{y} in Euclidean distance. By elementary geometry, the closest point in a flat subspace is the orthogonal projection of y\mathbf{y} onto that subspace: the unique point whose difference vector y−Xw^\mathbf{y} - \mathbf{X}\hat{\mathbf{w}} is perpendicular (normal) to every column of X\mathbf{X}. Requiring y−Xw^\mathbf{y} - \mathbf{X}\hat{\mathbf{w}} to be orthogonal to all columns of X\mathbf{X} is written X⊤(y−Xw^)=0\mathbf{X}^\top(\mathbf{y} - \mathbf{X}\hat{\mathbf{w}}) = \mathbf{0}, which is none other than the normal equations.

2.1.2.3 Minibatch Stochastic Gradient Descent#

If linear regression has a one-line analytic solution, why not stop here? Two obstacles rule out closed-form solutions across modern deep learning:

  1. Computational scaling: Forming X⊤X∈Rd×d\mathbf{X}^\top\mathbf{X} \in \mathbb{R}^{d \times d} costs O(nd2)O(nd^2) operations and solving the d×dd \times d system costs O(d3)O(d^3). When a dataset has millions of examples and a model has millions or billions of parameters, storing or inverting a d×dd \times d matrix is completely out of the question.
  2. Nonlinearity: As soon as we replace the squared loss with another objective (like cross-entropy in Chapter 3) or stack nonlinear hidden layers (Chapter 4), no closed-form solution exists at all.

Instead, we train almost every deep learning model iteratively using gradient descent and its stochastic variants. Recall from Section 1.4 that the gradient ∇L(w,b)\nabla L(\mathbf{w}, b) points in the direction of steepest ascent of the loss. Stepping in the opposite direction reduces the loss, yet evaluating the full gradient ∇L(w,b)=1n∑i=1n∇l(i)(w,b)\nabla L(\mathbf{w}, b) = \frac{1}{n}\sum_{i=1}^n \nabla l^{(i)}(\mathbf{w}, b) requires a pass over all nn training examples just to take a single parameter step. When n=107n = 10^7, full-batch gradient descent is glacially slow and statistically wasteful, because the average gradient over 100 randomly chosen examples is already a usable estimate of the average over 10 million. How accurate that estimate is depends on the size of the sample, not on the size of the dataset it was drawn from.

Minibatch stochastic gradient descent (minibatch SGD) exploits this statistical redundancy. At each step tt, we draw a small random minibatch Bt⊂{1,…,n}\mathcal{B}_t \subset \{1, \ldots, n\} of ∣B∣|\mathcal{B}| examples, average the loss gradients over Bt\mathcal{B}_t alone, and update the parameters with a positive learning rate (step size) η>0\eta > 0:

(w,b)←(w,b)−η∣B∣∑i∈Bt∂(w,b) l(i)(w,b).(2.1.9)(\mathbf{w}, b) \leftarrow (\mathbf{w}, b) - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}_t} \partial_{(\mathbf{w}, b)}\, l^{(i)}(\mathbf{w}, b). \tag{2.1.9}

Because Bt\mathcal{B}_t is sampled uniformly from the training set, the minibatch gradient is an unbiased estimator of the true full-batch gradient, with standard error decaying as 1/∣B∣1/\sqrt{|\mathcal{B}|}. For linear regression under the squared loss (2.1.4), differentiating l(i)=12(w⊤x(i)+b−y(i))2l^{(i)} = \frac{1}{2}(\mathbf{w}^\top\mathbf{x}^{(i)} + b - y^{(i)})^2 explicitly gives the update rule

w←w−η∣B∣∑i∈Btx(i)(w⊤x(i)+b−y(i)),b←b−η∣B∣∑i∈Bt(w⊤x(i)+b−y(i)).(2.1.10)\begin{aligned} \mathbf{w} &\leftarrow \mathbf{w} - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}_t} \mathbf{x}^{(i)} \left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right),\\ b &\leftarrow b - \frac{\eta}{|\mathcal{B}|} \sum_{i \in \mathcal{B}_t} \left(\mathbf{w}^\top \mathbf{x}^{(i)} + b - y^{(i)}\right). \end{aligned} \tag{2.1.10}

Look at what each term does: the scalar w⊤x(i)+b−y(i)\mathbf{w}^\top\mathbf{x}^{(i)} + b - y^{(i)} is the signed prediction error on example ii. If the model overpredicts (y^(i)>y(i)\hat{y}^{(i)} > y^{(i)}), the update subtracts a multiple of x(i)\mathbf{x}^{(i)} from w\mathbf{w} and nudges bb downward, pulling the next prediction closer to y(i)y^{(i)}. Notice also the conceptual distinction: w\mathbf{w} and bb are model parameters learned by optimization, whereas the minibatch size ∣B∣|\mathcal{B}| and learning rate η\eta are hyperparameters chosen before training starts (and tuned on held-out validation data, as we discuss in Section 2.6).

2.1.2.4 Gradient Noise and the Learning Rate#

How does the trajectory of minibatch SGD compare with full-batch gradient descent? Consider the contours of the empirical loss L(w)L(\mathbf{w}) around the least-squares solution w^\hat{\mathbf{w}} (Figure 2.1.4). Full-batch gradient descent computes the gradient of LL over all nn examples at every step, marching smoothly across the elliptic contours into the minimum w^\hat{\mathbf{w}} (provided η\eta is not so large that it overshoots and diverges).

Minibatch SGD follows a different path. Even at the global minimum w^\hat{\mathbf{w}}, where the average gradient across all nn examples is zero, individual noisy examples still have nonzero residuals y^(i)−y(i)≠0\hat{y}^{(i)} - y^{(i)} \neq 0. A random minibatch Bt\mathcal{B}_t almost never has its per-example gradients cancel out to zero. Consequently, at constant learning rate η\eta, minibatch SGD quickly descends into a small neighborhood of w^\hat{\mathbf{w}} and then fluctuates perpetually inside a noise ball around w^\hat{\mathbf{w}} whose squared radius scales as η/∣B∣\eta / |\mathcal{B}|.

Figure 2.1.4:

Full-batch gradient descent (black) marches smoothly along the gradient of LL to the minimum w^\hat{\mathbf{w}}, taking one pass over all nn examples per step. Minibatch SGD (color) takes n/∣B∣n/|\mathcal{B}| inexpensive steps per pass using noisy gradient estimates, descending rapidly to a small noise ball around w^\hat{\mathbf{w}}; quartering the learning rate (right) shrinks the ball.

Halving η\eta or doubling ∣B∣|\mathcal{B}| shrinks that terminal noise ball, and decaying η→0\eta \to 0 over the course of training lets the iterates settle onto w^\hat{\mathbf{w}} (Chapter 9). In practice, however, reaching the bottom of the training loss to ten decimal places is rarely desirable: our ultimate goal is low error on unseen data, and because w^\hat{\mathbf{w}} itself deviates from the true population parameters by statistical estimation error of order 1/n1/\sqrt{n}, a small optimization jitter inside that statistical uncertainty costs nothing in generalization.

2.1.2.5 Vectorization for Speed#

When implementing minibatch updates (2.1.10), you should never loop over the examples i∈Bti \in \mathcal{B}_t one by one in Python. Instead, we vectorize the computation, expressing the entire minibatch forward pass and gradient step as array and matrix operations dispatched to C++/CUDA libraries that run in parallel across SIMD vector units or GPU cores.

To see the difference firsthand, let us benchmark predicting the labels of n=1,000n = 1{,}000 examples with weights w=(2,−3.4)⊤\mathbf{w} = (2, -3.4)^\top and bias b=4.2b = 4.2: first one example at a time in a Python for loop, and then for all 1,0001{,}000 examples at once with a single matrix product X @ w + b:

n = 1000
X = torch.ones(n, 2)                # the values do not affect the timing
w = torch.tensor([[2.0], [-3.4]])
b = 4.2
# Wait until the device has finished (CUDA runs asynchronously)
wait = lambda x: torch.cuda.synchronize() if torch.cuda.is_available() else None

Our timing helper seconds runs a warm-up call first (to absorb one-time setup and JIT compilation costs) and calls wait before stopping the clock, since GPU and accelerator frameworks dispatch operations asynchronously and may return to Python while the hardware is still computing.

def seconds(f):
    """Time one call of f, after a warm-up call."""
    wait(f())
    start = time.perf_counter()
    wait(f())
    return time.perf_counter() - start
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

Even though both paths perform the same arithmetic, computing all 1,0001{,}000 predictions in a single vectorized call is hundreds of times faster. The loop pays Python interpreter overhead and kernel-launch latency on every single example, whereas the matrix multiplication pays that overhead once and hands the entire batch to a single compiled linear-algebra routine. Throughout this book, vectorizing over minibatches—turning nn inner products w⊤x(i)\mathbf{w}^\top\mathbf{x}^{(i)} into one matrix-vector product Xw\mathbf{X}\mathbf{w}—is the single most important habit for writing fast deep learning code.

2.1.3 Squared Loss and Gaussian Noise#

So far we motivated the squared error loss 12(y^−y)2\frac{1}{2}(\hat{y} - y)^2 by geometric convenience and clean derivatives. Now let us ask Gauss's deeper question: what probabilistic assumption about the data makes minimizing squared error the statistically optimal thing to do?

2.1.3.1 The Normal Distribution#

Recall the normal (or Gaussian) distribution with mean μ\mu and variance σ2\sigma^2 (standard deviation σ\sigma), whose probability density is

p(x)=12πσ2exp⁡(−12σ2(x−μ)2).p(x) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp\left(-\frac{1}{2 \sigma^2} (x - \mu)^2\right).

This density forms a symmetric bell-shaped curve centered at μ\mu, whose width is set by the standard deviation σ\sigma (about 68% of the probability lies within σ\sigma of the mean and about 95% within 2σ2\sigma). Because the squared deviation (x−μ)2(x - \mu)^2 appears inside the negative exponential, extreme deviations are vanishingly unlikely: a value 5σ5\sigma from the mean has density e−12.5≈4×10−6e^{-12.5} \approx 4 \times 10^{-6} times that at the peak. We write ϵ∼N(μ,σ2)\epsilon \sim \mathcal{N}(\mu, \sigma^2) to denote a normally distributed random variable. Because sums of many small independent disturbances converge toward a normal distribution (Section 24.3.2.3), the Gaussian is the natural default model for well-behaved measurement noise.

Formally, linear regression with additive Gaussian noise assumes that every observed label is the linear signal plus an independent normal noise term:

y=w⊤x+b+ϵ,ϵ∼N(0,σ2).(2.1.11)y = \mathbf{w}^\top \mathbf{x} + b + \epsilon, \quad \epsilon \sim \mathcal{N}(0, \sigma^2). \tag{2.1.11}

Under this model, the conditional mean E[y∣x]\mathbb{E}[y \mid \mathbf{x}] is indeed w⊤x+b\mathbf{w}^\top \mathbf{x} + b (matching Section 2.1.1.2), and labels scatter symmetrically around the line with the same noise scale σ\sigma at every input x\mathbf{x} (Figure 2.1.5).

Figure 2.1.5:

The Gaussian noise model. For every input xx, the label yy is drawn from a normal density p(y∣x)p(y \mid x) centered on the line wx+bwx + b, with the same width everywhere.

2.1.3.2 Maximum Likelihood#

Under this additive Gaussian noise model, given features x\mathbf{x}, the conditional distribution of the observed label yy is normal with mean w⊤x+b\mathbf{w}^\top\mathbf{x} + b and variance σ2\sigma^2:

P(y∣x)=12πσ2exp⁡(−12σ2(y−w⊤x−b)2).(2.1.12)P(y \mid \mathbf{x}) = \frac{1}{\sqrt{2 \pi \sigma^2}} \exp\left(-\frac{1}{2 \sigma^2} (y - \mathbf{w}^\top \mathbf{x} - b)^2\right). \tag{2.1.12}

According to the principle of maximum likelihood, we should choose (w,b)(\mathbf{w}, b) to maximize the conditional probability density of observing the entire dataset {y(1),…,y(n)}\{y^{(1)}, \ldots, y^{(n)}\} given {x(1),…,x(n)}\{\mathbf{x}^{(1)}, \ldots, \mathbf{x}^{(n)}\}. Assuming the examples are drawn independently, the dataset likelihood factors into the product ∏i=1nP(y(i)∣x(i))\prod_{i=1}^n P(y^{(i)} \mid \mathbf{x}^{(i)}). Maximizing a positive product is equivalent to minimizing its negative logarithm, the negative log-likelihood:

−log⁡P(y∣X)=∑i=1n12log⁡(2πσ2)+12σ2∑i=1n(y(i)−w⊤x(i)−b)2.(2.1.13)-\log P(\mathbf{y} \mid \mathbf{X}) = \sum_{i=1}^n \frac{1}{2} \log(2 \pi \sigma^2) + \frac{1}{2 \sigma^2} \sum_{i=1}^n \left(y^{(i)} - \mathbf{w}^\top \mathbf{x}^{(i)} - b\right)^2. \tag{2.1.13}

Look closely at the two terms on the right. The first term, n2log⁡(2πσ2)\frac{n}{2}\log(2\pi\sigma^2), does not depend on w\mathbf{w} or bb at all. The second term is simply nσ2L(w,b)\frac{n}{\sigma^2} L(\mathbf{w}, b), our mean squared error loss scaled by the positive constant n/σ2n/\sigma^2. Therefore, minimizing the squared error loss produces the maximum-likelihood estimator of (w,b)(\mathbf{w}, b) under independent homoscedastic Gaussian noise, regardless of the value of σ2\sigma^2.

2.1.3.3 Choosing a Loss from a Noise Model#

What does the squared loss do when the noise is not Gaussian? The answer needs no likelihood at all. Fix an input x\mathbf{x} and ask which single number cc minimizes the expected squared error E[(y−c)2∣x]\mathbb{E}[(y - c)^2 \mid \mathbf{x}]. Setting the derivative 2(c−E[y∣x])2(c - \mathbb{E}[y \mid \mathbf{x}]) to zero gives the conditional mean c=E[y∣x]c = \mathbb{E}[y \mid \mathbf{x}], for any noise distribution with finite variance. The expected absolute error E[∣y−c∣∣x]\mathbb{E}[|y - c| \mid \mathbf{x}] is minimized by the conditional median instead. Tilt it, so that each unit of underestimation costs qq and each unit of overestimation costs 1−q1 - q, and the minimizer becomes the qq-quantile; forecasters, who need a 90% demand level more often than a mean, call this the pinball loss. The corrupted label in Section 2.1.1.3 showed this difference: a mean follows one enormous value, and a median ignores it. Choosing a loss therefore means choosing which statistic of yy the model predicts, whatever the noise turns out to be.

The maximum-likelihood connection adds a principled recipe for designing loss functions whenever Gaussian noise is not the right model of reality (Figure 2.1.6):

Output typeNoise modelLoss (negative log-likelihood)Statistic predicted
real-valued, well-behaved noiseGaussiansquared error (this section)mean of yy
real-valued, outliers or heavy tailsLaplaceabsolute error (exercise 2)median of yy
positive, multiplicative fluctuations (prices)Gaussian on log⁡y\log ysquared error on log⁡y\log y (exercise 3)mean of log⁡y\log y
counts (sales, arrivals)Poissonν(x)−ylog⁡ν(x)\nu(\mathbf{x}) - y \log \nu(\mathbf{x}) (exercise 4)mean of yy
  • Heavy-tailed outliers (Laplace noise →\rightarrow ℓ1\ell_1 loss): If occasional corrupted measurements produce wild outliers, the quadratic growth of (y^−y)2(\hat{y} - y)^2 lets a single bad data point yank the fitted line toward itself. Modeling the noise with heavier exponential tails via the Laplace distribution p(ϵ)=12τexp⁡(−∣ϵ∣/τ)p(\epsilon) = \frac{1}{2\tau}\exp(-|\epsilon|/\tau) turns the negative log-likelihood into the absolute error (ℓ1\ell_1) loss ∣y^−y∣|\hat{y} - y| (Exercise 2), whose gradient has constant magnitude ±1\pm 1 no matter how far an outlier sits.
  • Combining smooth optima with outlier robustness (Huber loss): Because ∣y^−y∣|\hat{y} - y| has a sharp corner at zero where its derivative jumps between −1-1 and +1+1, practitioners often use the Huber loss, which splices a quadratic bowl for small residuals (∣y^−y∣≤δ|\hat{y} - y| \leq \delta) onto linear slopes for large residuals (∣y^−y∣>δ|\hat{y} - y| > \delta).
  • Count data (Poisson noise): When the target y∈{0,1,2,…}y \in \{0, 1, 2, \ldots\} is a discrete count (such as daily customer arrivals), a Poisson likelihood leads to its own convex negative log-likelihood (Exercise 4).
Figure 2.1.6:

Three regression loss functions (right) and the noise densities p(ϵ)∝exp⁡(−l(ϵ))p(\epsilon) \propto \exp(-l(\epsilon)) that the first two correspond to under maximum likelihood (left): squared error (Gaussian) and absolute error (Laplace), with the Huber loss between them. The log-scale inset shows the heavier Laplace tails.

2.1.4 Linear Regression as a Neural Network#

To connect linear regression to the deep architectures of later chapters, we can draw it as a single-layer neural network (Figure 2.1.7). The diagram shows the input features x1,…,xdx_1, \ldots, x_d as nodes in the input layer, each wired with its own synaptic weight w1,…,wdw_1, \ldots, w_d into a single computing unit o1o_1 in the output layer, which sums the weighted inputs, adds the bias bb, and emits y^=o1\hat{y} = o_1.

Figure 2.1.7:

Linear regression is a single-layer neural network (a single artificial neuron).

By convention, we count only layers that hold tunable parameters, so linear regression is a one-layer network. Because every input feature connects to the output node, this layer is called a fully connected layer (or dense layer). Individual neurons in the cortex likewise integrate weighted signals from thousands of synapses on their dendrites, an analogy that inspired early pioneers like McCulloch and Pitts (McCulloch and Pitts, 1943), though our focus throughout this book is on the mathematics and engineering of composing such layers into deep networks.

2.1.5 Summary#

Linear regression predicts a continuous target via an affine combination of the features, y^=Xw+b\hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b, and scores misfit by the mean squared error L(w,b)=12n∥Xw+b−y∥22L(\mathbf{w}, b) = \frac{1}{2n}\|\mathbf{X}\mathbf{w} + b - \mathbf{y}\|_2^2. Geometrically, the closed-form normal equations X⊤Xw∗=X⊤y\mathbf{X}^\top\mathbf{X}\mathbf{w}^* = \mathbf{X}^\top\mathbf{y} project y\mathbf{y} orthogonally onto the column space of X\mathbf{X}, but forming and solving that d×dd \times d system costs O(nd2+d3)O(nd^2 + d^3) operations and does not generalize to nonlinear networks. Minibatch stochastic gradient descent instead updates the parameters with vectorized matrix operations on small random batches Bt\mathcal{B}_t, descending rapidly in O(∣B∣d)O(|\mathcal{B}|d) work per step to a small noise ball around the optimum. Statistically, minimizing squared error is maximum-likelihood estimation under additive Gaussian noise; replacing the Gaussian model with heavier-tailed or discrete distributions yields alternative losses such as absolute error and the Poisson negative log-likelihood.

2.1.6 Exercises#

  1. Intercept and centering. Appending a constant feature 11 to every input turns the affine model w⊤x+b\mathbf{w}^\top \mathbf{x} + b into a linear model in (x,1)(\mathbf{x}, 1). Centering the data removes the bias in a different way. Let xˉ\bar{\mathbf{x}} and yˉ\bar{y} be the averages of the features and of the labels over the training set.

    1. Show that every minimizer (w^,b^)(\hat{\mathbf{w}}, \hat{b}) of the squared loss satisfies b^=yˉ−w^⊤xˉ\hat{b} = \bar{y} - \hat{\mathbf{w}}^\top \bar{\mathbf{x}}, and conclude that the errors y^(i)−y(i)\hat{y}^{(i)} - y^{(i)} of a least-squares fit with a bias sum to zero.
    2. Show that w^\hat{\mathbf{w}} is a least-squares fit without bias to the centered data (x(i)−xˉ, y(i)−yˉ)(\mathbf{x}^{(i)} - \bar{\mathbf{x}},\, y^{(i)} - \bar{y}).
  2. Laplace noise. Assume that the additive noise ϵ\epsilon follows the Laplace distribution with scale 11 (see Section 24.3), that is, p(ϵ)=12exp⁡(−∣ϵ∣)p(\epsilon) = \frac{1}{2} \exp(-|\epsilon|).

    1. Write out the negative log-likelihood of the data under the model −log⁡p(y∣X)-\log p(\mathbf y \mid \mathbf X).
    2. Determine whether a closed-form solution exists.
    3. Write the minibatch stochastic gradient descent update for (w,b)(\mathbf{w}, b) under this loss in the form of (2.1.10), using 00 where ∣⋅∣|\cdot| has no derivative, at zero, and elsewhere its slope sign⁡(⋅)=±1\operatorname{sign}(\cdot) = \pm 1. A substitute of this kind is called a subgradient. Compare how the size of each example's contribution depends on its error under this loss and under the squared loss.
    4. [code] Apply this update to the corrupted-label data of Section 2.1.1.3, for a line through the origin, using the full dataset in every step, the learning rate 0.002, and 2,000 steps from w=0w = 0. The minimizer of the absolute error is exactly w=2w = 2. Where do the iterates end? Explain why they do not settle at the minimizer, and propose a fix.
  3. Beyond Gaussian noise. Suppose you use regression to estimate the price of houses or of stocks.

    1. Model the price directly as y=w⊤x+b+ϵy = \mathbf{w}^\top \mathbf{x} + b + \epsilon with ϵ∼N(0,σ2)\epsilon \sim \mathcal{N}(0, \sigma^2), and take σ=100,000\sigma = 100{,}000 dollars. Compute the probability that the model assigns to a negative price for a house whose predicted price is 50,00050{,}000 dollars. Explain why no single σ\sigma suits both this house and a house whose predicted price is 5,000,0005{,}000{,}000 dollars.
    2. Now regress on the logarithm of the price, log⁡price=w⊤x+b+ϵ\log \textrm{price} = \mathbf{w}^\top \mathbf{x} + b + \epsilon, where ϵ∼N(0,σ2)\epsilon \sim \mathcal{N}(0, \sigma^2) now acts on the log scale. Compute the conditional mean and standard deviation of the price and show that their ratio does not depend on x\mathbf{x}. Determine whether exp⁡(w⊤x+b)\exp(\mathbf{w}^\top \mathbf{x} + b) is an unbiased prediction of the price. The same modeling choice underlies the Black--Scholes model of option pricing (Black and Scholes, 1973).
  4. Counting apples. Suppose we want to use regression to estimate the number of apples sold in a grocery store.

    1. Identify the problems with a Gaussian additive noise model for such a target.
    2. The Poisson distribution models counts. It is given by p(k∣ν)=νke−ν/k!p(k \mid \nu) = \nu^k e^{-\nu}/k!, where ν>0\nu > 0 is the rate and k∈{0,1,2,…}k \in \{0, 1, 2, \ldots\} is the observed count. Prove that E[k]=ν\mathbb{E}[k] = \nu.
    3. Derive the negative log-likelihood of a count kk under a rate ν(x)\nu(\mathbf{x}) that depends on the features, dropping terms that do not depend on the parameters, and check it against the table in Section 2.1.3.3.
    4. Compare the parameterizations ν(x)=w⊤x+b\nu(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b and log⁡ν(x)=w⊤x+b\log \nu(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b. Determine for each whether ν(x)>0\nu(\mathbf{x}) > 0 holds for all inputs and parameters, and state the consequence for the loss of part (c). Write that loss in terms of (w,b)(\mathbf{w}, b) for the second parameterization.
  5. [code] The size of the noise ball. Generate n=1,000n = 1{,}000 examples with two features drawn from N(0,1)\mathcal{N}(0, 1) and labels y=x⊤w∗+ϵy = \mathbf{x}^\top \mathbf{w}^* + \epsilon, where w∗=(2,−3.4)\mathbf{w}^* = (2, -3.4) and ϵ∼N(0,1)\epsilon \sim \mathcal{N}(0, 1), and compute the least-squares solution w^\hat{\mathbf{w}} with lstsq.

    1. Run minibatch SGD without a bias, starting at w^\hat{\mathbf{w}}, with minibatches of 10 and η=0.1\eta = 0.1 for 20,000 steps. Estimate the mean squared distance E∥w−w^∥2\mathbb{E}\|\mathbf{w} - \hat{\mathbf{w}}\|^2 of the iterates from w^\hat{\mathbf{w}}.
    2. Repeat for η∈{0.05,0.025}\eta \in \{0.05, 0.025\} and for minibatch sizes 20 and 40. Check that the mean squared distance is roughly proportional to η/∣B∣\eta / |\mathcal{B}|.
    3. Why does the distance not depend on how far w^\hat{\mathbf{w}} is from w∗\mathbf{w}^*? What would change if the labels had no noise at all?
  6. Singular design matrix. ● Full column rank makes the least-squares minimizer unique. Suppose instead that X⊤X\mathbf{X}^\top \mathbf{X} is singular.

    1. Show that a minimizer of ∥y−Xw∥2\|\mathbf{y} - \mathbf{X}\mathbf{w}\|^2 still exists and characterize the set of all minimizers.
    2. Write the singular value decomposition as X=UΣV⊤\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top with orthogonal U\mathbf{U} and V\mathbf{V} and a rectangular diagonal Σ\boldsymbol{\Sigma} of nonnegative singular values. The Moore--Penrose pseudoinverse is
X†=VΣ†U⊤,(2.1.14)\mathbf{X}^{\dagger} = \mathbf{V}\boldsymbol{\Sigma}^{\dagger}\mathbf{U}^\top, \tag{2.1.14}

where Σ†\boldsymbol{\Sigma}^{\dagger} transposes Σ\boldsymbol{\Sigma} and inverts its nonzero entries. Show that X†y\mathbf{X}^{\dagger}\mathbf{y} is the minimizer of smallest norm within the set of part (a).

  1. Starting from w=0\mathbf{w} = \mathbf{0}, which minimizer does gradient descent converge to? State whether the answer changes for minibatch stochastic gradient descent.

Discussions