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 torch2.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 examples. We index them by , writing for the feature vector of the house and for its observed sale price. More generally, when each example is described by features, , and the full dataset is the collection of pairs .
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:
Here and are the weights, and 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 anchors the prediction when all features are zero. Even if no real house has zero area, keeping 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 features, the model's prediction (where the hat distinguishes an estimate from the observed label ) takes the form
where collects the weights into a single column vector. Whenever we evaluate the model across all examples at once, we stack the feature vectors as the rows of the design matrix and the predictions into the column vector :
where the scalar bias is added to every component of 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 that make match the observed labels 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.
The shapes in , drawn for examples and features. Each row of is one example and produces one entry of (shaded); holds one weight per column, and the scalar is broadcast to all 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 misses the observed labels. A loss function assigns a nonnegative penalty to the gap between prediction and truth , vanishing when the two agree. For regression, the standard choice is the squared error:
The factor of is purely a cosmetic convenience: it cancels the factor of that drops down when we differentiate the square, leaving the location of the minimum unchanged. Because the difference 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 incurs nine times the loss of a prediction off by . Geometrically (Figure 2.1.2), each residual is the vertical distance between the data point and the regression line, and is the area of the square built on that vertical segment.
Fitting a line to data by minimizing the sum of squared vertical residuals.
To score across the entire training set of examples, we average the per-example losses to form the empirical loss (or cost / objective):
Dividing by 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
Because errors are squared, a prediction off by incurs a hundred times the penalty of a prediction off by , so a single corrupted label can dominate the fit. To see how severely, let us place twenty points on the line , corrupt a single label to (as a data-entry typo might), and fit a line through the origin in two ways: first by the closed-form squared-loss minimizer , and second by minimizing the mean absolute error 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 all the way to , while the absolute-error slope does not budge from . Under squared loss, one error of nearly 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 when there are features and 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 into the weight vector by appending a constant column of s to the design matrix: each input becomes and the parameter vector becomes (or equivalently, we can center both and by their sample means; see Exercise 1). Writing and in this augmented notation, the loss is simply
We can find its global minimum by pure algebra, completing the square without taking a derivative, whenever is invertible (which holds if and only if the columns of are linearly independent, requiring ). Define , so that . Adding and subtracting inside the norm and expanding the square yields
Look at the cross term at the end:
It vanishes identically for every . What remains is a sum of two nonnegative squared norms. The first term, , does not depend on at all; the second term, , is zero if and only if (since has full column rank). Thus is the unique global minimizer. We could reach the same equation via calculus by setting the gradient to zero, producing the classic normal equations:
When the columns of are linearly dependent (for instance, when two features are redundant or when ), 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 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 , labels , and augmented rows , so that holds the intercept first and the slope second. We also check that the residual vector satisfies 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 (Figure 2.1.3). As ranges over , the possible prediction vectors sweep out a -dimensional subspace of : the column space (or span) of . Usually the observed label vector does not lie in that subspace, because no linear combination of the feature columns reproduces all noisy observations.
Least squares as orthogonal projection in . The column space of contains every prediction vector ; the closest point to is the orthogonal projection , whose residual is perpendicular (normal) to every column of .
Minimizing means finding the point in the column space of that lies closest to in Euclidean distance. By elementary geometry, the closest point in a flat subspace is the orthogonal projection of onto that subspace: the unique point whose difference vector is perpendicular (normal) to every column of . Requiring to be orthogonal to all columns of is written , 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 costs operations and solving the system costs . When a dataset has millions of examples and a model has millions or billions of parameters, storing or inverting a 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 points in the direction of steepest ascent of the loss. Stepping in the opposite direction reduces the loss, yet evaluating the full gradient requires a pass over all training examples just to take a single parameter step. When , 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 , we draw a small random minibatch of examples, average the loss gradients over alone, and update the parameters with a positive learning rate (step size) :
Because 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 . For linear regression under the squared loss (2.1.4), differentiating explicitly gives the update rule
Look at what each term does: the scalar is the signed prediction error on example . If the model overpredicts (), the update subtracts a multiple of from and nudges downward, pulling the next prediction closer to . Notice also the conceptual distinction: and are model parameters learned by optimization, whereas the minibatch size and learning rate 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 around the least-squares solution (Figure 2.1.4). Full-batch gradient descent computes the gradient of over all examples at every step, marching smoothly across the elliptic contours into the minimum (provided is not so large that it overshoots and diverges).
Minibatch SGD follows a different path. Even at the global minimum , where the average gradient across all examples is zero, individual noisy examples still have nonzero residuals . A random minibatch almost never has its per-example gradients cancel out to zero. Consequently, at constant learning rate , minibatch SGD quickly descends into a small neighborhood of and then fluctuates perpetually inside a noise ball around whose squared radius scales as .
Full-batch gradient descent (black) marches smoothly along the gradient of to the minimum , taking one pass over all examples per step. Minibatch SGD (color) takes inexpensive steps per pass using noisy gradient estimates, descending rapidly to a small noise ball around ; quartering the learning rate (right) shrinks the ball.
Halving or doubling shrinks that terminal noise ball, and decaying over the course of training lets the iterates settle onto (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 itself deviates from the true population parameters by statistical estimation error of order , 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 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 examples with weights and bias : first one example at a time in a Python for loop, and then for all 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 NoneOur 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 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 inner products into one matrix-vector product —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 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 and variance (standard deviation ), whose probability density is
This density forms a symmetric bell-shaped curve centered at , whose width is set by the standard deviation (about 68% of the probability lies within of the mean and about 95% within ). Because the squared deviation appears inside the negative exponential, extreme deviations are vanishingly unlikely: a value from the mean has density times that at the peak. We write 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:
Under this model, the conditional mean is indeed (matching Section 2.1.1.2), and labels scatter symmetrically around the line with the same noise scale at every input (Figure 2.1.5).
The Gaussian noise model. For every input , the label is drawn from a normal density centered on the line , with the same width everywhere.
2.1.3.2 Maximum Likelihood#
Under this additive Gaussian noise model, given features , the conditional distribution of the observed label is normal with mean and variance :
According to the principle of maximum likelihood, we should choose to maximize the conditional probability density of observing the entire dataset given . Assuming the examples are drawn independently, the dataset likelihood factors into the product . Maximizing a positive product is equivalent to minimizing its negative logarithm, the negative log-likelihood:
Look closely at the two terms on the right. The first term, , does not depend on or at all. The second term is simply , our mean squared error loss scaled by the positive constant . Therefore, minimizing the squared error loss produces the maximum-likelihood estimator of under independent homoscedastic Gaussian noise, regardless of the value of .
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 and ask which single number minimizes the expected squared error . Setting the derivative to zero gives the conditional mean , for any noise distribution with finite variance. The expected absolute error is minimized by the conditional median instead. Tilt it, so that each unit of underestimation costs and each unit of overestimation costs , and the minimizer becomes the -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 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 type | Noise model | Loss (negative log-likelihood) | Statistic predicted |
|---|---|---|---|
| real-valued, well-behaved noise | Gaussian | squared error (this section) | mean of |
| real-valued, outliers or heavy tails | Laplace | absolute error (exercise 2) | median of |
| positive, multiplicative fluctuations (prices) | Gaussian on | squared error on (exercise 3) | mean of |
| counts (sales, arrivals) | Poisson | (exercise 4) | mean of |
- Heavy-tailed outliers (Laplace noise loss): If occasional corrupted measurements produce wild outliers, the quadratic growth of lets a single bad data point yank the fitted line toward itself. Modeling the noise with heavier exponential tails via the Laplace distribution turns the negative log-likelihood into the absolute error () loss (Exercise 2), whose gradient has constant magnitude no matter how far an outlier sits.
- Combining smooth optima with outlier robustness (Huber loss): Because has a sharp corner at zero where its derivative jumps between and , practitioners often use the Huber loss, which splices a quadratic bowl for small residuals () onto linear slopes for large residuals ().
- Count data (Poisson noise): When the target is a discrete count (such as daily customer arrivals), a Poisson likelihood leads to its own convex negative log-likelihood (Exercise 4).
Three regression loss functions (right) and the noise densities 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 as nodes in the input layer, each wired with its own synaptic weight into a single computing unit in the output layer, which sums the weighted inputs, adds the bias , and emits .
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, , and scores misfit by the mean squared error . Geometrically, the closed-form normal equations project orthogonally onto the column space of , but forming and solving that system costs operations and does not generalize to nonlinear networks. Minibatch stochastic gradient descent instead updates the parameters with vectorized matrix operations on small random batches , descending rapidly in 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 to every input turns the affine model into a linear model in . Centering the data removes the bias in a different way. Let and be the averages of the features and of the labels over the training set.
- Show that every minimizer of the squared loss satisfies , and conclude that the errors of a least-squares fit with a bias sum to zero.
- Show that is a least-squares fit without bias to the centered data .
-
Laplace noise. Assume that the additive noise follows the Laplace distribution with scale (see Section 24.3), that is, .
- Write out the negative log-likelihood of the data under the model .
- Determine whether a closed-form solution exists.
- Write the minibatch stochastic gradient descent update for under this loss in the form of (2.1.10), using where has no derivative, at zero, and elsewhere its slope . 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 . The minimizer of the absolute error is exactly . 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 with , and take dollars. Compute the probability that the model assigns to a negative price for a house whose predicted price is dollars. Explain why no single suits both this house and a house whose predicted price is dollars.
- Now regress on the logarithm of the price, , where 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 . Determine whether 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 , where is the rate and is the observed count. Prove that .
- Derive the negative log-likelihood of a count under a rate 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 and . Determine for each whether holds for all inputs and parameters, and state the consequence for the loss of part (c). Write that loss in terms of for the second parameterization.
-
[code] The size of the noise ball. Generate examples with two features drawn from and labels , where and , and compute the least-squares solution with
lstsq.- Run minibatch SGD without a bias, starting at , with minibatches of 10 and for 20,000 steps. Estimate the mean squared distance of the iterates from .
- Repeat for and for minibatch sizes 20 and 40. Check that the mean squared distance is roughly proportional to .
- Why does the distance not depend on how far is from ? 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 is singular.
- Show that a minimizer of still exists and characterize the set of all minimizers.
- Write the singular value decomposition as with orthogonal and and a rectangular diagonal of nonnegative singular values. The Moore--Penrose pseudoinverse is
where transposes and inverts its nonzero entries. Show that is the minimizer of smallest norm within the set of part (a).
- Starting from , which minimizer does gradient descent converge to? State whether the answer changes for minibatch stochastic gradient descent.