11  Lesson 3: Optimization and Regularization

From a loss function to parameter updates and generalization

Author

Pedro Gomes

12 Optimization and Regularization

12.1 Learning Goals

After studying this chapter, you should be able to:

  • express model fitting as an optimization problem and distinguish parameters from hyperparameters;
  • calculate and interpret a gradient-descent update;
  • explain mini-batch gradients, momentum, and the purpose of adaptive updates;
  • distinguish an optimization difficulty from evidence of overfitting;
  • derive an L2-regularized update and explain why AdamW treats weight decay separately;
  • use validation data to compare training choices without using the test set for selection.

We assume familiarity with linear regression, classification losses, vectors, and basic derivatives. Partial derivatives are introduced here. We do not assume knowledge of neural-network backpropagation, which will be discussed in the next chapter. All executable examples use derivatives that we can calculate directly.

12.2 What is Optimization?

Suppose we have chosen a linear regression model and a squared-error loss. We can calculate a prediction and measure its error. But an arbitrary line will usually make poor predictions. How should we change its slope and intercept?

Optimization is the process of choosing values of variables to improve an objective. You do this all the time: when you pick a route to the university, you have many routes to choose from, a way to measure each one (say, the travel time), and you want the route where that measurement is as small as possible. Every optimization problem has these same two ingredients: something we can adjust, and a number that tells us how good the current choice is. In transport planning, variables might describe routes and the objective might measure cost. In engineering, a design might minimize material use while meeting a strength requirement. In supervised learning, the variables are usually model parameters and the objective measures how well predictions fit training examples. Different fields give this same structure different names, but the pattern is the same: adjustable variables and an objective to optimize. Sometimes there are also what we call constraints, which are restrictions that limit the values of variables. Most of the optimization problems we study here are unconstrained, meaning the variables can take any value, but it’s worth knowing the term.

In mathematics, we describe the adjustable quantities by a list of numbers \(\theta = (\theta_1, \dots, \theta_d)\), and the quality of a choice by a function \(f(\theta)\), called the objective function, which we define so that smaller is better. Optimization is then the task of finding the \(\theta\) that makes \(f(\theta)\) as small as possible, which we write as

\[ \theta^* = \arg\min_{\theta} f(\theta). \]

Here \(\arg\min\) simply means “the value of \(\theta\) at which \(f\) is smallest”.

Optimization does not know which patterns are meaningful. It follows the objective and the data supplied to it. A model can therefore become better at the training task while becoming worse on new examples. This chapter asks two connected questions:

  1. How can we find parameters that reduce the training objective?
  2. How can we guide and evaluate learning so that the fitted model is useful beyond the training data?

Keep these terms separate: the model determines which functions can be represented; the loss measures prediction error; the data pipeline determines the examples and transformations seen during training; the optimizer determines parameter updates; and evaluation tests whether the result meets the task’s requirements.

12.3 Model Fitting as an Optimization Problem

12.3.1 From individual errors to a training objective

Let’s return to our regression example. As we have previously seen in Chapter 1, we can define a model \(f_\theta\) (a function parameterized by \(\theta\)), and \(f_\theta(x_i)\) is our prediction for input \(x_i\). For a line we have \(\theta = (w, b)\) and \(f_\theta(x_i) = w x_i + b\).

To measure “how wrong” a single prediction is, we use a loss function \(\ell(f_\theta(x_i), y_i)\), a number that is small when the prediction is close to the true value and large when it is far off. For regression, a common choice is the squared error: \(\ell(f_\theta(x_i), y_i) = (f_\theta(x_i) - y_i)^2\).

A single example tells us little about how good \(\theta\) is overall, so we average the loss over the whole dataset. This gives the training objective, or empirical loss:

\[ L_{\mathrm{train}}(\theta) = \frac{1}{n}\sum_{i=1}^{n} \ell(f_\theta(x_i), y_i). \tag{12.1}\]

This is exactly an objective function in the sense of Section 12.2: \(\theta\) is what we adjust, \(L_{\mathrm{train}}(\theta)\) is the number we want to make small (minimize), and there are no constraints on \(\theta\) here. Fitting a model to data is therefore the optimization problem

\[ \theta^* = \arg\min_\theta L_{\mathrm{train}}(\theta). \tag{12.2}\]

We’ll use squared error throughout this chapter, since it’s the standard choice for regression; other tasks, like classification, call for different loss functions, as introduced in the preceding classification chapter.

12.3.2 Analytical and iterative solutions

For some models, \(\theta^*\) can be computed directly. Linear regression with squared error is one such case: minimizing \(L_{\mathrm{train}}\) leads to a system of linear equations, the normal equations, whose solution can be written in closed form as \(\theta^* = (X^\top X)^{-1} X^\top y\), provided \(X\) has full column rank. Here \(X\) collects the input features and \(y\) the targets. In practice, use a least-squares solver rather than explicitly computing the inverse; rank-deficient problems also admit least-squares solutions, but their coefficients need not be unique.

This is the exception rather than the rule. Most models used in practice, including neural networks, have a loss \(L_{\mathrm{train}}(\theta)\) for which no such formula exists: the equation \(\nabla L_{\mathrm{train}}(\theta) = 0\) (we will come back to what \(\nabla\) means in the next section) is too complicated to solve directly, or the model is not linear in its parameters. In these cases, we must find \(\theta^*\) iteratively: starting from some initial guess \(\theta_0\), we repeatedly adjust it, producing a sequence \(\theta_0, \theta_1, \theta_2, \dots\) that we hope gets closer and closer to a minimizer.

Iterative methods are not only a fallback for hard problems. Even for linear regression, forming \(X^\top X\) and solving the resulting system can become expensive: the matrix size grows with the number of parameters, while forming it also requires processing the examples. In such cases, an iterative method can reach a good solution faster than the exact formula, despite the problem having a closed-form answer. This is why iterative optimization is the default approach throughout deep learning, and is central to this chapter.

12.3.3 Visualizing the objective

Because \(L_{\mathrm{train}}\) is just a function of \(\theta\), we can plot it like any other function.

One parameter. Suppose we fix the intercept \(b\) and only let the slope \(w\) vary. Then \(L_{\mathrm{train}}(w)\) is a function of a single number, and we can plot it as a curve: \(w\) on the horizontal axis, \(L_{\mathrm{train}}(w)\) on the vertical axis. For linear regression with squared error, this curve is a parabola, with its lowest point at the best value of \(w\).

Three panels show six observations near y equals 2x, candidate lines with slopes 1, 1.7, and 2.5, and a bowl-shaped loss curve with its minimum near slope 2.
Figure 12.1: From observations to an optimization problem. Left: six synthetic observations. Middle: three candidate slopes for the model ŷ = wx. Right: the loss associated with each slope, using matching colors. The black star marks the minimum over all possible slopes, not just the three candidates.

Two parameters. Now let both \(w\) and \(b\) vary. \(L_{\mathrm{train}}(w, b)\) is a function of two numbers, so its graph would be a surface in three dimensions — height above the \((w, b)\)-plane. Surfaces are harder to draw clearly, so instead we typically use a contour plot: a two-dimensional picture where each curve connects points \((w, b)\) with the same loss value, similar to elevation lines on a topographic map. The minimizer \(\theta^*\) sits at the center of the innermost contour, where the loss is lowest.

A parabola with minimum at w equals 1 beside a bowl-shaped surface with minimum at w1 equals 1 and w2 equals minus 1. A blue cross-section connects the two representations.
Figure 12.2: One parameter produces a loss curve; two parameters produce a loss surface. The blue curve on the surface fixes w₂ = −1 and reproduces the one-parameter curve on the left. Orange stars mark the minima. These illustrative quadratic objectives are not calculated from the earlier dataset.

We call this surface, or its contour plot, the loss landscape. For linear regression with squared error, the landscape is bowl-shaped, with a single lowest point. This is visible evidence of the fact that this loss is convex. Later in the chapter we will see landscapes that are far less simple, with multiple valleys, ridges, and flat regions, and this is precisely what makes optimization in deep learning difficult.

12.4 Mathematical Bridge: Gradients and Local Improvement

12.4.1 From derivatives to gradients

Recall from single-variable calculus that the derivative of a function \(g(w)\) at a point \(w\), written \(g'(w)\), tells us the slope of \(g\) at that point: how much \(g(w)\) changes for a small change in \(w\). If \(g'(w) > 0\), increasing \(w\) slightly increases \(g(w)\); if \(g'(w) < 0\), increasing \(w\) decreases \(g(w)\). This is exactly the information we’d want in order to improve our loss curve: at any point \(w\), the derivative \(L_{\mathrm{train}}'(w)\) tells us which direction to move \(w\) in to make the loss smaller.

Once we have more than one parameter, say \(\theta = (w, b)\), we ask a slightly different question: how does \(L_{\mathrm{train}}(w, b)\) change if we move only \(w\), holding \(b\) fixed? This is the partial derivative of \(L_{\mathrm{train}}\) with respect to \(w\), written \(\dfrac{\partial L_{\mathrm{train}}}{\partial w}\). It is computed exactly like an ordinary derivative, treating every other parameter as a constant. Likewise, \(\dfrac{\partial L_{\mathrm{train}}}{\partial b}\) tells us how the loss changes if we move only \(b\).

Collecting all partial derivatives into a single vector gives the gradient of \(L_{\mathrm{train}}\) at \(\theta\):

\[ \nabla L_{\mathrm{train}}(\theta) = \left( \frac{\partial L_{\mathrm{train}}}{\partial w}, \; \frac{\partial L_{\mathrm{train}}}{\partial b} \right). \tag{12.3}\]

More generally, for \(\theta = (\theta_1, \dots, \theta_d)\), the gradient is the vector of all \(d\) partial derivatives, \(\nabla L_{\mathrm{train}}(\theta) = \left(\frac{\partial L_{\mathrm{train}}}{\partial \theta_1}, \dots, \frac{\partial L_{\mathrm{train}}}{\partial \theta_d}\right)\). The gradient lives in the same space as \(\theta\) itself, meaning it has the same number of components as \(\theta\), and it points in the direction in which \(L_{\mathrm{train}}\) increases fastest at that point. Intuitively, if the loss landscape is a hilly surface, the gradient at a point \(\theta\) points uphill, in the steepest direction available.

12.4.2 Why move against the gradient?

The gradient tells us the direction of steepest increase, but training wants to decrease the loss. To see why moving against the gradient helps, we use a local linear approximation: for a small step \(\Delta\theta\) away from \(\theta\),

\[ L(\theta + \Delta\theta) \approx L(\theta) + \nabla L(\theta)^\top \Delta\theta. \]

This equation says something simple: near \(\theta\), the loss changes by roughly a fixed amount for every small step we take, and that amount depends on which direction we step in. This is the same idea as a tangent line approximating a curve close to a point, just generalized to more than one parameter.

Note. This is the first-order Taylor approximation of \(L\) around \(\theta\). Higher-order approximations exist; for instance, a second-order approximation additionally uses the matrix of second derivatives (the Hessian) and some optimizers exploit these for faster convergence.

We want to pick a step \(\Delta\theta\) that makes the loss go down, so we want \(\nabla L(\theta)^\top \Delta\theta\) to be as negative as possible. For a nonzero gradient, among all steps of a given Euclidean length, this quantity is smallest (most negative) when \(\Delta\theta\) points exactly opposite to \(\nabla L(\theta)\). In other words, stepping against the gradient gives the greatest decrease predicted by the local linear approximation.

To compare directions fairly, keep the step length fixed. Write \(\Delta\theta=\varepsilon u\), where \(\varepsilon>0\) is the length and \(\|u\|_2=1\). Here \(\|\cdot\|_2\) denotes Euclidean length. The predicted change in loss is then \(\varepsilon\,\nabla L(\theta)^\top u\). Since \(\varepsilon\) is fixed and positive, we only need to find the direction \(u\) that makes the dot product smallest.

The Cauchy–Schwarz inequality says that \(|a^\top b|\leq\|a\|_2\|b\|_2\): the absolute value of a dot product cannot exceed the product of the vectors’ lengths. Applying it here gives

\[ |\nabla L(\theta)^\top u| \leq \|\nabla L(\theta)\|_2\|u\|_2 =\|\nabla L(\theta)\|_2. \]

Therefore the dot product cannot be smaller than \(-\|\nabla L(\theta)\|_2\). For a nonzero gradient, choose the unit vector pointing directly against it:

\[ u^*=-\frac{\nabla L(\theta)}{\|\nabla L(\theta)\|_2}. \]

Substituting this direction shows that it reaches the lower bound:

\[ \nabla L(\theta)^\top u^* =-\frac{\|\nabla L(\theta)\|_2^2}{\|\nabla L(\theta)\|_2} =-\|\nabla L(\theta)\|_2. \]

No other unit direction can give a smaller dot product. This proves the claim for the local linear approximation, not for arbitrarily large steps on the actual loss surface. If the gradient is zero, every direction gives a zero first-order change; the normalized expression above is then undefined.

This gives us the update rule at the heart of this chapter:

\[ \Delta\theta = -\eta\, \nabla L(\theta), \]

for some small positive step size \(\eta\) (the learning rate). For a nonzero gradient and a fixed Euclidean step length, this is the steepest descent direction in the first-order approximation. Other directions can also decrease the loss; the learning rate must still be small enough for the local approximation to be useful.

The update uses the same direction as the normalized vector in the proof, but its length is \(\|\Delta\theta\|_2=\eta\|\nabla L(\theta)\|_2\). Thus the learning rate scales the gradient; it is not itself the distance moved.

12.4.3 Understanding the landscape

The rule “move against the gradient” naturally stops when the gradient is zero: if \(\nabla L(\theta) = 0\), the local linear approximation predicts no change in \(L\) for a small step in any direction, so there is no direction of steepest descent to follow. A point where \(\nabla L(\theta) = 0\) is called a stationary point. For a differentiable objective at an unconstrained interior minimum, a zero gradient is a necessary condition, but not a sufficient one — plenty of stationary points are not minima at all.

Contours of a two-parameter objective with a global minimum at (1, 0), a local minimum at (-1, 0), and a saddle at (-0.3, 0). The saddle curves downward horizontally and upward vertically.
Figure 12.3: Synthetic landscape L(u,v) = u⁴/4 + u³/10 − u²/2 − 3u/10 + v²/2 + 1. Its three stationary points are marked at their exact locations. The additive constant keeps the displayed loss positive without changing the gradients.

Looking at this loss landscape, we can distinguish several cases:

  • A local minimum: a point where \(L(\theta)\) is lower than all nearby points, though not necessarily the lowest point in the entire domain.
  • A global minimum: a point where \(L(\theta)\) is lower than every other point in the domain. This is the \(\theta^*\) we ultimately want.
  • A saddle point: a stationary point that is a minimum along some directions and a maximum along others, so the surface curves up in one direction and down in another.
  • A local or global maximum (not pictured): a stationary point that is higher than all nearby (or all) points. These are rarely relevant when minimizing a loss, but they satisfy \(\nabla L(\theta) = 0\) just as minima do.

For linear regression with squared error, the loss is convex: every stationary point is a global minimum. The fitted parameters are unique when the design matrix has full column rank; otherwise several parameter vectors may minimize the loss. Gradient descent still requires a suitable learning rate to converge.

Note. Formally, \(L\) is convex if for all \(\theta_1, \theta_2\) and all \(\lambda \in [0,1]\), \(L(\lambda\theta_1 + (1-\lambda)\theta_2) \le \lambda L(\theta_1) + (1-\lambda) L(\theta_2)\). Geometrically, the line segment connecting any two points on the surface never dips below the surface itself. Convex functions can be shown to have no local minima that aren’t also global minima.

This is a special property, not the general case. Once we move to more complex models, loss landscapes typically have many stationary points and a zero gradient no longer tells us we have found the best solution, only that we have stopped moving.

12.5 Gradient Descent and the Learning Rate

12.5.1 Calculate an update

Section 12.4 established that \(-\nabla L(\theta)\) is, locally, the best direction to move in to decrease the loss. Gradient descent turns this into an algorithm by repeating the step over and over: starting from an initial guess \(\theta_0\), we generate a sequence of parameters

\[ \theta_{t+1} = \theta_t - \eta_t \nabla L_{\mathrm{train}}(\theta_t), \tag{12.4}\]

where \(t = 0, 1, 2, \dots\) indexes the iteration, and \(\eta_t\) is the learning rate at that iteration (for now, take \(\eta_t = \eta\) to be a fixed constant; we revisit why it might change with \(t\) in the next section). At each step, we compute the gradient at the current parameters, take a step of size \(\eta\) in the opposite direction, and repeat. Each iteration nudges \(\theta\) a little further downhill in the loss landscape.

NoteExample

Let’s calculate a few updates by hand using the dataset behind our regression figure: \(x = (1,2,3,4,5,6)\) and \(y = (2.3, 3.6, 6.2, 7.7, 10.4, 11.8)\). We fit \(f_\theta(x) = wx\), with

\[L_{\mathrm{train}}(w) = \frac{1}{2n}\sum_{i=1}^n (wx_i - y_i)^2, \qquad \frac{\partial L_{\mathrm{train}}}{\partial w} = \frac{1}{n}\sum_{i=1}^n (wx_i - y_i)x_i.\]

(We use half squared mean error here to facilitate the derivative). Starting at \(w_0 = 1.0\) with a learning rate \(\eta = 0.01\):

\(t\) \(w_t\) \(\nabla L_{\mathrm{train}}(w_t)\) \(w_{t+1} = w_t - \eta\nabla L_{\mathrm{train}}(w_t)\)
0 1.00 \(-15.12\) \(1.00 - 0.01(-15.12) = 1.15\)
1 1.15 \(-12.82\) \(1.15 - 0.01(-12.82) = 1.28\)
2 1.28 \(-10.88\) \(1.28 - 0.01(-10.88) = 1.39\)

Two things to notice: \(w_t\) moves steadily toward the minimizer \(w^* \approx 2.00\) from our regression example, and the gradient shrinks in magnitude at each step. This is expected, since, as we discussed, \(\nabla L_{\mathrm{train}}(w^*) = 0\) at the minimizer, so the steps naturally get smaller as \(w_t\) approaches it.

This loss curve is fairly steep. We can quantify this with the curvature of \(L_{\mathrm{train}}(w)\) (its second derivative), \(\dfrac{\partial^2 L_{\mathrm{train}}}{\partial w^2} = \dfrac{1}{n}\sum_i x_i^2\), which for this dataset is \(\approx 15.17\). A curvature this high means the loss rises steeply as \(w\) moves away from \(w^*\), so a step size that would be reasonable for a shallower bowl can easily overshoot here. Concretely: with \(\eta = 0.1\) instead of \(0.01\), the very first update would overshoot the minimum entirely: \(w_1 = 1.00 - 0.1(-15.12) = 2.51\), already past \(w^* \approx 2.00\). We’ll see exactly this kind of behavior, and why it connects to curvature, in the next section.

NoteCode Example

Here is a simple implementation of the same updates in Python using PyTorch. The code defines the loss and gradient functions, then iteratively updates the slope \(w\) using gradient descent. After three updates, it prints the current value of \(w\), the gradient, and the loss.

import torch

x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], dtype=torch.float64)
y = torch.tensor([2.3, 3.6, 6.2, 7.7, 10.4, 11.8], dtype=torch.float64)

def line_loss(w):
    return 0.5 * ((w * x - y) ** 2).mean()

def line_gradient(w):
    return ((w * x - y) * x).mean()

w = torch.tensor(1.0, dtype=torch.float64)
eta = 0.01
for step in range(3):
    gradient = line_gradient(w)
    w = w - eta * gradient
    print(f"Update {step + 1}: w={w.item():.5f}, grad={gradient.item():.5f}, loss={line_loss(w).item():.5f}")

assert torch.isclose(w, torch.tensor(1.38819, dtype=w.dtype), atol=1e-4)
Update 1: w=1.15117, grad=-15.11667, loss=5.46982
Update 2: w=1.27941, grad=-12.82397, loss=3.94999
Update 3: w=1.38820, grad=-10.87900, loss=2.85621

12.5.2 Small steps, overshooting, and divergence

The learning rate \(\eta\) controls how large each step is, and getting it right matters more than it might first appear. Using the 1D loss curve in Figure 12.1 as a picture, four behaviors are possible:

  • Slow progress (\(\eta\) too small): each step barely moves \(w_t\), and many iterations are needed to get close to \(w^*\). The direction is always correct, but progress is wastefully slow.
  • Effective progress (\(\eta\) well chosen): \(w_t\) approaches \(w^*\) in relatively few steps, without overshooting significantly.
  • Oscillation (\(\eta\) too large): each step overshoots the minimum, landing on the opposite side of the curve, then overshoots again on the way back. The parameter \(w_t\) alternates around \(w^*\); for this quadratic in the convergent regime, the loss itself decreases monotonically.
  • Divergence (\(\eta\) far too large): each overshoot is worse than the last, and \(L_{\mathrm{train}}(w_t)\) increases without bound rather than converging.

For our quadratic loss, we can make this precise rather than just qualitative. Write \(c = \frac{1}{n}\sum_i x_i^2\) for the curvature (we previously computed \(c\approx 15.17\) for our dataset). One can show that the signed error relative to the minimizer is multiplied by \((1-\eta c)\) at every step:

\[ w_{t+1} - w^* = (1-\eta c)(w_t - w^*). \]

This single factor explains all four behaviors: if \(\eta\) is small enough that \(0 < \eta c < 1\), \(w_t\) approaches \(w^*\) steadily from the same side (slow progress for very small \(\eta\), effective progress as \(\eta\) increases toward this boundary); once \(\eta c\) exceeds 1, the factor turns negative and each step overshoots to the opposite side (oscillation), though the swings still shrink as long as \(\eta c < 2\); beyond that, \(\eta c > 2\), the swings grow instead of shrinking, and the sequence diverges. For our dataset, this means \(\eta < 1/c \approx 0.066\) for monotonic convergence, and \(\eta > 2/c \approx 0.132\) before the process genuinely diverges. Our earlier example with \(\eta=0.1\) overshoots the minimum but is still in the convergent, oscillating regime, not the divergent one.

The following figure illustrates these same three regimes, using a separate, simpler regression example chosen purely to make the differences easy to see (its curvature is \(c=2.5\), gentler than our previous example). The three learning rates shown, \(\eta = 0.1\), \(0.6\), and \(0.85\), were chosen to fall one in each regime: slow/effective progress, oscillating and diverging.

Parameter and log-loss trajectories for a toy quadratic objective: learning rates 0.1 and 0.6 converge to slope 2, while 0.85 oscillates with increasing magnitude and diverges.
Figure 12.4: A separate, simpler regression example (not the dataset from our regression example), chosen so the three regimes from Section 12.5 are easy to see: a small learning rate converges steadily, a larger one oscillates while still converging, and a larger one still diverges. The underlying mechanics are identical to our worked example, just with a gentler curvature, which makes the differences visually clearer over a short number of updates.

Why does the useful learning rate depend on curvature at all? Where the loss curve is steep and narrow (large \(c\)), a fixed \(\eta\) produces a large step in \(w\)-space relative to how close the minimum is, making overshoot likely; where the curve is shallow and wide (small \(c\)), the same \(\eta\) makes cautious, slow progress. This is why no single learning rate is “correct” in general, as the right value depends on the curvature of the objective itself, and in multiple dimensions, different parameters can effectively have different curvatures, which is one of the motivations for the adaptive methods in Section 12.7.

12.6 Stochastic and Mini-Batch Optimization

12.6.1 How much data does one update use?

Computing \(\nabla L_{\mathrm{train}}(\theta)\) exactly requires summing over all \(n\) training examples, as in the definition \(L_{\mathrm{train}}(\theta) = \frac{1}{n}\sum_{i=1}^n \ell(f_\theta(x_i), y_i)\). An update that uses the full sum, as in Section 12.5, is called full-batch gradient descent. For small datasets like ours, this is cheap, but real datasets can have millions of examples, and recomputing the exact gradient at every single step becomes expensive.

An alternative is to estimate the gradient using only a subset of the data. At one extreme, stochastic gradient descent (SGD) picks a single example \(i\) at random and computes \(\nabla \ell(f_\theta(x_i), y_i)\) as a stand-in for \(\nabla L_{\mathrm{train}}(\theta)\). (Some texts and libraries, including PyTorch’s optim.SGD, use “SGD” loosely to mean any gradient descent using a randomly sampled subset of the data, whether that subset has size 1 or larger. We’ll follow that broader convention going forward and use “mini-batch” only when the batch size matters to the point being made.) This is far cheaper per step, but the resulting direction is noisy: it points, on average, in roughly the right direction, but any single step can be quite wrong. In practice, a middle ground is used: mini-batch gradient descent estimates the gradient from a small, randomly chosen subset of \(B\) examples,

\[ \nabla L_{\mathrm{batch}}(\theta) = \frac{1}{B}\sum_{i \in \text{batch}} \nabla \ell(f_\theta(x_i), y_i), \tag{12.5}\]

where \(B\) is the batch size. Larger batches give a more accurate but more expensive gradient estimate; smaller batches are cheaper per step, but the resulting gradient estimate is noisier, which can slow convergence on average. This same noise, however, has a useful side effect. Recall from Section 12.5 that gradient descent stops exactly where the gradient is zero: if \(\theta_t\) reaches a point where \(\nabla L_{\mathrm{train}}(\theta_t) = 0\), the update becomes \(\theta_{t+1} = \theta_t - \eta \cdot 0 = \theta_t\), and full-batch gradient descent stays there permanently — even if that point is only a local minimum, not the global one. A mini-batch update instead follows \(\nabla L_{\mathrm{batch}}(\theta_t)\), the gradient of a different, randomly sampled subset of the loss at every step. This gradient is generally not zero at the same point, even though the full gradient is, so the noisy update can carry \(\theta_t\) back out, particularly out of shallow or narrow local minima, where a small, well-placed nudge is enough to escape. The following figure (using a synthetic objective) illustrates this on a hand-built, non-convex landscape: full-batch gradient descent gets trapped in a shallow local minimum, while noisy updates escape it and continue toward the deeper, global minimum.

Contour map with two basins. The blue full-batch path ends in the left local minimum. The orange stochastic path crosses the saddle region and finishes near the right global minimum.
Figure 12.5: Full-batch gradient descent converges to a local minimum. SGD samples one of two synthetic example losses per update; for this chosen seed, it crosses into the basin of the global minimum. Both methods use the same initialization and learning-rate schedule. SGD is not guaranteed to escape or find a global minimum.

Working with batches introduces two related but distinct notions of “step”:

  • An iteration is one parameter update, using one batch.
  • An epoch is one full pass through the training set — that is, enough iterations to have used every training example roughly once.

If \(n = 1000\) and \(B = 100\), one epoch consists of 10 iterations. Full-batch gradient descent is the special case \(B = n\), where one iteration equals one epoch.

12.6.2 Learning-rate schedules

Section 12.5 showed that the “right” learning rate is tied to the local curvature of the loss. In practice, this ideal step size often isn’t constant throughout training: early on, when \(\theta_t\) is far from \(\theta^*\), larger steps may make faster progress if they remain stable; smaller steps later can help refine the solution or reduce fluctuations from stochastic gradients. For a fixed quadratic, the stability threshold does not change merely because we approach the minimum. Nevertheless, these practical considerations motivate letting \(\eta_t\) shrink over the course of training rather than fixing it in advance — a learning-rate schedule.

One simple choice is step decay: keep \(\eta_t\) constant for some number of iterations, then multiply it by a factor less than 1 (say, \(0.5\)) at fixed intervals. For example, \(\eta_t = 0.1\) for the first 1000 iterations, then \(\eta_t = 0.05\) for the next 1000, then \(\eta_t = 0.025\), and so on. This lets training move quickly at first and settle more carefully as it approaches a minimum. Many other schedules exist, for instance, ones that decay smoothly rather than in discrete jumps, but the underlying motivation is the same in each case.

12.7 Momentum and Adaptive Optimization

12.7.1 Momentum: use the history of gradients

Gradient descent can struggle on certain loss shapes, even when the loss is convex. Consider a simple example, distinct from our regression dataset: a two-parameter quadratic loss \(q(u,v) = 0.5u^2 + 8v^2\), whose curvature is \(16\) times larger in the \(v\) direction than in the \(u\) direction. Its contour plot is a long, narrow, elongated valley rather than a circular bowl.

This elongation causes a real dilemma for gradient descent with a single learning rate \(\eta\). From Section 12.5, \(0<\eta<2/c\) ensures convergence along a scalar quadratic direction of curvature \(c\), while \(\eta\leq 1/c\) avoids alternating parameter errors. Here, \(\eta\) needs to be small enough to remain stable along the steep \(v\) direction, but that same small \(\eta\) makes painfully slow progress along the shallow \(u\) direction. There is no single learning rate that is both stable in \(v\) and fast in \(u\). The figure below (left side) shows the result: the path zig-zags sharply back and forth across the narrow valley while creeping only slowly along its length toward the minimum.

Momentum addresses this by giving the optimizer a form of memory. Instead of using only the current gradient, it forms an exponentially weighted accumulation of recent gradients, called the velocity, and steps in that direction instead:

\[ v_{t+1} = \beta v_t + \nabla L(\theta_t), \qquad \theta_{t+1} = \theta_t - \eta\, v_{t+1}, \]

where \(v_0 = 0\) and \(0\leq\beta<1\) controls how much past gradients are remembered. Here the velocity is an unnormalized accumulation; it does not include the \((1-\beta)\) factor used in a normalized moving average. Along a direction where gradients keep the same sign, past contributions accumulate and can accelerate progress. Alternating contributions can partially cancel, but momentum can also overshoot and oscillate. The figure compares the resulting trajectories for one fixed learning rate and momentum coefficient; it does not demonstrate that momentum always follows a straighter path or always wins.

Two contour plots of an elongated quadratic with paths for gradient descent and momentum approaching the origin.
Figure 12.6: Full-gradient descent and momentum on q(u,v)=0.5u²+8v², starting at (4,2), for 35 updates. Both use learning rate 0.1; momentum uses beta=0.7. The contours illustrate unequal curvature. These fixed choices illustrate a mechanism rather than establish which optimizer is best.

12.7.2 Adam: adapt the scale of each coordinate

Momentum solves the elongated-valley problem by remembering the direction gradients have consistently pointed. A related but different idea is to also track the typical size of each parameter’s gradients, and use that to give each parameter, in effect, its own learning rate.

To see why this is useful, look again at our elongated landscape: not only does \(v\) have gradients that oscillate more sharply than \(u\)’s, its gradients are also consistently larger in magnitude. A parameter with a history of large gradients probably needs smaller steps to stay stable; a parameter with a history of small gradients can safely take larger ones. Adam (Adaptive Moment Estimation) formalizes this by keeping, for every parameter, a running average of its recent gradients (like momentum) and a running average of its recent squared gradients, then dividing each parameter’s step by the square root of that second average. Parameters with a history of large gradients get their steps shrunk; parameters with a history of small gradients get their steps left relatively large. In effect, every parameter gets an automatically-tuned, individual step size, rather than sharing one global \(\eta\) across a landscape where, as we just saw, a single learning rate can be simultaneously too large for some directions and too small for others.

Adam has become one of the most widely used optimizers in deep learning largely for this reason: it is comparatively robust to the choice of \(\eta\) and requires little per-problem tuning to get reasonable results, which matters enormously in practice, since real neural networks have far more than two parameters, often with wildly different gradient scales across layers. The exact update equations, including a technical correction needed in the first few iterations, are shown below.

NoteMathematical extension

Adam in full. Adam maintains two running averages per parameter, we can call them \(m_t\) (mean of recent gradients) and \(s_t\) (mean of recent squared gradients), updated at every step as

\[ m_{t+1} = \beta_1 m_t + (1-\beta_1)\nabla L(\theta_t), \qquad s_{t+1} = \beta_2 s_t + (1-\beta_2)\big(\nabla L(\theta_t)\big)^2, \]

with typical defaults \(\beta_1=0.9\), \(\beta_2=0.999\), and both \(m_0=s_0=0\). Because both averages start at zero, they are biased toward zero for the first several iterations, as the true average of one or two samples is a poor estimate. Adam corrects for this with bias correction,

\[ \hat m_{t+1} = \frac{m_{t+1}}{1-\beta_1^{t+1}}, \qquad \hat s_{t+1} = \frac{s_{t+1}}{1-\beta_2^{t+1}}, \]

where dividing by \(1-\beta_1^{t+1}\) (a factor close to \(0\) when \(t\) is small, close to \(1\) once \(t\) is large) inflates the early, under-counted averages back up to a fair estimate. The final update is

\[ \theta_{t+1} = \theta_t - \eta\,\frac{\hat m_{t+1}}{\sqrt{\hat s_{t+1}} + \epsilon}, \]

with a small constant \(\epsilon\) (e.g. \(10^{-8}\)) added only to prevent division by zero.

12.7.3 Choosing the right optimizer

We’ve now seen three optimizers, each adding machinery to address a limitation of the last:

Mechanism Extra memory per parameter Key hyperparameters
SGD Steps directly against the (possibly noisy) gradient none
Momentum Steps against an accumulated average of recent gradients 1 value (\(v\))
Adam Steps against an average gradient, rescaled per parameter by an average squared gradient 2 values (\(m\), \(s\))

Momentum and Adam are not free improvements, they trade extra memory (one or two additional numbers stored per parameter, which matters when a model has millions or billions of parameters) and extra hyperparameters (each with its own default that may or may not suit a given problem) for, typically, faster and more robust convergence.

It’s tempting, having seen this progression, to conclude that Adam is simply “the best” optimizer and always the right default. This isn’t quite right. Optimizer performance depends on the specific model architecture, dataset, batch size, and even the other hyperparameters (like \(\eta\)) chosen alongside it. A single comparison on one problem, showing optimizer A beating optimizer B, does not establish that A is generally better, only that it was better for that problem, with those settings. Some architectures are known to train noticeably better with plain SGD plus momentum than with Adam, despite Adam’s reputation. This is why the deep learning literature treats optimizer choice as an empirical, problem-specific decision, not a solved question, and why you will see published results comparing optimizers across many architectures and datasets before drawing general conclusions.

Optional extension: AdaGrad and RMSProp. Adam’s per-parameter rescaling builds on two earlier ideas. AdaGrad rescales each parameter’s step by the square root of the sum of all its past squared gradients, \(s_{t+1} = s_t + (\nabla L(\theta_t))^2\). This helps early on, but \(s_t\) only ever grows, so the effective step size shrinks monotonically and can become vanishingly small well before training is finished. RMSProp fixes this by replacing the running sum with a running exponential average, \(s_{t+1} = \gamma s_t + (1-\gamma)(\nabla L(\theta_t))^2\), so that old, stale gradients are gradually forgotten rather than permanently accumulated, keeping the effective step size from collapsing. Adam combines RMSProp’s exponential-average rescaling with momentum’s exponential-average of the gradient itself.

12.8 From Training Loss to Generalization

12.8.1 What does the training loss estimate?

Every optimizer in this chapter so far has had one job: make \(L_{\mathrm{train}}(\theta)\) as small as possible. It’s tempting to think that job is the whole story. If we’ve found \(\theta\) that drives the training loss close to zero, surely we’ve found a good model. Section 12.2 already flagged that this isn’t quite right, and we’re now equipped to see precisely why.

Recall that \(L_{\mathrm{train}}(\theta) = \frac{1}{n}\sum_{i=1}^n \ell(f_\theta(x_i), y_i)\) is an average over one specific, finite set of \(n\) examples: the ones we happened to collect. Nothing in the definition of \(L_{\mathrm{train}}\), and nothing in gradient descent’s pursuit of it, refers to any data outside that set. A model can therefore learn to fit the particular \(n\) examples in front of it extremely well, including whatever noise or quirks happen to be specific to those examples, without that skill transferring to new data drawn from the same source. Minimizing loss on that sample does not ensure the smallest population loss. What we actually care about (whether the model is useful), is how well it performs on examples it did not train on. This is the gap this section is about: the difference between fitting well and generalizing well.

12.8.2 Underfitting, overfitting, and optimization failure

To see this gap concretely, consider fitting a polynomial \(f_\theta(x) = \theta_0 + \theta_1 x + \theta_2 x^2 + \dots + \theta_k x^k\) to noisy data — the same regression-fitting idea as before, but now letting the degree \(k\) act as a knob controlling how flexible the model is.

Three panels compare linear, cubic, and degree-14 polynomial fits. Dark dots show training observations, open green circles show validation observations, and a dashed gray curve shows the generating sine function. The high-degree fit has large excursions clipped by the common vertical limits.
Figure 12.7: Fits to the same synthetic noisy sine data. The linear model misses the curved trend; the cubic gives a better compromise in this sample; the degree-14 polynomial interpolates the 15 training points but predicts poorly between them and beyond their range. Validation points are not used for fitting. All panels share axis limits; the high-degree curve extends far outside the displayed vertical range.

With \(k=1\), the model is a straight line, too rigid to capture whatever curve the data actually follows: both the training loss and the loss on new data are high, because the model cannot represent the right shape even in principle. This is underfitting: the model’s capacity is the bottleneck, and no amount of additional optimization will fix it. A better optimizer, more iterations, or a smaller learning rate cannot make a straight line curve.

With \(k=15\), the opposite happens: the model has enough flexibility to pass through (or very near) every single training point, driving \(L_{\mathrm{train}}\) close to zero. But between the training points, the fitted curve swings wildly, chasing the specific noise in this particular sample rather than the underlying trend. On new data, drawn from the same source but not seen during training, this model performs poorly — its wiggles don’t match the new points’ noise, which is different (random) noise. This is overfitting: excellent training performance paired with poor performance on unseen data.

This gives us two very different explanations whenever training performance is disappointing, and it matters which one applies: it might be that the model is simply too rigid (underfitting: the fix is a more flexible model, not a better optimizer), or that optimization itself failed to find good parameters even within a model that’s flexible enough (the fix is a better optimizer, more iterations, or a better learning rate). Confusing the two leads to wasted effort, for instance, tuning the learning rate for hours when the real problem is that a degree-1 polynomial simply cannot fit a curve, no matter how well it’s optimized.

12.8.2.1 Training and validation curves.

The cleanest way to see this trade-off is to track two losses as model flexibility increases: the training loss \(L_{\mathrm{train}}\), computed on the data used for fitting, and a second loss computed on a separate batch of examples the model never trained on. As \(k\) increases from 1, both losses start high and fall together as the model becomes flexible enough to capture the true trend. Past some point, though, the two curves diverge: \(L_{\mathrm{train}}\) keeps falling, while the loss on the held-out examples starts rising again. That is the signature of overfitting.

Blue training-loss curve decreases with polynomial degree. Green validation-loss curve fluctuates, reaches its minimum at degree 3, and rises sharply at high degrees. A dashed vertical line marks the selected degree.
Figure 12.8: Training and validation loss for polynomial degrees 1–14 on the same synthetic dataset. Training loss decreases as model flexibility increases, approaching zero at degree 14. Validation loss fluctuates and becomes very large at high degrees; degree 3 gives its lowest value in this sample. The logarithmic axis accommodates the wide range of losses. Near-zero losses are displayed at a plotting floor of 10⁻¹².

This divergence is exactly what motivates the next subsection: since we now have two losses, computed on two different sets of examples, we need to be precise about which data each one is allowed to use, and for what purpose.

12.8.3 Different roles for different data

We typically need to split our data three ways, because we make two different kinds of decisions during model development:

  • Training data: the examples used directly in \(L_{\mathrm{train}}(\theta)\), which gradient descent (or any optimizer from this chapter) uses to fit the parameters \(\theta\).
  • Validation data: a separate set of examples, not used to fit \(\theta\), used instead to make decisions about training, such as choosing the polynomial degree \(k\) in our example, or comparing optimizers, or picking a learning rate.
  • Test data: a third, held-out set of examples, only used at the very end, to report how well the final chosen model is expected to perform on genuinely new data.

Why three sets rather than two? Because the validation set, despite never appearing in \(L_{\mathrm{train}}\), is still used to make choices, and if we make many such choices (trying many values of \(k\), many learning rates, many architectures) and always pick whichever performs best on the validation set, we risk implicitly fitting our choices to the validation set’s own noise, the same way the degree-14 polynomial fit the training set’s noise. The validation loss for our selected model can end up optimistic for exactly the same reason the training loss was: we chose the model that looked best according to a fixed, finite set of examples. The test set, touched only at the end and never used to decide anything, gives an honest, final estimate of generalization, uncontaminated by the selection process itself.

In our polynomial example, this means: fit each candidate degree \(k\) using only the training data (producing \(\theta^*_k\) for each \(k\)), compare all candidates using the validation loss to choose the best \(k^*\), and only then evaluate the already fitted model with degree \(k^*\) on the untouched test set, once. Do not fit parameters or select hyperparameters using the test set.

12.8.3.1 Formalizing the distinction.

We can now state precisely what “generalizing well” means. Suppose our data is drawn from some underlying distribution, the full population of possible \((x,y)\) pairs, of which our finite dataset is only a sample. The population loss (or expected loss) is the average loss over this entire distribution, not just our \(n\) observed examples:

\[ L_{\mathrm{pop}}(\theta) = \mathbb{E}_{(x,y)}\big[\ell(f_\theta(x), y)\big]. \]

Population loss describes expected performance on new examples from the target distribution. Training, validation, and test losses are finite-sample estimates, but the training loss is also used to fit the model and validation loss is used for selection. Consequently, they need not be unbiased estimates for the selected model. The earlier plot shows training loss falling while validation loss rises as polynomial degree increases; it does not display test or population loss. This gap is evidence to investigate generalization, not an exact measurement of population loss. Our goal is low loss on new data, rather than merely a small training–validation gap: an underfitting model can have a small gap and still predict poorly.

12.9 Regularization Methods

12.9.1 Guide learning with additional preferences

Section 12.8 showed that driving \(L_{\mathrm{train}}(\theta)\) to zero is not exactly the goal. A model that fits the training data perfectly can still generalize poorly, because \(L_{\mathrm{train}}\) alone can’t distinguish a solution that captured the true trend from one that memorized noise. Often, among the many parameter settings that fit the training data reasonably well, some generalize better than others. Regularization is any technique that steers training toward solutions we expect to generalize better, using knowledge that isn’t contained in \(L_{\mathrm{train}}\) itself, for instance, a preference for simpler functions, smaller weights, or predictions that don’t change drastically under small, meaningless changes to the input.

It’s worth being clear from the outset that regularization is broader than “adding a penalty term to the loss,” which is the most common technique but not the only one. As this section will show, stopping training early, deliberately altering the training data, and randomly perturbing the model during training are all regularization methods too, even though none of them modifies \(L_{\mathrm{train}}\)’s formula directly. What unifies them is the underlying goal: better generalization, and not the specific mechanism.

12.9.2 L2 and L1 Penalties

The most direct way to express a preference among solutions is to add a term to the objective that is small for preferred parameters and large for disfavored ones. This gives a regularized objective,

\[ J(\theta) = L_{\mathrm{train}}(\theta) + \lambda R(\theta), \tag{12.6}\]

where \(R(\theta)\) is a regularizer that measures something about \(\theta\) we want to discourage, and \(\lambda \ge 0\) is the regularization strength, controlling how much we’re willing to trade training fit for whatever \(R\) penalizes. Optimization now minimizes \(J(\theta)\) rather than \(L_{\mathrm{train}}(\theta)\) directly. For differentiable penalties such as L2, the optimizers in Section 12.6 and Section 12.7 can use \(\nabla J\) in place of \(\nabla L_{\mathrm{train}}\). L1 is not differentiable at zero and needs a subgradient or a method such as a proximal update.

12.9.2.1 L2 regularization.

The most common choice is \(R(\theta) = \|\theta\|_2^2 = \sum_j \theta_j^2\), the sum of squared parameters, giving

\[ J(\theta) = L_{\mathrm{train}}(\theta) + \lambda \sum_j \theta_j^2. \tag{12.7}\]

This penalizes large weights in the chosen parameterization. In our degree-14 polynomial example, shrinking coefficients in a fixed, scaled basis can reduce extreme predictions. However, a polynomial can vary sharply even with small coefficients if its input powers are large. Coefficient size and the effect of a penalty depend on the basis and input scale; L2 does not universally guarantee a smoother function.

The next figure uses the same \(\lambda\sum_j\theta_j^2\) convention as the prose. Only non-intercept coefficients are penalized, and the inputs are mapped to \([-1,1]\) before constructing polynomial features.

Three panels show dark training points and blue polynomial fits for zero, moderate, and strong L2 regularization.
Figure 12.9: Degree-14 polynomial fits with increasing L2 regularization. The penalty shrinks coefficients in a fixed, scaled polynomial basis; the intercept is unpenalized. Strong regularization produces an almost constant fit. Curves are shown within the training input range, with large unregularized excursions clipped by the shared vertical limits.

\(\lambda\) plays a role similar to model capacity in Section 12.8, but tuned continuously rather than by choosing a discrete degree \(k\): \(\lambda = 0\) recovers plain training-loss minimization (prone to overfitting if the model is flexible), while \(\lambda \to \infty\) drives the penalized coefficients toward zero. In this figure the intercept is unpenalized, so the fit approaches a constant rather than necessarily zero. Between these extremes lies a useful range, and, just like the polynomial degree \(k^*\) in Section 12.8, the right value of \(\lambda\) is a hyperparameter chosen using validation performance, never training performance (since \(L_{\mathrm{train}}\) alone always prefers \(\lambda=0\)).

12.9.2.2 L1 regularization.

A related choice is \(R(\theta) = \|\theta\|_1 = \sum_j |\theta_j|\), the sum of absolute values rather than squares. Like L2, this discourages large weights, but with an important qualitative difference: L1 regularization tends to push many parameters to exactly zero, rather than merely shrinking all of them toward zero. This produces sparse solutions, where only a subset of parameters end up nonzero. This is useful when we suspect that only a few of many available inputs actually matter, since the zeroed parameters effectively remove their corresponding inputs from the model entirely. This sparsity-inducing behavior, rather than the size of the penalty itself, is usually the main reason to prefer L1 over L2 in practice.

12.9.3 Weight decay and AdamW

In the AdamW formulas below, \(\lambda\) denotes a decay coefficient. Matching the shrinkage of plain SGD with our L2 penalty convention would require a decay coefficient of \(2\lambda_{\mathrm{L2}}\); identical numeric settings are not automatically equivalent.

For plain gradient descent, L2 regularization has a second interpretation worth making explicit. The gradient of \(J(\theta) = L_{\mathrm{train}}(\theta) + \lambda\sum_j \theta_j^2\) is \(\nabla J(\theta) = \nabla L_{\mathrm{train}}(\theta) + 2\lambda\theta\), so the gradient descent update becomes

\[ \theta_{t+1} = \theta_t - \eta\big(\nabla L_{\mathrm{train}}(\theta_t) + 2\lambda\theta_t\big) = (1 - 2\eta\lambda)\,\theta_t - \eta\,\nabla L_{\mathrm{train}}(\theta_t). \]

Compare this to plain, unregularized gradient descent, \(\theta_{t+1} = \theta_t - \eta\nabla L_{\mathrm{train}}(\theta_t)\). The regularized version does exactly the same gradient step, but first shrinks \(\theta_t\) toward zero by a fixed multiplicative factor \((1-2\eta\lambda)\). This shrinking-then-stepping view is called weight decay, and for ordinary gradient descent (or SGD), it is not merely similar to L2 regularization, it is exactly the same update, just written two different ways.

This equivalence breaks down for the adaptive optimizers of Section 12.7. Recall that Adam rescales each parameter’s update by dividing by the square root of a running average of squared gradients. If we implement “L2 regularization” the naive way, adding \(2\lambda\theta_t\) directly into the gradient before it reaches Adam’s moving averages, that penalty term gets swept up into the same per-parameter rescaling as the rest of the gradient. A parameter with historically large gradients has its regularization shrunk along with its gradient step, even though there’s no real reason the penalty on large weights should weaken just because that parameter’s gradients happen to be large. The clean “shrink by a fixed factor, then step” interpretation no longer holds once rescaling enters the picture.

AdamW fixes this by decoupling the two operations: rather than folding \(2\lambda\theta_t\) into the gradient before Adam processes it, AdamW applies the weight-decay shrinkage \((1-\eta\lambda)\) directly to \(\theta_t\), separately from, and unaffected by, Adam’s adaptive rescaling of the gradient step itself. This restores the clean interpretation from the SGD case: a fixed proportional shrinkage, independent of each parameter’s gradient history, plus a separately-computed adaptive step.

Note

Mathematically: Writing Adam’s update from Section 12.7 as \(\theta_{t+1} = \theta_t - \eta \,\hat m_{t+1}/(\sqrt{\hat s_{t+1}}+\epsilon)\), AdamW modifies only the final line to

\[ \theta_{t+1} = \theta_t - \eta\left(\frac{\hat m_{t+1}}{\sqrt{\hat s_{t+1}}+\epsilon} + \lambda\,\theta_t\right), \tag{12.8}\]

where the \(\lambda\theta_t\) term is added after the adaptive rescaling, not before it — the one-line change that distinguishes AdamW from “Adam with an L2 penalty,” and the reason the two are not equivalent despite looking superficially similar.

12.9.4 Early stopping

The earlier degree comparison in Section 12.8 varied model capacity, not training time. We now hold the degree fixed and monitor losses during optimization. Training loss may continue decreasing after validation loss stops improving; this suggests keeping an earlier checkpoint instead of the final parameters. The following example illustrates this behavior.

Early stopping exploits this directly: monitor validation loss throughout training (for instance, once per epoch), keep a saved copy of the model’s parameters whenever validation loss reaches a new low, and stop training once validation loss has failed to improve for some number of checks in a row (a patience window, since validation loss can fluctuate slightly even while on a genuine downward trend, especially with mini-batch training). The final model used is not the one obtained after the last training iteration, but the one saved at the point of lowest validation loss. Everything trained afterward, while \(L_{\mathrm{train}}\) kept falling, is discarded.

Blue training loss decreases while green validation loss reaches an early minimum and subsequently rises. A dashed vertical line marks the best validation checkpoint.
Figure 12.10: Training and validation loss during gradient descent on a degree-14 polynomial. The dashed line marks the lowest recorded validation loss. Early stopping would retain the parameters from that checkpoint rather than the final update. The full run is shown to reveal what happens afterward.

Why does this count as regularization, given our definition at the beginning of this section? It doesn’t modify \(L_{\mathrm{train}}\) or add any penalty term, but it does use information outside \(L_{\mathrm{train}}\) (the validation loss) to steer which solution we ultimately keep, exactly matching the broad definition we gave. In effect, early stopping restricts how far optimization is allowed to pursue \(L_{\mathrm{train}}\) before we intervene, which is precisely why it belongs in this section.

Early stopping is attractive because it’s inexpensive. It costs one validation-loss computation per check, requires choices about the validation-check frequency, patience, and optionally a minimum improvement threshold, and can be combined freely with L2/L1 penalties, dropout, or any other regularizer in this section, since it acts on when training stops rather than what is being minimized.

12.9.5 Data augmentation

A different strategy addresses generalization by changing what the model trains on, rather than what it optimizes. Data augmentation creates additional training examples by applying transformations to existing ones: transformations chosen specifically because we believe they shouldn’t change the target label \(y\). For an image classifier, a photo of a dog rotated by a few degrees, slightly brightened, or mirrored left-to-right is still a photo of a dog; training on these variations, alongside the originals, teaches the model that such changes are irrelevant to the task, without ever having to state that rule explicitly in the loss function.

This is a regularizer in the same broad sense as we’ve discussed: it doesn’t touch \(L_{\mathrm{train}}\)’s formula, but it does encode outside knowledge, specifically, knowledge about which input changes should and shouldn’t affect the prediction. That steers the fitted model toward solutions that generalize better. The transformations used are always task-specific: the mirroring example above would be actively harmful for a task where left/right orientation matters, so choosing sensible augmentations requires understanding what the task’s labels do and don’t depend on, not a generic recipe that applies everywhere.

12.9.6 Dropout

Dropout regularizes a neural network by randomly disabling (“dropping”) a fraction of its units during each training step: for each mini-batch, every unit in a dropout-enabled layer is independently set to zero with some probability \(p\), and the network is trained as if those units simply didn’t exist for that step. Because a different random subset is dropped every step, no single unit can be relied upon to always be present, which discourages the network from developing brittle dependencies on any one specific unit or narrow combination of units. This is a form of built-in redundancy that tends to improve generalization.

PyTorch uses inverted dropout: during training, retained activations are multiplied by \(1/(1-p)\), preserving each activation in expectation. At evaluation, dropout is disabled and no further scaling is applied. Another convention performs the scaling at inference instead; do not combine the two. Preserving individual activations in expectation does not imply that the entire nonlinear network has an unchanged expected output.

12.10 Putting it Together: Training and Diagnosing a Model

This chapter has developed a toolbox: gradient descent and its variants (Section 12.6), momentum and adaptive optimizers (Section 12.7), the training/validation/test framework for detecting overfitting (Section 12.8), and several regularization methods (Section 12.9). In practice, these pieces are never used in isolation. Training a real model means making several of these choices simultaneously, then figuring out, from imperfect evidence, which choices are working and which aren’t. This section works through that process end to end.

A baseline. Every investigation needs a fixed starting point to compare against. A baseline specification should fully pin down everything that could otherwise silently vary between runs: the training/validation/test split, the model and its capacity (e.g. polynomial degree, or network architecture), the loss function, the optimizer and its hyperparameters, and the evaluation metric used to judge success. Record all of these explicitly before making any changes. Without a documented baseline, it’s impossible to know later which specific change caused an observed difference.

Changing one factor at a time. With a baseline fixed, investigate individual questions by varying exactly one setting and holding everything else fixed. For instance, comparing a few learning rates while keeping the optimizer, model, and regularization strength unchanged, or comparing optimizers while keeping the learning rate’s tuning process identical across them. This last point deserves emphasis, because it’s easy to get wrong: each optimizer’s ideal learning rate can differ substantially, and an optimizer run at a poorly-suited \(\eta\) will look artificially weak. A sound comparison gives every optimizer a reasonable tuning budget, for example, trying a small grid of learning rates for each one and reporting each optimizer’s best result rather than assuming one learning rate is equally appropriate everywhere. The same discipline applies to comparing regularization strengths: vary \(\lambda\) while holding the optimizer and its tuning fixed, not both at once.

Interpreting the evidence. Once results are in, reading them well is its own skill, separate from producing them. A few things worth checking every time:

  • Training and validation losses together, not training loss alone. A change that improves training loss but worsens validation loss is a warning sign for overfitting, not a success.
  • Runtime, since a modest accuracy gain that costs substantially more compute (more iterations, a heavier optimizer like Adam’s extra memory) may not be worth adopting, depending on the constraints of the task.
  • Variation across repeated runs. Randomness enters through the initial parameters, the mini-batch sampling order, and any stochastic regularizer like dropout, so a single run’s result is one sample, not a guarantee. Repeating a comparison two or three times with different random seeds, and looking at the spread of outcomes, reveals whether an apparent improvement is real or within the range of ordinary run-to-run noise.

Be explicit about what the evidence actually supports. A learning-rate sweep that shows \(\eta=0.01\) beating \(\eta=0.1\) on this dataset and model supports a claim about this specific setup; not a general claim that \(0.01\) is a universally better learning rate, echoing some point made about optimizer comparisons. Similarly, a single successful run after adding regularization is weaker evidence than the same result holding up consistently across several seeds. Distinguishing “the data support this conclusion” from “the data are suggestive but inconclusive” is often more valuable than any single number produced by the experiment.

12.10.1 Worked example: diagnosing a failed training run.

This separate experiment uses seed 7, 20 training observations, and a degree-9 model. Its penalty applies to all scaled coefficients, including the intercept, unlike the earlier ridge illustration and the practical. Compare strengths only within a fixed basis and penalty definition.

To see how the diagnostic ideas of this chapter come together in practice, let’s work through a complete case: an initial training run that fails, and the reasoning that leads to a fix.

Setup. We’ll fit a flexible polynomial model to a noisy dataset generated from an underlying sine curve, split into training and validation sets.

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)

n_total = 40
x_all = np.sort(rng.uniform(0, 6, n_total))
y_all = np.sin(x_all) + rng.normal(scale=0.25, size=n_total)

n_train = 20
train_idx = rng.choice(n_total, size=n_train, replace=False)
val_idx = np.array([i for i in range(n_total) if i not in train_idx])
x_train, y_train = x_all[train_idx], y_all[train_idx]
x_val, y_val = x_all[val_idx], y_all[val_idx]

degree = 9  # lower than 15, to reduce the ill-conditioning of raw polynomial features
X_train = np.vander(x_train, degree + 1)
X_val = np.vander(x_val, degree + 1)
scale = X_train.std(axis=0)
scale[scale == 0] = 1.0
X_train_s = X_train / scale
X_val_s = X_val / scale

def train_gd(X, y_target, X_v, y_v, eta, n_iters, lam=0.0):
    theta = np.zeros(X.shape[1])
    train_losses, val_losses = [], []
    for _ in range(n_iters):
        pred = X @ theta
        grad = X.T @ (pred - y_target) / len(y_target) + 2 * lam * theta
        theta = theta - eta * grad
        train_losses.append(0.5 * np.mean((X @ theta - y_target) ** 2))
        val_losses.append(0.5 * np.mean((X_v @ theta - y_v) ** 2))
    return theta, train_losses, val_losses

theta1, train_losses1, val_losses1 = train_gd(
    X_train_s, y_train, X_val_s, y_val, eta=0.02, n_iters=3000, lam=0.0
)

Step 1 — train a first configuration. We fit a degree-9 polynomial with plain gradient descent, no regularization, for 3000 iterations.

fig, ax = plt.subplots(figsize=(6.5, 3.6))
updates = np.arange(1, len(train_losses1) + 1)
ax.plot(updates, train_losses1, label="Training loss")
ax.plot(updates, val_losses1, label="Validation loss")
ax.set(xlabel="Iteration", ylabel="Half mean squared error", yscale="log")
ax.legend(fontsize=8)
fig.tight_layout()
plt.show()

print(f"Final training loss:   {train_losses1[-1]:.4f}")
print(f"Final validation loss: {val_losses1[-1]:.4f}")
print(f"Best validation loss:  {min(val_losses1):.4f} (iteration {np.argmin(val_losses1) + 1})")
Line chart of training and validation loss against iteration on a logarithmic scale. Both decrease initially, then validation loss rises while training loss keeps decreasing.
Figure 12.11: Training and validation losses for an unregularized degree-9 polynomial fitted by gradient descent. Validation loss rises after its minimum while training loss continues to fall.
Final training loss:   0.0354
Final validation loss: 0.7366
Best validation loss:  0.0842 (iteration 295)

Step 2 — diagnose. Figure 12.11 shows a clear pattern. After a brief initial settling period, training and validation loss decrease together, reaching a minimum validation loss of \(0.0842\) at iteration \(295\). Training loss continues falling steadily throughout the rest of training, reaching \(0.0354\) by the final iteration. The falling training loss demonstrates optimization progress, but does not establish convergence to the training-loss minimum or rule out conditioning difficulties. Validation loss, however, does the opposite after its minimum: it rises steadily and substantially, reaching \(0.7366\) by iteration 3000, nearly nine times higher than its best value, even as training loss keeps improving. This divergence between an improving training loss and a worsening validation loss is exactly the overfitting signature we talked about: the model has more than enough flexibility to fit the 20 training points closely, and later updates worsen performance on this validation sample. This is consistent with overfitting, but the boundary extrapolation visible in Figure 12.12 also matters; the loss curves alone do not identify the cause.

Step 3 — visualize the fitted function. It’s worth seeing what this failure actually looks like as a curve, not just as a loss number. Figure 12.12 plots the fitted polynomial at the final iteration against both training and validation points. For most of the input range, the fit tracks the data closely and looks entirely reasonable. Near the right edge of the range, however, the curve swings sharply upward, departing from the data entirely by \(x=6\). This localized instability is typical of high-degree polynomials: with comparatively few training points anchoring the model near the boundary, the extra flexibility there is only loosely constrained by the data, and the fitted curve can swing wildly in exactly the region with the least training support. This also explains the shape of the model’s validation curve: several validation points sit in or near this unstable region, so as training continues and this swing grows more extreme, it drives validation loss up substantially while leaving training loss (measured only on the 20 training points, none of which sit deep in the unstable region) largely unaffected.

Training and validation observations with a degree-9 fitted curve that rises sharply at the right edge; the largest excursion extends beyond the displayed vertical limits.
Figure 12.12: The degree-9 polynomial fit at the final iteration (iteration 3000), overlaid on the training and validation data. The curve rises sharply near the right boundary, where validation inputs extend beyond the training range.

Step 4 — apply a fix and compare. Two fixes follow directly from Section 12.9: restoring the parameters from the iteration of lowest validation loss (early stopping), and refitting with an L2 penalty \(\lambda\sum_j\theta_j^2\) added to the objective. For the L2 penalty, the right strength isn’t obvious in advance; Section 12.9 established that \(\lambda\) must be chosen using validation performance, so we try a small grid of values and pick whichever generalizes best rather than guessing one value up front.

best_iter = int(np.argmin(val_losses1))
theta_es, _, _ = train_gd(X_train_s, y_train, X_val_s, y_val, eta=0.02, n_iters=best_iter + 1, lam=0.0)
val_loss_es = 0.5 * np.mean((X_val_s @ theta_es - y_val) ** 2)

lambdas = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05]
l2_results = {}
for lam in lambdas:
    theta_l2, _, val_losses_l2 = train_gd(
        X_train_s, y_train, X_val_s, y_val, eta=0.02, n_iters=3000, lam=lam
    )
    l2_results[lam] = val_losses_l2[-1]
    print(f"lambda={lam}: final validation loss = {val_losses_l2[-1]:.4f}")

best_lambda = min(l2_results, key=l2_results.get)
val_loss_l2 = l2_results[best_lambda]
print(f"\nBest lambda: {best_lambda}, validation loss: {val_loss_l2:.4f}")

labels = ["No safeguard\n(final iteration)", "Early stopping", f"L2 regularization\n($\\lambda$={best_lambda})"]
values = [val_losses1[-1], val_loss_es, val_loss_l2]

fig, ax = plt.subplots(figsize=(6, 3.8))
ax.bar(labels, values, color=["C3", "C0", "C1"])
ax.set(ylabel="Validation loss of selected model (half MSE)")
fig.tight_layout()
plt.show()

print(f"\nNo safeguard:      {values[0]:.4f}")
print(f"Early stopping:    {values[1]:.4f}")
print(f"L2 regularization: {values[2]:.4f}")
lambda=0.0001: final validation loss = 0.7311
lambda=0.0005: final validation loss = 0.7094
lambda=0.001: final validation loss = 0.6833
lambda=0.005: final validation loss = 0.5126
lambda=0.01: final validation loss = 0.3679
lambda=0.05: final validation loss = 0.0848

Best lambda: 0.05, validation loss: 0.0848
Bar chart comparing validation loss for three training strategies. Early stopping and validation-selected L2 regularization have much lower losses than the final unregularized fit.
Figure 12.13: Validation loss for the final unregularized fit, early stopping, and L2 regularization selected from a grid of penalty strengths using validation loss.

No safeguard:      0.7366
Early stopping:    0.0842
L2 regularization: 0.0848

Both interventions recover almost all of the validation performance lost to overfitting, bringing validation loss down from \(0.7366\) to roughly \(0.084\), an improvement of nearly \(9\times\), and land within a hundredth of each other. This confirms the diagnosis from Step 2: the failure was a generalization problem caused by excess, poorly-constrained model flexibility (visible directly in Step 3’s curve near the boundary), not a failure of the optimizer to find a good fit. Both fixes work by constraining that flexibility, just through different mechanisms.

Two caveats are worth stating plainly, echoing the point made earlier in this section about reading evidence carefully. First, this comparison shows that both remedies help for this dataset, this model, and this optimizer. It doesn’t establish that early stopping and L2 regularization are interchangeable in general, or that \(\lambda=0.05\) is some universally ideal value. Second, validation loss in the \(\lambda\) sweep improved monotonically right up to the largest value tried, suggesting the grid may not have gone far enough to find the point where regularization becomes too strong and starts to underfit. A more thorough study would extend the \(\lambda\) grid further and repeat the comparison across several random seeds, following the one-factor-at-a-time and tuning-budget discipline described earlier in this section.

Concluding. This worked example illustrates the chapter’s central theme in miniature: minimizing \(L_{\mathrm{train}}\) is a well-defined, solvable problem, but solving it well is only half the task. Knowing when to stop, what to hold back, and what your evidence actually supports is what turns a working optimizer into a model that generalizes. The next chapter turns to a different question this one has deliberately set aside: how the gradients driving every optimizer in this chapter are actually computed for a real neural network, through backpropagation.

12.11 Chapter summary and the next question

Optimization turns a chosen objective into parameter updates, guided by the gradient and shaped by the learning rate: too large causes oscillation or divergence, too small wastes iterations, and a zero gradient marks a stationary point, not necessarily a minimum. Mini-batch noise trades some accuracy for cheaper steps, and can even help escape shallow local minima; momentum and Adam build on this by using gradient history to move faster and more reliably through difficult landscapes.

None of this guarantees a model that generalizes. A lower training objective does not mean better predictions on new data, and closing that gap is what regularization, early stopping, and careful use of validation data are for: not fitting the training set better, but fitting it in a way that transfers.

We derived simple gradients by hand and used explicit matrix gradients for polynomial regression. The synthetic stochastic-landscape demonstration also used PyTorch automatic differentiation. A neural network has many layers and millions of shared parameters, so the next question is how to compute all of its gradients efficiently, which is the role of backpropagation. Backpropagation calculates gradients; the optimizer, as we’ve now seen in detail, is what uses them.

12.12 Review questions

12.12.1 Check the foundations

  1. For \(L(w)=\frac54(w-2)^2\), calculate two updates from \(w_0=0\) with \(\eta=0.2\). What happens if \(\eta=0.8\)?
  2. For \(q(u,v)=u^2-v^2\), calculate the gradient at the origin. Why is the origin not a minimum?
  3. A dataset contains 100 examples and batches have size 32. How many updates occur per epoch when the final partial batch is retained? Why does changing batch size alter a comparison with a fixed number of epochs?
  4. Derive the minimizer of \(J(w)=\frac54(w-2)^2+\frac\lambda2w^2\). This exercise uses the alternative \(\lambda/2\) penalty convention; account for that factor when differentiating. Distinguish the effect of \(\lambda\) from that of \(\eta\).

12.12.2 Explain and diagnose

  1. A training loss oscillates. Give two possible causes and one check that could help distinguish them.
  2. Both training and validation losses are high. Why is “use a bigger model” not yet a justified conclusion?
  3. Training loss decreases while validation loss rises. What checkpoint would you consider, and what would you inspect before attributing the behavior entirely to overfitting?
  4. Explain why adding an L2 penalty to Adam and applying decoupled weight decay generally produce different updates. No memorization of Adam’s equations is required.

12.12.3 Design and evaluate

  1. Design a comparison of SGD with and without momentum. State what is controlled, what is tuned, how validation is used, and which computational resource is matched.
  2. In the synthetic experiment, increase the number of training examples while keeping the feature count and noise scale fixed. Predict how the training–validation gap might change, then test several seeds.
  3. Propose an augmentation for a task you know. Give a concrete example for which the same transformation would invalidate the label.
  4. A colleague standardizes all data before splitting and chooses the best run using test loss. Identify both problems and redesign the procedure.

12.13 Selected further reading

12.13.1 Build intuition and work through examples

12.13.2 Read selected explanations more deeply

  • Goodfellow, Bengio, and Courville, Deep Learning, Chapters 7 and 8. Consult selected sections on penalties, early stopping, and optimization challenges; the full chapters are broader than this lesson (Goodfellow et al. 2016).
  • Boyd and Vandenberghe, Convex Optimization, Chapter 1 and selected parts of Chapters 3 and 9. An optional mathematical reference, not prerequisite reading for this course (Boyd and Vandenberghe 2004).

12.13.3 Connect methods to the original papers