import time
import numpy as np
import torch2.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 tensorflow as tfimport time
import jax
from jax import numpy as jnp
import numpy as npimport time
import numpy as np
from mxnet import np as mnp, npx
npx.set_np()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 \(n\) examples. We index them by \(i \in \{1, \ldots, n\}\), writing \(\mathbf{x}^{(i)} = (x_1^{(i)}, x_2^{(i)})^\top \in \mathbb{R}^2\) for the feature vector of the \(i^{\textrm{th}}\) house and \(y^{(i)} \in \mathbb{R}\) for its observed sale price. More generally, when each example is described by \(d\) features, \(\mathbf{x}^{(i)} \in \mathbb{R}^d\), and the full dataset is the collection of pairs \(\{(\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:
\[\textrm{price} = w_{\textrm{area}} \cdot \textrm{area} + w_{\textrm{age}} \cdot \textrm{age} + b. \tag{2.1.1}\]
Here \(w_{\textrm{area}}\) and \(w_{\textrm{age}}\) are the weights, and \(b\) 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 \(b\) anchors the prediction when all features are zero. Even if no real house has zero area, keeping \(b\) is essential: without it, the fitted plane is forced to pass through the origin, severely restricting the functions our model can express. Strictly speaking, Equation 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 \(d\) features, the model’s prediction \(\hat{y}\) (where the hat distinguishes an estimate from the observed label \(y\)) takes the form
\[\hat{y} = w_1 x_1 + \cdots + w_d x_d + b = \mathbf{w}^\top \mathbf{x} + b, \tag{2.1.2}\]
where \(\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 \(n\) examples at once, we stack the feature vectors \(\mathbf{x}^{(i)}\) as the rows of the design matrix \(\mathbf{X} \in \mathbb{R}^{n \times d}\) and the predictions \(\hat{y}^{(i)}\) into the column vector \(\hat{\mathbf{y}} \in \mathbb{R}^n\):
\[\hat{\mathbf{y}} = \mathbf{X} \mathbf{w} + b, \tag{2.1.3}\]
where the scalar bias \(b\) is added to every component of \(\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 \((\mathbf{w}, b) \in \mathbb{R}^d \times \mathbb{R}\) that make \(\hat{\mathbf{y}}\) match the observed labels \(\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.
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 \((\mathbf{w}, b)\) misses the observed labels. A loss function assigns a nonnegative penalty to the gap between prediction \(\hat{y}\) and truth \(y\), vanishing when the two agree. For regression, the standard choice is the squared error:
\[l^{(i)}(\mathbf{w}, b) = \frac{1}{2} \left(\hat{y}^{(i)} - y^{(i)}\right)^2. \tag{2.1.4}\]
The factor of \(\frac{1}{2}\) is purely a cosmetic convenience: it cancels the factor of \(2\) that drops down when we differentiate the square, leaving the location of the minimum unchanged. Because the difference \(\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 \(3\) incurs nine times the loss of a prediction off by \(1\). Geometrically (Figure 2.1.2), each residual \(\hat{y}^{(i)} - y^{(i)}\) is the vertical distance between the data point and the regression line, and \(2\,l^{(i)}\) is the area of the square built on that vertical segment.
To score \((\mathbf{w}, b)\) across the entire training set of \(n\) examples, we average the per-example losses to form the empirical loss (or cost / objective):
\[ \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 \(n\) 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
\[\mathbf{w}^*, b^* = \operatorname*{argmin}_{\mathbf{w},\, b}\ L(\mathbf{w}, b). \tag{2.1.5}\]
Because errors are squared, a prediction off by \(10\) incurs a hundred times the penalty of a prediction off by \(1\), so a single corrupted label can dominate the fit. To see how severely, let us place twenty points on the line \(y = 2x\), corrupt a single label to \(y^{(6)} = 10{,}000\) (as a data-entry typo might), and fit a line through the origin \(\hat{y} = wx\) in two ways: first by the closed-form squared-loss minimizer \(w = \sum_i x^{(i)} y^{(i)} / \sum_i (x^{(i)})^2\), and second by minimizing the mean absolute error \(\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.00\) all the way to \(22.88\), while the absolute-error slope does not budge from \(2.00\). Under squared loss, one error of nearly \(10{,}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 \((\mathbf{w}^*, b^*)\) when there are \(d\) features and \(n\) 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 \(b\) into the weight vector by appending a constant column of \(1\)s to the design matrix: each input becomes \((\mathbf{x}^{(i)}, 1)^\top \in \mathbb{R}^{d+1}\) and the parameter vector becomes \((\mathbf{w}, b)^\top \in \mathbb{R}^{d+1}\) (or equivalently, we can center both \(\mathbf{X}\) and \(\mathbf{y}\) by their sample means; see Exercise 1). Writing \(\mathbf{X}\) and \(\mathbf{w}\) in this augmented notation, the loss is simply
\[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 \(\mathbf{X}^\top\mathbf{X}\) is invertible (which holds if and only if the columns of \(\mathbf{X}\) are linearly independent, requiring \(n \geq d\)). Define \(\hat{\mathbf{w}} = (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}\), so that \(\mathbf{X}^\top\mathbf{X}\hat{\mathbf{w}} = \mathbf{X}^\top\mathbf{y}\). Adding and subtracting \(\mathbf{X}\hat{\mathbf{w}}\) inside the norm and expanding the square yields
\[ \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:
\[(\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 \(\mathbf{w}\). What remains is a sum of two nonnegative squared norms. The first term, \(\|\mathbf{y} - \mathbf{X}\hat{\mathbf{w}}\|_2^2\), does not depend on \(\mathbf{w}\) at all; the second term, \(\|\mathbf{X}(\hat{\mathbf{w}} - \mathbf{w})\|_2^2\), is zero if and only if \(\mathbf{w} = \hat{\mathbf{w}}\) (since \(\mathbf{X}\) has full column rank). Thus \(\hat{\mathbf{w}}\) is the unique global minimizer. We could reach the same equation via calculus by setting the gradient \(\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:
\[\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 \(\mathbf{X}\) are linearly dependent (for instance, when two features are redundant or when \(d > n\)), \(\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 \((\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, 2\), labels \(1, 1, 0\), and augmented rows \((1, \textrm{input})\), so that \(\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 \(\mathbf{r} = \mathbf{X}\hat{\mathbf{w}} - \mathbf{y} = (1/6, -1/3, 1/6)^\top\) satisfies \(\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
X = tf.constant([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]) # rows (1, input)
y = tf.constant([[1.0], [1.0], [0.0]])
w_hat = tf.linalg.lstsq(X, y, fast=False) # do not form X^T X
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]))
XTr = tf.transpose(X) @ r
print(f'max |X^T r|: {float(tf.reduce_max(tf.abs(XTr))):.0e}')w_hat: (1.1667, -0.5)
r: (0.1667, -0.3333, 0.1667)
max |X^T r|: 4e-07
X = jnp.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]) # rows (1, input)
y = jnp.array([[1.0], [1.0], [0.0]])
w_hat = jnp.linalg.lstsq(X, y)[0]
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(jnp.abs(X.T @ r).max()):.0e}')w_hat: (1.1667, -0.5)
r: (0.1667, -0.3333, 0.1667)
max |X^T r|: 3e-07
X = mnp.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]) # rows (1, input)
y = mnp.array([[1.0], [1.0], [0.0]])
w_hat = mnp.linalg.lstsq(X, y, rcond=None)[0]
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(mnp.abs(X.T @ r).max()):.0e}')w_hat: (1.1667, -0.5)
r: (0.1667, -0.3333, 0.1667)
max |X^T r|: 5e-07
2.1.2.2 Least Squares as Projection
Why are these called the normal equations? The identity Equation 2.1.7 with the vanishing cross term is literally the Pythagorean theorem in \(\mathbb{R}^n\) (Figure 2.1.3). As \(\mathbf{w}\) ranges over \(\mathbb{R}^d\), the possible prediction vectors \(\hat{\mathbf{y}} = \mathbf{X}\mathbf{w}\) sweep out a \(d\)-dimensional subspace of \(\mathbb{R}^n\): the column space (or span) of \(\mathbf{X}\). Usually the observed label vector \(\mathbf{y} \in \mathbb{R}^n\) does not lie in that subspace, because no linear combination of the \(d\) feature columns reproduces all \(n\) noisy observations.
Minimizing \(\|\mathbf{y} - \mathbf{X}\mathbf{w}\|_2^2\) means finding the point \(\hat{\mathbf{y}} = \mathbf{X}\hat{\mathbf{w}}\) in the column space of \(\mathbf{X}\) that lies closest to \(\mathbf{y}\) in Euclidean distance. By elementary geometry, the closest point in a flat subspace is the orthogonal projection of \(\mathbf{y}\) onto that subspace: the unique point whose difference vector \(\mathbf{y} - \mathbf{X}\hat{\mathbf{w}}\) is perpendicular (normal) to every column of \(\mathbf{X}\). Requiring \(\mathbf{y} - \mathbf{X}\hat{\mathbf{w}}\) to be orthogonal to all columns of \(\mathbf{X}\) is written \(\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:
- Computational scaling: Forming \(\mathbf{X}^\top\mathbf{X} \in \mathbb{R}^{d \times d}\) costs \(O(nd^2)\) operations and solving the \(d \times d\) system costs \(O(d^3)\). When a dataset has millions of examples and a model has millions or billions of parameters, storing or inverting a \(d \times d\) matrix is completely out of the question.
- 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 \(\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 \(\nabla L(\mathbf{w}, b) = \frac{1}{n}\sum_{i=1}^n \nabla l^{(i)}(\mathbf{w}, b)\) requires a pass over all \(n\) training examples just to take a single parameter step. When \(n = 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 \(t\), we draw a small random minibatch \(\mathcal{B}_t \subset \{1, \ldots, n\}\) of \(|\mathcal{B}|\) examples, average the loss gradients over \(\mathcal{B}_t\) alone, and update the parameters with a positive learning rate (step size) \(\eta > 0\):
\[(\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 \(\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/\sqrt{|\mathcal{B}|}\). For linear regression under the squared loss Equation 2.1.4, differentiating \(l^{(i)} = \frac{1}{2}(\mathbf{w}^\top\mathbf{x}^{(i)} + b - y^{(i)})^2\) explicitly gives the update rule
\[ \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 \(\mathbf{w}^\top\mathbf{x}^{(i)} + b - y^{(i)}\) is the signed prediction error on example \(i\). If the model overpredicts (\(\hat{y}^{(i)} > y^{(i)}\)), the update subtracts a multiple of \(\mathbf{x}^{(i)}\) from \(\mathbf{w}\) and nudges \(b\) downward, pulling the next prediction closer to \(y^{(i)}\). Notice also the conceptual distinction: \(\mathbf{w}\) and \(b\) are model parameters learned by optimization, whereas the minibatch size \(|\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(\mathbf{w})\) around the least-squares solution \(\hat{\mathbf{w}}\) (Figure 2.1.4). Full-batch gradient descent computes the gradient of \(L\) over all \(n\) examples at every step, marching smoothly across the elliptic contours into the minimum \(\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 \(\hat{\mathbf{w}}\), where the average gradient across all \(n\) examples is zero, individual noisy examples still have nonzero residuals \(\hat{y}^{(i)} - y^{(i)} \neq 0\). A random minibatch \(\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 \(\hat{\mathbf{w}}\) and then fluctuates perpetually inside a noise ball around \(\hat{\mathbf{w}}\) whose squared radius scales as \(\eta / |\mathcal{B}|\).
Halving \(\eta\) or doubling \(|\mathcal{B}|\) shrinks that terminal noise ball, and decaying \(\eta \to 0\) over the course of training lets the iterates settle onto \(\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 \(\hat{\mathbf{w}}\) itself deviates from the true population parameters by statistical estimation error of order \(1/\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 Equation 2.1.10, you should never loop over the examples \(i \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{,}000\) examples with weights \(\mathbf{w} = (2, -3.4)^\top\) and bias \(b = 4.2\): first one example at a time in a Python for loop, and then for all \(1{,}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 Nonen = 1000
X = tf.ones((n, 2)) # the values do not affect the timing
w = tf.constant([[2.0], [-3.4]])
b = 4.2
# Wait until all devices have finished (a GPU runs asynchronously)
wait = lambda x: tf.test.experimental.sync_devices()n = 1000
X = jnp.ones((n, 2)) # the values do not affect the timing
w = jnp.array([[2.0], [-3.4]])
b = 4.2
wait = jax.block_until_ready # JAX returns before it has finishedn = 1000
X = mnp.ones((n, 2)) # the values do not affect the timing
w = mnp.array([[2.0], [-3.4]])
b = 4.2
wait = lambda x: npx.waitall() # MXNet returns before it has finishedOur 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() - startloop = 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
one example at a time: 391.189 ms
all examples at once: 2.357 ms
speedup: 166x
one example at a time: 485.697 ms
all examples at once: 0.559 ms
speedup: 869x
one example at a time: 78.185 ms
all examples at once: 0.151 ms
speedup: 519x
Even though both paths perform the same arithmetic, computing all \(1{,}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 \(n\) inner products \(\mathbf{w}^\top\mathbf{x}^{(i)}\) into one matrix-vector product \(\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 \(\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 \(\sigma^2\) (standard deviation \(\sigma\)), whose probability density is
\[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\sigma\)). Because the squared deviation \((x - \mu)^2\) appears inside the negative exponential, extreme deviations are vanishingly unlikely: a value \(5\sigma\) from the mean has density \(e^{-12.5} \approx 4 \times 10^{-6}\) times that at the peak. We write \(\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 36.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 = \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 \(\mathbb{E}[y \mid \mathbf{x}]\) is indeed \(\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 \(\mathbf{x}\) (Figure 2.1.5).
2.1.3.2 Maximum Likelihood
Under this additive Gaussian noise model, given features \(\mathbf{x}\), the conditional distribution of the observed label \(y\) is normal with mean \(\mathbf{w}^\top\mathbf{x} + b\) and variance \(\sigma^2\):
\[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 \((\mathbf{w}, b)\) to maximize the conditional probability density of observing the entire dataset \(\{y^{(1)}, \ldots, y^{(n)}\}\) given \(\{\mathbf{x}^{(1)}, \ldots, \mathbf{x}^{(n)}\}\). Assuming the examples are drawn independently, the dataset likelihood factors into the product \(\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(\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, \(\frac{n}{2}\log(2\pi\sigma^2)\), does not depend on \(\mathbf{w}\) or \(b\) at all. The second term is simply \(\frac{n}{\sigma^2} L(\mathbf{w}, b)\), our mean squared error loss scaled by the positive constant \(n/\sigma^2\). Therefore, minimizing the squared error loss produces the maximum-likelihood estimator of \((\mathbf{w}, b)\) under independent homoscedastic Gaussian noise, regardless of the value of \(\sigma^2\).
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 \(x_1, \ldots, x_d\) as nodes in the input layer, each wired with its own synaptic weight \(w_1, \ldots, w_d\) into a single computing unit \(o_1\) in the output layer, which sums the weighted inputs, adds the bias \(b\), and emits \(\hat{y} = o_1\).
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, \(\hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b\), and scores misfit by the mean squared error \(L(\mathbf{w}, b) = \frac{1}{2n}\|\mathbf{X}\mathbf{w} + b - \mathbf{y}\|_2^2\). Geometrically, the closed-form normal equations \(\mathbf{X}^\top\mathbf{X}\mathbf{w}^* = \mathbf{X}^\top\mathbf{y}\) project \(\mathbf{y}\) orthogonally onto the column space of \(\mathbf{X}\), but forming and solving that \(d \times d\) system costs \(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 \(\mathcal{B}_t\), descending rapidly in \(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
- Intercept and centering. Appending a constant feature \(1\) to every input turns the affine model \(\mathbf{w}^\top \mathbf{x} + b\) into a linear model in \((\mathbf{x}, 1)\). Centering the data removes the bias in a different way. Let \(\bar{\mathbf{x}}\) and \(\bar{y}\) be the averages of the features and of the labels over the training set.
- Show that every minimizer \((\hat{\mathbf{w}}, \hat{b})\) of the squared loss satisfies \(\hat{b} = \bar{y} - \hat{\mathbf{w}}^\top \bar{\mathbf{x}}\), and conclude that the errors \(\hat{y}^{(i)} - y^{(i)}\) of a least-squares fit with a bias sum to zero.
- Show that \(\hat{\mathbf{w}}\) is a least-squares fit without bias to the centered data \((\mathbf{x}^{(i)} - \bar{\mathbf{x}},\, y^{(i)} - \bar{y})\).
- Laplace noise. Assume that the additive noise \(\epsilon\) follows the Laplace distribution with scale \(1\) (see Section 36.3), that is, \(p(\epsilon) = \frac{1}{2} \exp(-|\epsilon|)\).
- Write out the negative log-likelihood of the data under the model \(-\log p(\mathbf y \mid \mathbf X)\).
- Determine whether a closed-form solution exists.
- Write the minibatch stochastic gradient descent update for \((\mathbf{w}, b)\) under this loss in the form of Equation 2.1.10, using \(0\) where \(|\cdot|\) has no derivative, at zero, and elsewhere its slope \(\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.
- [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 = 0\). The minimizer of the absolute error is exactly \(w = 2\). Where do the iterates end? Explain why they do not settle at the minimizer, and propose a fix.
- Beyond Gaussian noise. Suppose you use regression to estimate the price of houses or of stocks.
- Model the price directly as \(y = \mathbf{w}^\top \mathbf{x} + b + \epsilon\) with \(\epsilon \sim \mathcal{N}(0, \sigma^2)\), and take \(\sigma = 100{,}000\) dollars. Compute the probability that the model assigns to a negative price for a house whose predicted price is \(50{,}000\) dollars. Explain why no single \(\sigma\) suits both this house and a house whose predicted price is \(5{,}000{,}000\) dollars.
- Now regress on the logarithm of the price, \(\log \textrm{price} = \mathbf{w}^\top \mathbf{x} + b + \epsilon\), where \(\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 \(\mathbf{x}\). Determine whether \(\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).
- Counting apples. Suppose we want to use regression to estimate the number of apples sold in a grocery store.
- Identify the problems with a Gaussian additive noise model for such a target.
- The Poisson distribution models counts. It is given by \(p(k \mid \nu) = \nu^k e^{-\nu}/k!\), where \(\nu > 0\) is the rate and \(k \in \{0, 1, 2, \ldots\}\) is the observed count. Prove that \(\mathbb{E}[k] = \nu\).
- Derive the negative log-likelihood of a count \(k\) under a rate \(\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.
- Compare the parameterizations \(\nu(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b\) and \(\log \nu(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b\). Determine for each whether \(\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 \((\mathbf{w}, b)\) for the second parameterization.
- [code] The size of the noise ball. Generate \(n = 1{,}000\) examples with two features drawn from \(\mathcal{N}(0, 1)\) and labels \(y = \mathbf{x}^\top \mathbf{w}^* + \epsilon\), where \(\mathbf{w}^* = (2, -3.4)\) and \(\epsilon \sim \mathcal{N}(0, 1)\), and compute the least-squares solution \(\hat{\mathbf{w}}\) with
lstsq.- Run minibatch SGD without a bias, starting at \(\hat{\mathbf{w}}\), with minibatches of 10 and \(\eta = 0.1\) for 20,000 steps. Estimate the mean squared distance \(\mathbb{E}\|\mathbf{w} - \hat{\mathbf{w}}\|^2\) of the iterates from \(\hat{\mathbf{w}}\).
- Repeat for \(\eta \in \{0.05, 0.025\}\) and for minibatch sizes 20 and 40. Check that the mean squared distance is roughly proportional to \(\eta / |\mathcal{B}|\).
- Why does the distance not depend on how far \(\hat{\mathbf{w}}\) is from \(\mathbf{w}^*\)? What would change if the labels had no noise at all?
- Singular design matrix. ● Full column rank makes the least-squares minimizer unique. Suppose instead that \(\mathbf{X}^\top \mathbf{X}\) is singular.
Show that a minimizer of \(\|\mathbf{y} - \mathbf{X}\mathbf{w}\|^2\) still exists and characterize the set of all minimizers.
Write the singular value decomposition as \(\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^\top\) with orthogonal \(\mathbf{U}\) and \(\mathbf{V}\) and a rectangular diagonal \(\boldsymbol{\Sigma}\) of nonnegative singular values. The Moore–Penrose pseudoinverse is
\[\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 \(\mathbf{X}^{\dagger}\mathbf{y}\) is the minimizer of smallest norm within the set of part (a).
Starting from \(\mathbf{w} = \mathbf{0}\), which minimizer does gradient descent converge to? State whether the answer changes for minibatch stochastic gradient descent.