Machine learning replaces hand-written rules with functions fitted to data. Every method in this book does this with three components: a model that makes predictions, a loss that scores them, and an update rule that improves the model. Before we can see what is deep about deep learning, we need all three working together on the smallest model that contains them. Linear regression is that model. By the end of this chapter we will fit it with two methods: a direct solve and gradient descent. We will write gradient descent twice, once by hand and once with PyTorch modules. All three implementations agree, and we will see why.
where each \(\featurepart{\vect{x}_i}\in\R^d\) is an input with \(d\) features and \(\targetpart{y_i}\) is the output observed for that input, called the target or the supervision signal. Stacking the inputs as rows gives the blue data matrix \(\featurepart{\matr{X}}\in\R^{n\times d}\): \(n\) examples down, \(d\) features across, with the purple targets in \(\targetpart{\vect{y}}\).
Figure 1.1: Stacking examples turns a dataset into two aligned objects: one row of \(\matr{X}\) per input and one entry of \(\vect{y}\) per observed target. Color will keep these roles visible in the equations that follow.
Our goal is a flexible function \(f\) such that
\[
\predictionpart{f(\featurepart{\vect{x}_i})}
\approx \targetpart{y_i}
\quad \text{and } f \text{ generalizes to unseen data.}
\]
The second requirement, generalization to unseen data, is the central objective. Training fit alone is not sufficient. We assume that the training pairs \((\featurepart{\vect{x}_i}, \targetpart{y_i})\) are independent draws from one fixed but unknown probability distribution \(P\) over input–target pairs. A new input–target pair comes from the same \(P\), and what matters is how well \(f\) predicts the target from the input.
In statistical notation, training minimizes the empirical risk
Here \(\ell\) scores one prediction against its target (the loss section chooses a concrete \(\ell\)), and \(\parameterpart{\theta}\) is the vector of all the model’s adjustable parameters. The empirical risk is the average loss on the \(n\) examples we have. The population risk is the expected loss on a fresh pair drawn from \(P\), which we can only estimate. We will use this distinction throughout the book. An independent validation set drawn from \(P\) estimates performance under \(P\). After deployment, a model may meet inputs from a different distribution \(Q\), in which, for instance, every image is shifted by a few pixels. Performance under \(P\) need not predict performance under \(Q\). Chapter 6 makes that difference visible, and Appendix E gathers these statistical distinctions in one reference.
NoteThree supervised-learning tasks
The range of \(y\) determines the task and, as we will see, the natural loss:
Task
Range of \(y\)
Typical loss
Regression
\(\R\)
Mean squared error
Classification
\(\{0, \dots, K-1\}\)
Cross-entropy
Structured prediction
sequences, images, graphs
Task-specific
This chapter covers regression, and Chapter 2 handles classification with the same machinery.
Why is this hard?
Learning a function from examples sounds simple, but it hides a difficulty: for any finite set of examples, there are infinitely many functions that fit them perfectly. We want the one best suited to our problem, so the learning algorithm needs a nudge in the right direction: an assumption about which functions to prefer. That guiding assumption is called its inductive bias.
A linear model restricts its predictions to a weighted sum of the supplied features plus a constant. That strong assumption keeps it simple. It can follow a curve such as \(y = x^2\) only if \(x^2\) is one of the supplied features.
A deep neural network can learn nonlinear features of its own, while its architecture and training still impose assumptions about which solutions to prefer. Its flexibility lets it learn complex patterns. It can also memorize the training set without learning the underlying rule, and then perform poorly on new data.
The key to modern deep learning is to use a flexible model and limit overfitting with more data, regularization, and inductive biases matched to the structure of the problem. That last principle is the subject of Chapter 6.
To make any of this concrete, we parameterize a family of functions \(f_{\vect{w}}\) by a vector \(\vect{w}\) of adjustable parameters, the \(\parameterpart{\theta}\) of the risks above. Think of each parameter as a knob. Learning is finding a good setting \(\hat{\vect{w}}\) of the knobs. Inference is using \(f_{\hat{\vect{w}}}\) to predict on unseen data. That is the vocabulary we will use throughout the book.
The second term, \(\parameterpart{b}\), is the prediction at \(\featurepart{\vect{x}}=\vect{0}\). The first term, \(\parameterpart{\vect{w}^\top}\featurepart{\vect{x}}\), adjusts that baseline up or down based on how the input matches the weight vector. In linear algebra, a linear map plus a constant is called affine. Machine learning usually says “linear” for both, and we will say “affine” when the constant matters.
Figure 1.2: The dot product measures the signed shadow of an input along the weight vector. Aligned inputs raise the prediction above \(\parameterpart{b}\), orthogonal inputs leave it at \(\parameterpart{b}\), and opposing inputs lower it.
Figure 1.2 draws the first term and shows the principle behind it: a dot product is a similarity score. With \(\varphi\) the angle between \(\parameterpart{\vect{w}}\) and \(\featurepart{\vect{x}}\),
For normalized vectors it measures directional similarity directly: positive when \(\featurepart{\vect{x}}\) points along \(\parameterpart{\vect{w}}\), zero when they are orthogonal, and negative when they oppose. Without normalization, the two norms also control the score, so a large dot product can mean strong alignment, large magnitude, or both. A linear model is therefore a learned pattern scorer: \(\parameterpart{\vect{w}}\) is a template whose direction and scale both matter.1
To simplify notation, we absorb \(\parameterpart{b}\) into the weights by appending \(1\) to the input vector, \(\featurepart{\vect{x}} = (x_1, \dots, x_d, 1)^\top\), and \(\parameterpart{b}\) to \(\parameterpart{\vect{w}} = (w_1, \dots, w_d, \parameterpart{b})^\top\).2 Then
A large score: does it mean the input matches the template, or only that one of them is long?
A schematic view of this section's signed-shadow figure. One fixed template w is scored against one input x, and the prediction is read against the baseline b.
Now only the template's length changes. Direction similarity holds; the score still halves.
0:00 / 0:40
The calculation is readable without playback. Opening this panel loads the optional controls.
Nothing here is trained: one fixed template is scored against one input, with the direction and the length varied one at a time.
Scope and caveats
The template direction, the input length, the bias, both schedules and the slider range are declared schematic drawing geometry, not numbers this chapter prints; the identity and the sign behaviour are the chapter's. Orthogonal means this feature adds nothing to this prediction, not that the feature is useless — a template pointing elsewhere would score the same input. A dot product is not cosine similarity: divide by both lengths first, and only then does the number measure direction alone. Green marks the signed displacement from b twice, on the template's line and on the meter, because it is one number seen twice. The length slider moves the template only; dragging it pauses playback, and any timeline action restores the timeline's own value.
Check yourself. Swap in an input of length 4.00 at 60 degrees from this same template, keeping the length of w at 1.50 and b at 1.00. What does the model predict?
Exactly 4.00. The score is 1.50 × 4.00 × cos 60°, and cos 60° is 0.50, so the score is 3.00 and the prediction is 1.00 + 3.00. That beats the 3.82 this scene opened with, even though 60° is a far worse match than 20°.
Transcript and keyboard help
Predict. An orange template of length 1.50 and a blue input of length 2.00 stand 20 degrees apart. The score and the prediction meter are withheld.
The signed shadow of the input on the template's line appears, and the meter opens beside it. Direction similarity 0.94, score 2.82, prediction 3.82 against a baseline of 1.00.
The input turns at a fixed length of 2.00. Only its direction changes: at 80 degrees the shadow has shortened to 0.35 and the score to 0.52.
Hold at 80 degrees. The input is about to cross the right angle. Predict the score there before releasing it.
Released. The shadow slides back along the template's line to the origin.
Hold at 90 degrees. The shadow is a single point, direction similarity is zero, the score is exactly zero, and the prediction reads exactly the baseline 1.00.
Past the right angle, at 120 degrees, the shadow lies on the far side of the origin. The score is minus 1.50 and the prediction minus 0.50, below the baseline.
The angle is frozen. Only the template's length changes, 1.50 to 0.75 and back. Direction similarity holds at minus 0.50 while the score moves between minus 1.50 and minus 0.75. The same score can come from alignment or from length.
Silent; paused initially; 1.5× playback. Focus the animation pane: Space or K plays/pauses, arrows seek between beats, Home/End jump, Escape pauses. The scrubber, the speed menu and the template-length slider also work by keyboard; the slider's own keys never move the timeline. Reduced-motion mode holds each beat's state instead of moving between them.
1.3 Measuring prediction error
To find the best hyperplane we must first quantify error. Write the residual on example \(i\) as \(\residualpart{e_i}=\targetpart{y_i}-\predictionpart{\hat y_i}\). The standard choice for regression is the mean squared error (MSE):
The dark red residual vector \(\residualpart{\vect{e}}\) records the discrepancy on each example. Squaring and averaging the residuals turns them into one number, the objective that training minimizes. The maximum-likelihood section explains why squared error is a principled choice.
The loss is a function of the parameters. With one weight and one bias, \(\parameterpart{\vect{w}} = (w,b)\), the MSE is a surface over the \((w,b)\) plane, called the loss landscape. Figure 1.4, later in this chapter, draws it as a surface and as contour lines for a small dataset. Learning means finding a low point on this surface. The next two methods differ in whether they solve for that point directly or approach it step by step.
1.4 Finding the best weights, method 1: solve it exactly
For this one special problem we do not need to search: we can characterize the exact minimizer. Differentiate the MSE of Equation 1.1 with respect to \(\parameterpart{\vect{w}}\) and set the gradient to zero:
The condition \(\featurepart{\matr{X}}^{\top}\residualpart{\vect{e}}=\vect{0}\) says the residual is orthogonal to every feature column. Substituting \(\residualpart{\vect{e}}=\targetpart{\vect{y}}-\featurepart{\matr{X}}\parameterpart{\hat{\vect{w}}}\) and moving the known term to the right gives the normal equations:
The normal equations characterize the minimizer. To compute it, we do not form \(\featurepart{\matr{X}}^\top\featurepart{\matr{X}}\) and invert it: the inverse \((\featurepart{\matr{X}}^\top\featurepart{\matr{X}})^{-1}\) is mathematical shorthand, and numerical libraries solve the system by more stable means (Implementation 1 below).
Direct inversion also requires full column rank (\(n \ge d\), with no redundant features). When parameters outnumber training examples (\(d > n\)), the matrix \(\featurepart{\matr{X}}^\top\featurepart{\matr{X}}\) is singular, and infinitely many weight vectors achieve the same minimum error. Classical statistics treated \(d > n\) as a pathology. In deep learning, having more parameters than training examples (overparameterization) is common.3
Even if direct inversion is impractical at scale, setting the gradient to zero gives a geometric picture of the solution. As the next subsection shows, the normal equations describe an orthogonal projection, and that projection can be read in two ways. The first reads a prediction as a weighted sum of features, as in every linear model. The second reads it as a weighted sum of training targets, the form that attention takes in Part IV.
Two sides of the same projection
Each column \(\featurepart{\matr{X}_{:j}}\) of the data matrix holds the values of feature \(j\) for all \(n\) examples. The prediction vector is a weighted combination of these columns, with the weights as coefficients:
It therefore lies in the column space of \(\featurepart{\matr{X}}\). If \(\targetpart{\vect{y}}\) lies outside that space, the closest point to it inside the space is found by dropping a perpendicular: \(\predictionpart{\hat{\vect{y}}}\) is the orthogonal projection of \(\targetpart{\vect{y}}\) onto the column space. The residual \(\residualpart{\vect{e}}=\targetpart{\vect{y}}-\predictionpart{\hat{\vect{y}}}\) is then orthogonal to every column, which is the condition \(\featurepart{\matr{X}}^{\top}\residualpart{\vect{e}}=\vect{0}\) derived above. No adjustment of the weights can shorten it further. Figure 1.3 draws the picture.
Figure 1.3: The normal equations, geometrically: the optimal prediction \(\predictionpart{\hat{\vect{y}}} = \featurepart{\matr{X}}\parameterpart{\hat{\vect{w}}}\) is the projection of \(\targetpart{\vect{y}}\) onto the column space of \(\featurepart{\matr{X}}\). The residual \(\residualpart{\vect{e}}\) is orthogonal to it.
Now read the same projection from the other side. Let \(\featurepart{\matr{X}^{+}}\) be the Moore–Penrose pseudoinverse of \(\featurepart{\matr{X}}\). It equals \((\featurepart{\matr{X}}^\top\featurepart{\matr{X}})^{-1}\featurepart{\matr{X}}^\top\) when \(\featurepart{\matr{X}}\) has full column rank. In general it is \(\matr{V}\matr{\Sigma}^{+}\matr{U}^\top\), where \(\featurepart{\matr{X}}=\matr{U}\matr{\Sigma}\matr{V}^\top\) is the SVD of \(\featurepart{\matr{X}}\) (Appendix A) and \(\matr{\Sigma}^{+}\) inverts the nonzero singular values and keeps the zero ones. One least-squares solution is \(\parameterpart{\hat{\vect{w}}} = \featurepart{\matr{X}^{+}}\targetpart{\vect{y}}\), and it is the only one when \(\featurepart{\matr{X}}\) has full column rank. Substituting it into \(\predictionpart{\hat{\vect{y}}} = \featurepart{\matr{X}}\parameterpart{\hat{\vect{w}}}\) gives \(\predictionpart{\hat{\vect{y}}} = \featurepart{\matr{X}\matr{X}^{+}}\targetpart{\vect{y}}\). The \(n\times n\) matrix \(\featurepart{\matr{X}\matr{X}^{+}}\) is the projection matrix, often called the hat matrix because it puts the hat on \(\targetpart{\vect{y}}\). Entry \(i\) of the product is one fitted value:
Read this way, every prediction is a weighted combination of the training targets\(\targetpart{y_j}\).4
This dual perspective will return often. The column-space reading predicts by weighting the features with learned weights. The hat-matrix reading predicts by mixing observed training targets. Under full column rank, the weight on \(\targetpart{y_j}\) is the inner product \(\featurepart{\vect{x}_i^\top(\matr{X}^\top\matr{X})^{-1}\vect{x}_j}\), which measures how the training input \(\featurepart{\vect{x}_j}\) aligns with the input \(\featurepart{\vect{x}_i}\) at which we predict.5
The normal equations define the optimal destination. What they do not provide is a scalable way to get there. A direct solution is available for the small linear models considered here. To train modern models, we trade the one-shot solve for an iterative search: start with an initial guess, measure how bad it is, and take a local step downhill.
Watch the mechanism: the prediction cannot leave the plane
If you tune the weights hard enough, can the prediction reach the target exactly?
A schematic of the projection figure above, with three examples standing in for the rows of X and two feature columns for its columns. The chapter prints no coordinates for that figure, so these vectors are this panel's own; the geometry they produce is the chapter's.
This leftover points straight out of the plane. No weights can remove it.
0:00 / 0:40
The diagram is readable without playback. Opening this panel loads the optional controls.
Three dimensions stand in for n examples and two columns for d features: this is a schematic of the chapter's geometry, not its dataset, and nothing is trained.
Scope and caveats
The two columns, the target and the swept path are declared on this panel; the projection, the weights that reach it, the residual and its length are solved from them by the normal equations, not fitted. The right angle is exact in that arithmetic — both columns give a zero inner product with the residual — and the small square is the drawn projection of a genuine three-dimensional one, so the flat page foreshortens it. The residual draws straight up the page only because the viewpoint was chosen to look across the plane; a tilted residual is not a different kind of error. The candidate's path is a drawing device, not an optimizer trajectory, and the weights are swept rather than learned. Two independent columns keep the weights unique. The chapter's text covers what this picture does not: rank deficiency, from redundant features or more parameters than examples, where infinitely many weight vectors reach the same minimum error, and, in a footnote, conditioning, where forming the normal equations squares the condition number.
Check yourself. Add a third feature column that is the sum of these two. Does the shortest residual drop below 3?
No — it stays 3. The sum of two columns is already reachable, so the column space, the projection and the perpendicular leftover are all unchanged. What does change is the weights: with a dependent column they are no longer unique. The chapter calls such a column a redundant feature, and it breaks full column rank.
Transcript and keyboard help
A purple target floats above a plane. The plane is the column space: every prediction the model can make lies in it. A green candidate sits somewhere inside, with the wine residual drawn from the candidate to the target. Predict where in the plane that residual is shortest.
Two blue arrows are the feature columns. Each is scaled by its own weight, and the second slides onto the head of the first, so the candidate prediction is assembled as one weighted combination.
The weights change and the candidate slides across the plane. The residual follows it, and its length readout moves with it.
The candidate travels on toward the target's shadow. Nothing it does leaves the plane, and the residual gets shorter.
The candidate reaches the foot of the perpendicular. A right-angle mark appears, the length readout stops at 3.00, and the normal equations light up: a zero inner product with every column is the same statement as the equation the chapter solves.
The candidate moves past that point. The right-angle mark goes, and the residual grows again. The stop was a genuine minimum, not the end of a path.
The candidate returns to the same point, and the residual falls back to the same 3.00.
The target is the green in-plane part plus the wine perpendicular part, head to tail. Only the in-plane part is reachable, so no choice of weights removes the rest. This is a schematic; nothing here was trained.
Silent; paused initially; 1.5× playback. Focus the animation pane: Space or K plays/pauses, arrows seek between beats, Home/End jump, Escape pauses. The scrubber and speed menu also work by keyboard. Reduced-motion mode holds each beat's state instead of moving between them.
1.5 Finding the best weights, method 2: walk downhill
Here is the geometric intuition. Picture the loss as a landscape over the parameter space, and imagine standing on it blindfolded, trying to find the lowest valley. You cannot see the valley, but you can feel the slope under your feet. So you feel the slope, take a small step downhill, and repeat. The mathematical expression of this procedure is gradient descent:
where the learning rate\(\eta\) sets the step size.
Recall from our derivation of the normal equations that the gradient of the MSE loss is already in hand. With \(\featurepart{\matr{X}}\in\R^{n\times d}\), \(\parameterpart{\vect{w}}\in\R^d\), and \(\targetpart{\vect{y}}\in\R^n\), the gradient is
Figure 1.4: One loss landscape, two views. The surface makes the scalar height of MSE visible; the contour view makes the update path legible. Gradient descent needs only the local slope, not a view of the whole bowl.
This iterative loop (predict \(\rightarrow\) evaluate the loss \(\rightarrow\) compute the gradient \(\rightarrow\) update the parameters) is what modern deep learning frameworks automate, at billion-parameter scale. When the dataset is huge, we will not even evaluate the loss on every example at each step: a small random batch provides an unbiased gradient estimate that is accurate enough to make steady progress. That refinement, stochastic gradient descent, is the subject of Chapter 4.
Twenty steps from one start, at one fixed learning rate. Will every step be the same length?
The chapter's own update rule, its start (−0.5, 2.0), its learning rate 0.25 and its twenty steps, run on the eight-point schematic dataset this panel declares.
The step shrank because the slope did. Nothing was scheduled and nothing was seen.
0:00 / 0:40
The calculation is readable without playback. Opening this panel loads the optional controls.
A quadratic bowl is the special case that makes mean squared error easy: a deep network's loss surface has no such bowl, and nothing drawn here is a measured training run.
Scope and caveats
This is full-batch gradient descent over every declared point, not the stochastic version Chapter 4 introduces. The contour view is a drawing device for the reader: the algorithm reads only the gradient at the point it stands on, and never sees a ring.
The dataset is schematic — eight points on the chapter's own generating line, with their spread declared in this panel — because the figure's sixty points are seeded and never printed. The path drawn here is therefore this panel's, not the figure's; the rule, the start (−0.5, 2.0), the learning rate 0.25, the twenty steps, the grid extents and the generating parameters are the chapter's.
Weight and bias are drawn at equal scale, so each arrow meets its contour at a right angle; the chapter's two-dimensional panel does not preserve that. Contour levels are equally spaced in loss, as the figure's twenty-five levels are, so crowded rings mean a steep surface and the open middle is what a flat bottom looks like, not missing data.
The star marks the data-generating parameters (2.5, −1.0), not this dataset's least-squares minimum, which sits 0.0158 lower in weight and 0.0063 higher in bias. Each bar carries the same number as the arrow beside the walker at that step; all twenty share one scale. No learning rate other than 0.25 is shown, and no claim is made here about what a larger one would do.
Check yourself. Move the start twice as far from the minimum, along the same direction. How does the first step change, and does the walker need more steps to arrive?
The first step doubles, to about 2.1097, because on a quadratic bowl the gradient is proportional to the displacement from the minimum. Doubling the start doubles every step and every position, so twenty steps still cover the same fraction of the distance.
Transcript and keyboard help
Predict. A walker stands at weight −0.5 and bias 2.0 on a loss surface it cannot see. Nothing is drawn but the point: no contours, no valley, no view of where the bottom is.
Feel the slope. The one thing available at a point is the local gradient. A dashed arrow grows from the walker's feet in the direction of steepest descent; its length, the gradient magnitude, is 4.2194.
Scale it by the learning rate. The solid arrow is the first quarter of the dashed one, because the learning rate is 0.25. Three ticks mark the quarters. The step it prescribes is 1.0548 long.
Take the step. The walker slides along the solid arrow and stops exactly at its tip, at weight 0.0502 and bias 1.1000. Will the next nineteen steps be this long?
Nine more steps. The same rule runs from each new point. Each completed step adds a bar to the shelf beside the plane; the bars are the step lengths, all on one scale.
Ten more steps, finishing the chapter's twenty. The arrows at the walker's head are now shorter than the walker itself. The last step is 0.0061 long and the walker rests at weight 2.4682 and bias −0.9816.
The contours appear, and the star at the data-generating parameters 2.5 and −1.0. The rings are crowded where the walk began and open out near the bottom. The walker never saw any of this.
Read the shelf. The first step was 1.0548 and the last 0.0061, about 172 times smaller, with the same rule and the same learning rate at every step. The step shrank because the slope did.
Silent; paused initially; 1.5× playback. Focus the animation pane: Space or K plays/pauses, arrows seek between beats, Home/End jump, Escape pauses. The scrubber and speed menu also work by keyboard. Reduced-motion mode shows one still per beat; a moving beat rests in the state its caption describes.
The 60-point problem above had two parameters, so we could draw its landscape and the path of gradient descent. Now we fit a regression model with two features and a bias to a new dataset, using both methods. Implementation 1 is the direct solve. Implementations 2 and 3 are gradient descent, written by hand and then with the PyTorch modules we will reuse for every later model. We then check whether the three computations give the same estimate.
TipCoding hygiene
Two habits are worth forming from the first cell: fix seeds so runs are reproducible, and annotate functions with types so shapes and interfaces stay readable. The cells in this book are short teaching examples that expose the mechanism and the checks behind each claim.
Load the chapter dependencies and establish reproducible state.
import torchimport matplotlib.pyplot as plt# [1]torch.manual_seed(6050);
First, synthetic data. We know the data-generating weights and bias, so we can compare each method’s estimate against them.
Define the reusable make_synthetic_data helper.
Generate noisy targets from known weights, then check the batch shapes.
# [1]def make_synthetic_data( weights: torch.Tensor, bias: float, n_samples: int, noise: float=0.1) ->tuple[torch.Tensor, torch.Tensor]:"""y = Xw + b + noise. Returns X: (n, d) and y: (n,).""" X = torch.randn(n_samples, len(weights)) y = X @ weights + bias + noise * torch.randn(n_samples)return X, y# [2]true_w, true_b = torch.tensor([2.0, -3.4]), 4.2X, y = make_synthetic_data(true_w, true_b, n_samples=200)X.shape, y.shape # always check your shapes
(torch.Size([200, 2]), torch.Size([200]))
Implementation 1: least squares
First append a column of ones to \(\featurepart{\matr{X}}\), so that the bias becomes the weight of a constant feature (the linear model section). Then call the least-squares routine:
Append a constant feature to represent the bias.
Solve least squares with a rank-aware library routine.
Compare the estimate with the planted parameters.
# [1]X_aug = torch.cat([X, torch.ones(X.shape[0], 1)], dim=1)# [2]w_ols = torch.linalg.lstsq(X_aug, y).solution# [3]print(f"closed form: w = {w_ols[:2].numpy().round(3)}, b = {w_ols[2]:.3f}")print(f"ground truth: w = {true_w.numpy()}, b = {true_b}")
closed form: w = [ 2.01 -3.402], b = 4.196
ground truth: w = [ 2. -3.4], b = 4.2
These two lines compute the least-squares estimate, which we compare with the planted parameters here and with the two iterative estimates below. lstsq handles rank and conditioning more reliably than explicitly forming \(\matr{X}^{\top}\matr{X}\).
Implementation 2: manual gradient descent
We write the model as a small class: a forward pass and an update step. Each step predicts, forms the error, and moves both parameters against the gradient of Equation 1.4, which we derived by hand.
Store the parameters and define the linear prediction.
Convert batch residuals into the exact MSE update.
Repeat that update until the loss settles.
Compare the learned parameters with the other solution.
Finally, we adopt the idiom you will use for every model from here on: nn.Linear stores the parameters, autograd computes their gradients, and the optimizer applies the update.
NoteA deliberate framework preview
This cell shows the complete PyTorch training loop so you can recognize its shape. We use the three framework calls as black boxes here: Chapter 3 introduces modules, Chapter 4 opens the optimizer, and Chapter 5 explains what backward() computes. Until then, the manual implementation above shows what the three calls do.
Pair a linear module with MSE and an SGD optimizer.
Repeat the framework forward, backward, and update sequence.
Detach and report the learned parameters.
from torch import nn# [1]net = nn.Linear(in_features=2, out_features=1)optimizer = torch.optim.SGD(net.parameters(), lr=0.1)loss_fn = nn.MSELoss()nn_losses = []# [2]for _ inrange(100): optimizer.zero_grad() # clear old gradients: they accumulate! loss = loss_fn(net(X).squeeze(-1), y) # (n, 1) -> (n) nn_losses.append(float(loss.detach())) loss.backward() # autograd feels the slope for us optimizer.step()w_nn = net.weight.detach().squeeze()b_nn = net.bias.item()# [3]print(f"nn.Linear: w = {w_nn.numpy().round(3)}, b = {b_nn:.3f}")
nn.Linear: w = [ 2.01 -3.402], b = 4.196
Each method leaves a loss record we can compare:
Collect the direct-solve and iterative loss records.
Figure 1.5: Three routes to the same loss floor. The closed form is a before-and-after solve, not an optimization trajectory; both gradient methods expose the sequence of corrective steps.
Loss-versus-step plots will recur throughout the book. They reveal whether an optimization process is descending, stalling, or diverging, and they make competing update rules comparable.
Three implementations, one answer:
Choose a one-dimensional slice through the two-feature data.
Evaluate each learned model along that same slice.
Plot the adjusted observations and all three fits.
# [1]grid = torch.linspace(X[:, 0].min(), X[:, 0].max(), 50)x2_mean = X[:, 1].mean()# [2]def prediction_slice(weights: torch.Tensor, bias: float) -> torch.Tensor:"""Predictions along x1 while x2 is held at its sample mean."""return weights[0] * grid + weights[1] * x2_mean + biasy_on_slice = y - true_w[1] * (X[:, 1] - x2_mean)plt.figure(figsize=(5.5, 3.6))# [3]plt.scatter(X[:, 0], y_on_slice, s=12, alpha=0.4, label="data adjusted to slice")plt.plot(grid, prediction_slice(w_ols, float(w_ols[2])), lw=3, label="closed form")plt.plot(grid, prediction_slice(model.w, model.b.item()), "--", lw=2, label="gradient descent")plt.plot(grid, prediction_slice(w_nn, b_nn), ":", lw=2, label="nn.Linear")plt.xlabel("$x_1$"); plt.ylabel("$y$"); plt.legend()plt.tight_layout()plt.show()
Figure 1.6: All three methods find the same line on the slice \(x_2 = \bar{x}_2\). Because this is synthetic data, the points can be adjusted to that same slice using the known true coefficient; line and points now show the same question.
The computation shared by all three implementations can also be drawn as a small circuit:
Figure 1.7: A linear model as a computation circuit: each blue input is scaled by an orange learnable weight, the signals and orange bias are added, and the green prediction leaves the circuit.
1.7 Why squared error? The maximum-likelihood view
Mean squared error is not an arbitrary penalty. Assume targets are generated by a linear process with additive Gaussian noise.6
The conditional distribution of \(\targetpart{y}\) given \(\featurepart{\vect{x}}\) is therefore a Gaussian centered at the deterministic prediction \(\predictionpart{\hat y}
=\parameterpart{\vect{w}^{\top}}\featurepart{\vect{x}}+\parameterpart{b}\):
Maximum likelihood asks which \((\parameterpart{\vect{w}},\parameterpart{b})\) make the observed dataset most probable. Independence makes the dataset likelihood the product of the per-example densities, \(\prod_{i=1}^{n} p(\targetpart{y_i}\mid\featurepart{\vect{x}_i};\parameterpart{\vect{w}},\parameterpart{b})\). The logarithm turns that product into a sum and brings the Gaussian exponent down:
Maximizing this log-likelihood is equivalent to minimizing the sum of squared residuals. A likelihood-derived loss is a probability model in disguise: we state how targets may vary around a prediction and take the negative log-likelihood.
Figure 1.8: The target type changes the conditional distribution and link function, but the maximum-likelihood recipe stays fixed. Gaussian continuous targets yield MSE, and Bernoulli binary targets yield binary cross-entropy.
The same recipe carries over to classification in Chapter 2. Continuous targets suggest a Gaussian likelihood and MSE. Binary and categorical targets suggest Bernoulli and categorical likelihoods and cross-entropy. A Laplace likelihood would instead produce absolute error. Choosing a loss is therefore a modeling decision: we make it by choosing a distribution for the targets.
1.8 A first look at bias and variance
A fitted model depends on the training set we happened to collect. To judge a fitting recipe, we therefore ask how its predictions would change if we collected the data again. A simulation answers this question. Take the curve \(f^*(x) = 0.25 + 0.75x + 0.85x^2\) as the truth, and repeat three steps 200 times:
draw 12 inputs uniformly from \([-1, 1]\);
set each target to \(f^*(x)\) plus Gaussian noise with standard deviation 0.32;
fit a straight line to the 12 points by least squares.
Each repetition gives a different line (the left panel of Figure 1.9). At a fixed input such as \(x_0 = 0.65\), the 200 predictions form a green distribution with a center and a spread (the middle panel, a vertical slice through the left one). The center can miss the black true curve, because a line cannot follow a parabola. The spread comes from the changing training sets. Fresh targets at \(x_0\) also scatter around the true curve, because of the noise.
Figure 1.9: Bias and variance from repeated fits. Left: forty of the 200 fits, each a straight line fitted to a fresh noisy dataset. One dataset is purple, the mean prediction is green, and the data-generating curve is black. The dotted line marks the slice at \(x_0=0.65\). Middle: on the same vertical scale, that slice becomes two distributions, the predictions at \(x_0\) (green) and fresh targets at \(x_0\) (gray). Bias is the distance from the truth to the mean prediction. The green and gray arrows each span \(\pm 1\) sample standard deviation, and the squares of these spreads are the variance and the irreducible noise. Right: the familiar U-curve, a schematic of the classical trade-off between the three terms as the model grows more flexible. Modern models can depart from it.
Now we formalize what the figure shows. Our learned predictor \(\predictionpart{\hat f_{\mathcal D}}\) depends on the random training set \(\mathcal D\). Let \(f^*(\featurepart{\vect{x}})
=\E[\targetpart{Y}\mid\featurepart{X}=\featurepart{\vect{x}}]\) be the regression function, and write the average learned prediction as \(\predictionpart{\bar f}(\featurepart{\vect{x}})
=\E_{\mathcal D}[\predictionpart{\hat f_{\mathcal D}}(\featurepart{\vect{x}})]\). Now fix an input \(\featurepart{\vect{x}}\) and draw a fresh target \(\targetpart{Y}\) at that input, independently of the training set. The error \(\predictionpart{\hat f_{\mathcal D}}(\featurepart{\vect{x}}) - \targetpart{Y}\) is random for two reasons: the training set \(\mathcal D\) varies, and so does \(\targetpart{Y}\). The average of its square over both sources of randomness has three parts:
The \(\residualpart{\text{bias}}\) term measures how far the \(\predictionpart{\text{average prediction}}\) is from the truth because of limiting assumptions like linearity: a simple model on complex data is systematically wrong (underfitting). The \(\predictionpart{\text{variance}}\) term measures how much the prediction would change if we collected a fresh training set (the model’s sensitivity to sampling noise). A complex model can fit the noise itself (overfitting). The \(\targetpart{\text{irreducible noise}}\) belongs to the data-generating process and cannot be learned away.
This is why we split data into training, validation, and test sets. We fit the model on the training set. The validation set is an independent sample from \(P\), so its average loss estimates each fitted model’s population risk \(R_P\) and referees the bias–variance trade-off. The test set stays untouched until the end.
WarningTrap: treating the U-shaped curve as a universal law
The textbook picture shows validation error falling and then rising as complexity grows. It is a helpful first mental model, but bias and variance need not move in opposite directions. In classical fixed-dimensional, well-specified settings, variance often falls roughly like \(1/n\) as data grows, and modern models need not follow that rate. Regularization and inductive biases matched to the problem can allow more capacity without a sharp rise in variance. An overparameterized network can even pass the interpolation threshold, the capacity at which it first fits the training set exactly, and then improve again as capacity grows. This second fall is called double descent. Chapter 6 tests the classical U-curve in a small width sweep and discusses double descent.
Regularization, briefly
We can already reduce variance with one change to the loss: a penalty on large weights. Ridge regression adds an \(L_2\) penalty,
nudging the model toward smaller, more stable weights: it accepts a little bias in exchange for less variance.7 The factor \(n\) is there because our data-fit term is a mean. This displayed solution applies when there is no intercept or when features and targets have been centered so the intercept is recovered separately. We normally do not penalize that intercept. In augmented-matrix notation, replace \(I\) by \(\operatorname{diag}(1,\ldots,1,0)\) so the final bias coordinate remains free.
To see the effect, we construct a dataset on which least squares is unstable. It has \(n = 25\) examples, each with \(d = 20\) features drawn from a standard normal distribution, so there are barely more examples than weights to fit. Only the first 5 features have nonzero planted weights. The other 15 have weight zero, the bias is zero, and Gaussian noise is added to each target. With so few examples per weight, the ordinary least-squares (OLS) estimate varies a lot from one dataset to the next, and it can give sizable weights to the 15 features that do not affect the target.
Create a small-sample problem with many irrelevant features.
Solve the same data with unregularized and ridge estimators.
We score each estimate by its weight MSE, the mean squared difference between the estimated and planted weights. Ridge shrinks every weight toward zero and reduces the weight MSE from 1.2347 for OLS to 0.4400. These numbers come from a single draw of the data, taken from the random stream of the runs above, with \(\lambda\) set by hand. Another draw would give other numbers, and separating the gain into bias and variance would require repeating the experiment across fresh datasets, as in Figure 1.9. (Rerun this cell with n = 100 and watch OLS become more stable, as classical fixed-dimensional theory predicts.) In later chapters, the same \(L_2\) idea returns as weight decay in large neural networks.
NoteCheck yourself
Close the book for one minute and answer these questions from memory.
What are the model, loss, and update rule in linear regression?
Why do fitted predictions lie in the column space of the data matrix?
When do the closed form, scratch loop, and PyTorch module represent the same estimator?
Watch the mechanism: the same nudge, a longer weight
One identical sideways nudge is applied to a short weight vector and to a long one. Which turns further?
A schematic reading of this section's footnote on ridge regression, which states that the same nudge rotates a larger vector less and that weight decay shrinks a weight along its own direction.
A radial shrink restores steering. It does not by itself explain or cure stalled training.
0:00 / 0:40
The calculation is readable without playback. Opening this panel loads the optional controls.
This scene shows steering, not stalling: the radial shrink limits scale and can preserve angular responsiveness, and it does not by itself explain or cure stalled training.
Scope and caveats
The chapter writes the angle relation with an approximately-equals sign, because it is the small-angle form of the exact turn. This picture draws the exact angle instead, the arctangent of the nudge divided by the length, and computes every printed angle that way. The two agree closely where the chapter applies them — for the long weight the linear estimate reads 6.88 degrees against an exact 6.84 — and visibly disagree for the short one, 34.38 against 30.96, because a nudge six tenths as long as the weight is not a small update. Read the arctangent as the drawn geometry and the chapter's relation as the statement it approximates.
Decay changes scale, not direction: the long tip slides back along its own ray and the dashed stub marks where it came from. Nothing here is trained, no data enters, and no gradient is measured. The nudge is stipulated perpendicular; a real update is only nearly so, and its size is not held fixed while the weights grow. The two lengths, the nudge, and the learning rate and penalty behind the shrink factor are declared computed variants, not manuscript numbers; a realistic per-step factor is far closer to one, so the contraction drawn here as one step accumulates over many. The chapter also notes that the intercept is normally left unpenalized, and bias and normalization parameters are commonly exempted from decay in the same way. Orange is the learnable weight, wine the update that carries the loss gradient, grey the fixed direction and the scenery.
Check yourself. A layer's weights grow ten times longer while the gradient keeps the same size. With η = 0.1 and λ = 0.01, how many weight-decay steps alone would restore the original turning angle?
About 1151 steps. Each multiplies the weight by 1 − 2ηλ = 0.998, and the angle follows one over the length, so the length must fall tenfold; repeated multiplication by 0.998 first drops below one tenth at step 1151. The scene's single 0.40 factor stands in for that slow accumulation.
Transcript and keyboard help
Predict. Two weight vectors lie on one shared direction, a short one of length 1.00 and a long one of length 5.00. A grey ray marks the direction they share. No nudge has been applied yet.
Nudge the short vector. A perpendicular update of length 0.60 lifts its tip, and the vector turns through 30.96 degrees, the arctangent of 0.60 divided by 1.00. The same nudge goes to the long tip next: more, less, or the same turn?
Carry the same nudge. The update slides along the shared direction to the long tip, keeping its length exactly. A thin wine tick records where it was applied before. The long vector has not moved.
Nudge the long vector. The identical update lifts its tip by the same 0.60, and the vector turns through 6.84 degrees, the arctangent of 0.60 divided by 5.00.
Compare. A dashed line joins the two lifted tips: both moved sideways by exactly the same amount. The short vector turned 4.53 times as far. Length alone set the angle; the update never changed.
Shorten the weight. The long vector's length falls to 3.00 and the same nudge now turns it through 11.31 degrees. The length slider drives this; you may drag it yourself.
Introduce weight decay. The update rule multiplies the weight by one minus twice the learning rate times the penalty, here 0.40, before the data gradient is subtracted. Nothing has moved yet.
Apply the shrink. The long tip slides back along its own ray from 5.00 to 2.00, the direction unchanged, and a dashed stub marks where it was. The same nudge now turns it through 16.70 degrees, 2.44 times the angle before decay. This is angular responsiveness preserved, not an explanation or a cure for stalled training.
Silent; paused initially; 1.5× playback. Focus the animation pane: Space or K plays/pauses, arrows seek between beats, Home/End jump, Escape pauses. The scrubber and speed menu also work by keyboard. The length slider pauses playback and recomputes the picture; its arrow keys change the length, not the time. Play or a timeline seek returns the length to the recorded sweep. Reduced-motion mode holds each beat's finished state.
1.9 Okay, so: the simplest model establishes the learning framework
Learning a function from examples used these components:
A model family: hyperplanes parameterized by knobs \(\vect{w}, b\), with the bias absorbed into the weight vector when compact notation helps.
A loss: MSE, which is maximum likelihood under Gaussian noise and converts prediction error into the scalar signal that guides every update.
A fitting procedure: solve least squares directly, or approach its solution through gradient updates.
The generalization lens: bias vs. variance, the data splits that referee them, and regularization as a first countermeasure to overfitting.
One reframing will carry the whole book. A neuron computes the same weighted sum and then applies a fixed function \(\sigma\), its activation. Linear regression is the neuron whose activation is the identity, \(\sigma(z) = z\):
First, in Chapter 2, a sigmoid activation turns our regressor into a classifier. Then, in Chapter 3, we stack neurons and discover why the nonlinearity is not optional.
TipThe first “make it learnable” step
We first saw the geometry of the linear response in Figure 1.2. Now we can name its neural-network form: a neuron with the identity activation. The model–loss–gradient–update pattern carries over, while the particular loss and derivatives change with the model. The nonlinearity is the first ingredient that expands what the model can learn.
(Pencil.) Expand \(\norm{\vect{y}-\matr{X}\vect{w}}_2^2\) term by term and differentiate it with respect to \(\vect{w}\) to recover the gradient displayed before Equation 1.2. Then rearrange it into Equation 1.2. This derivation does not require an inverse. Then state what becomes unique when \(\matr{X}\) has full column rank and what remains unique when it is rank deficient (rank below \(d\), as when \(d > n\)).
(Pencil.) Repeat the derivation with the ridge penalty \(\lambda\norm{\vect{w}}_2^2\) and show the solution becomes \((\matr{X}^\top\matr{X} + n\lambda I)^{-1}\matr{X}^\top\vect{y}\) when the data-fit term is the MSE. Why does the \(n\lambda I\) term guarantee invertibility for any \(\lambda > 0\)? If you augment \(\matr{X}\) with a bias column, which diagonal entry should be zero so the intercept is not penalized?
(Code.) In make_synthetic_data, raise noise to 1.0 and draw 10 training sets with different seeds. Fit each with the closed form. Because the three implementations above yield the same weights, one is enough. How much do the learned weights vary across training sets? The noise you raised sets the irreducible-noise term of Equation 1.5. Which term measures the spread you observed, and how does higher label noise inflate it?
(Code.) Set the learning rate in LinearRegressionScratch to 1.0 and rerun. Describe what the loss curve does, and explain it using the blindfolded-descent picture.
(Code.) In the ridge experiment, sweep \(\lambda \in \{0.01, 0.1, 1, 10, 100\}\) and plot both weight MSE and \(\norm{\vect{w}}_2\) against \(\lambda\) on a logarithmic \(\lambda\) axis (for example, plt.semilogx). Fix a seed before generating the data so the sweep is reproducible. Your numbers will differ from the chapter’s single draw. Which value in the sweep minimizes the weight MSE, and what happens to error and weight scale at the two extremes? Connect your answer to bias and variance.
In Part II, an image filter will slide this same dot product across an image. In Part IV, attention will build learned similarities between queries and keys from the same primitive.↩︎
Across all \(n\) examples stacked in the data matrix \(\featurepart{\matr{X}}\in\R^{n\times d}\), the predictions \(\predictionpart{\hat{\vect{y}}} = \featurepart{\matr{X}}\parameterpart{\vect{w}} + \parameterpart{b}\vect{1}\) likewise become \(\predictionpart{\hat{\vect{y}}} = \featurepart{\matr{X}}\parameterpart{\vect{w}}\) after appending a column of ones \(\vect{1}\) to \(\featurepart{\matr{X}}\). This is called bias augmentation or homogeneous coordinates. Geometrically, lifting the problem to \(\R^{d+1}\) anchors the hyperplane to the origin. Every model adjustment then rotates or rescales one weight vector about the origin, with no separate translation.↩︎
Two additional numerical hurdles make forming and inverting \(\featurepart{\matr{X}}^\top\featurepart{\matr{X}}\) impractical in software. You can skip these details without losing the conceptual thread. First, forming \(\featurepart{\matr{X}}^\top\featurepart{\matr{X}}\) explicitly squares the condition number, doubling the digits of precision that rounding can destroy (Appendix A and Appendix C). Second, exact inversion scales cubically as \(O(d^3)\) and storing the square matrix takes \(O(d^2)\) memory. At a million parameters, that matrix alone would hold a trillion entries. Robust numerical libraries therefore bypass the normal equations and factor rectangular data directly, as in Implementation 1 below.↩︎
The same reading holds for kernel ridge regression in a reproducing kernel Hilbert space: each prediction is again a fixed weighted combination of the training targets, and, as in least squares, some of those weights can be negative.↩︎
In ordinary least squares, these mixing weights are fixed globally, and some can be negative. In Part IV (Chapter 14 and Chapter 17), we reopen this exact target-mixing equation. Replacing this rigid projection with a localized, positive similarity score connects linear regression directly to Nadaraya–Watson kernel regression and the modern attention mechanism, which forces the mixing weights to be nonnegative and sum to one.↩︎
This is more than algebraic convenience. A residual often aggregates many small, unobserved effects, such as sensor variation, environmental fluctuations, omitted features, and rounding. Under the conditions of the central limit theorem, sums of many independent or weakly dependent finite-variance effects become approximately Gaussian. There is also an informational argument: among continuous distributions with a fixed mean and variance, the Gaussian has maximum differential entropy, so it adds no further structure beyond those two constraints. Neither argument makes every residual Gaussian. The assumption is a useful model, and its fit to the data should be checked.↩︎
For a small update nearly perpendicular to \(\vect{w}\), the rotation angle is \(\Delta\varphi\approx
\norm{\Delta\vect{w}_{\perp}}_2/\norm{\vect{w}}_2\): the same nudge rotates a larger vector less. The \(L_2\) penalty adds \(2\lambda\vect{w}\) to the gradient, so a gradient step becomes \(\vect{w}\leftarrow(1-2\eta\lambda)\vect{w}
-\eta\nabla\loss_{\mathrm{data}}\). The first factor shrinks \(\vect{w}\) along its own direction. A shorter weight vector turns further under the same nudge, so the shrink keeps later updates able to change the weight’s direction.↩︎