Chapter 2 · PDF Pages 34-74

Optimization: from problems to gradient descent

The whole book is also in the PDF.

Having established the language of vectors, norms, and distances, this chapter pivots from description to action. We introduce the paradigm of optimization by framing real-world tasks as problems of finding the “best” vector. We begin by formulating several key problems, including linear regression and data clustering, using only the vector operations and norms from Chapter 1. This process naturally gives rise to the concepts of a model, a cost function, and the formal definition of an optimization problem. We then confront the fundamental question: how do we find the solution? After contrasting the rare cases of closed-form solutions with the necessity of iterative methods, we develop the intuition for gradient descent, our first optimization algorithm. This motivates a formal treatment of calculus for vector functions, including derivatives, gradients, and the powerful Taylor approximation. Armed with these tools, we formalize gradient descent and revisit our initial examples, demonstrating how to derive and apply the algorithm to solve concrete problems.

Keywords. Optimization | Cost Function | Least Squares | Linear Regression | Gradient Descent | Taylor Approximation | Derivatives | Gradients

Figure 2.1(a): The least-squares objective.
(a) The least-squares objective.
Figure 2.1(b): The data centroid objective.
(b) The data centroid objective.
Figure 2.1(c): A gradient descent step.
(c) A gradient descent step.
Figure 2.1: Visualizations of core optimization concepts. (a) Least-squares regression finds the model (line) that minimizes the sum of squared red residual lines. (b) The centroid problem finds the center point \(\mathbf{c}\) that minimizes the sum of squared distances to all data points. (c) An iterative step of gradient descent moves from the current point \(\mathbf{x}_t\) (upper red dot) in the direction of steepest descent (opposite the gradient) to a lower point \(\mathbf{x}_{t+1}\) (lower red dot); the teal arrow is the step between them.

2.1 Framing Problems with Vectors and Cost Functions

In the previous chapter, we learned some grammar of linear algebra: how to define vectors and measure their properties. Now, we begin writing stories with this grammar. Many problems in AI/ML can be translated into a common narrative: finding a specific vector that best accomplishes a certain goal. To do this, we need three components:

  1. A Model: An assumption about how an output or decision can be computed from an input vector. In our vector-only world thus far, this model will often be a simple inner product, but as we proceed, more models will emerge.
  2. A Cost Function (or Loss Function): A function that takes our model’s prediction and a desired outcome and returns usually a scalar value measuring the “error” or “badness” of that prediction. Our tools from Chapter 1, norms and distances, are the perfect building blocks for this at this point.
  3. An Objective: The overall goal, which is to find the one model vector that minimizes the total cost. This usually translates into “Find a set of parameters that minimizes the loss function over the data”, but these matters (“what is data? what is a training dataset and what a testing dataset? What is population and what empirical loss?” etc) are subject of ML/AI courses.

Let’s make these ideas concrete with a few motivating examples.

2.1.1 Example 1: The Least-Squares Problem for Price Prediction

Imagine we are tasked with building a simple model to predict house prices. We have collected information on \(n\) houses. For each house \(i\), we have a set of \(p\) features, such as, for instance, its area, number of bedrooms, and distance to the city center, among others. We represent these features as a vector \(\mathbf{a}_i \in \mathbb{R}^p\) for the \(i\)-th house in our database. We also know the actual price it sold for, a scalar \(y_i \in \mathbb{R}\).

The Model. Our first step is to propose a model. Let’s assume a simple linear relationship: the predicted price, \(\hat{y}_i\), is a weighted sum of the features. This is a perfect use for the inner product. We introduce a vector of unknown weights, \(\mathbf{w} \in \mathbb{R}^p\), where each component \(w_j\) represents the importance of the \(j\)-th feature. Our model is then:

\[ \hat{y}_i = \langle \mathbf{a}_i, \mathbf{w} \rangle = \mathbf{a}_i^\top \mathbf{w}. \]

What do we mean as “our model”? We mean that if we know a good \(\mathbf{w}\), then if someone provides us with the features of a house that we do not know the price (say the \(k\)-th house that is not in our database), maybe our linear model (and there is a big IF here) will provide us a good approximation of the unknown price by computing \(\hat{y}_k = \langle \mathbf{a}_k, \mathbf{w} \rangle\). Thus, what we are looking for here is a collection of parameters \(w_j\) that predict well the prices of many houses at the same time: i.e., the set of parameters “learn” how to combine the features of any house to predict the final price. Our goal is to find this best possible weight vector, denoted as \(\mathbf{w}^\star \in \mathbb{R}^p\).

The Cost Function. What does “best” mean? It means the predicted prices \(\hat{y}_i\) are close to the true prices \(y_i\). Here, we implicitly make the assumption that the true prices in our database, i.e., prices of houses we know their features AND their prices, are “generated by nature” as a linear model: I.e., we assume that really the prices are computed as a linear combination of the features we consider, and there are no hidden relationships and features not covered by this model. Under this assumption, we can safely say that the true prices are generated as:

\[ \begin{aligned} y_i = \langle \mathbf{a}_i, \mathbf{w}^\star \rangle = \mathbf{a}_i^\top \mathbf{w}^\star \end{aligned} \]

but \(\mathbf{w}^\star\) is unknown to us; this is the goal of finding a \(\mathbf{w}\) that is close to \(\mathbf{w}^\star\) by minimizing a cost function. Then, for a single house \(i\), the error is the difference \(y_i - \hat{y}_i = y_i - \mathbf{a}_i^\top \mathbf{w}\), where \(\mathbf{w}\) is our belief what \(\mathbf{w}^\star\) might look like. A natural way to measure the magnitude of this error is its square: \((y_i - \hat{y}_i)^2 = (y_i - \mathbf{a}_i^\top \mathbf{w})^2\). This is known as the squared error.

The Objective. We want to find the single vector \(\mathbf{w}\) that performs well across all the houses in our database. Why? Because assume we found a set of parameters \(\bar{\mathbf{w}}\) that works amazingly for the house with features \(\mathbf{a}_{100}\), but super underperforms for any other house in our database. This means that we just found a vector that works well on one house, but most probably is useless for our task: to predict the prices for houses we do not know their prices. Thus, it is reasonable to ask that if we find a set of parameters \(\mathbf{w}\) that collectively work well on our database, \(\mathbf{w}\) then MIGHT work well on more houses, outside this database. A standard approach is to minimize the average squared error over all \(n\) houses. This gives us our final objective function, which we want to minimize:

\[ f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top \mathbf{w})^2. \]

This is the celebrated least-squares problem. It is a function that takes a vector \(\mathbf{w}\) and tells us how bad our model is on average. The problem is now mathematically precise: find the vector \(\mathbf{w}\) that minimizes \(f(\mathbf{w})\), or

\[ \begin{aligned} \min_{\mathbf{w} \in \mathbb{R}^p} f(\mathbf{w}). \end{aligned} \]

Complexity Analysis. Let’s perform a more detailed analysis of the computational cost, counting a more precise number of FLOPs required to evaluate the cost function \(f(\mathbf{w})\) for a given weight vector \(\mathbf{w}\). We can break down the computation by first analyzing the work required for a single term in the summation (for one data point \(\mathbf{a}_i\)) and then aggregating:

  1. Work for a Single Data Point \(i\): The core computation for each data point is calculating the squared error, \((y_i - \mathbf{a}_i^\top \mathbf{w})^2\). We follow the order of operations:
    • Inner Product: First, we compute the inner product \(\mathbf{a}_i^\top \mathbf{w}\). Since both \(\mathbf{a}_i\) and \(\mathbf{w}\) are vectors in \(\mathbb{R}^p\), this operation involves \(p\) multiplications (\(a_{i1}w_1, a_{i2}w_2, \dots\)) and \(p-1\) additions to sum the results.
      FLOP Count: \(p + (p-1) = 2p - 1\) FLOPs.
    • Subtraction: Next, we subtract this result from the true value \(y_i\). This is a single scalar subtraction.
      FLOP Count: \(1\) FLOP.
    • Squaring: Finally, we square the resulting error. This is a single scalar multiplication.
      FLOP Count: \(1\) FLOP.

    The total cost to compute the squared error for one data point is the sum of these steps: \((2p - 1) + 1 + 1 = 2p + 1\) FLOPs.

  2. Aggregating Over All Data Points: Now, we account for the summation and the final division by \(n\).
    • Summation: The cost of \(2p+1\) FLOPs is incurred for each of the \(n\) data points. This gives a running total of \(n \times (2p+1) = 2np + n\) FLOPs to compute all \(n\) squared errors. These \(n\) scalar values must then be summed together, which requires an additional \(n-1\) additions.
      FLOP Count: \((2np + n) + (n-1) = 2np + 2n - 1\) FLOPs.
    • Division: The final step is to divide the total sum by \(n\) to get the average. This is one final division.
      FLOP Count: \(1\) FLOP.

The exact total number of floating-point operations is therefore \((2np + 2n - 1) + 1 = 2np + 2n\). To translate this precise count into Big-O notation, we identify the dominant term as the problem size (both \(n\) and \(p\)) grows large. The term \(2np\) grows faster than the term \(2n\). We ignore the constant factor of 2, giving us a final complexity of \(O(np)\). This tells us that the time to evaluate the cost function scales linearly with both the number of data points and the number of features.

2.1.2 Example 2: Finding the “Center” of a Data Cloud

Suppose we have a collection of \(n\) data points, represented by vectors \(\mathbf{a}_1, \mathbf{a}_2, \dots, \mathbf{a}_n\), all in \(\mathbb{R}^p\). This could represent the locations of customers, the feature vectors of a set of images, or any other collection of data. We want to find a single vector \(\mathbf{c} \in \mathbb{R}^p\) that represents the “center” of this cloud of points.

The Model. In this case, our “model” is simply the candidate center vector, \(\mathbf{c}\).

The Cost Function. A good center should be close to all the data points. We can define the cost as the sum of the squared Euclidean distances from our candidate center \(\mathbf{c}\) to each data point \(\mathbf{a}_i\). Recall that the squared distance between two vectors is \(\|\mathbf{a}_i - \mathbf{c}\|_2^2\).

The Objective. The total cost to be minimized is the sum of these squared distances:

\[ \min_{\mathbf{c} \in \mathbb{R}^p} \left\{ f(\mathbf{c}) = \sum_{i=1}^n \|\mathbf{a}_i - \mathbf{c}\|_2^2.\right\} \]

This objective function takes a vector \(\mathbf{c}\) and returns a scalar measure of how “off-center” it is. Finding the vector \(\mathbf{c}^\star\) that minimizes this function gives us the arithmetic mean, or centroid, of the data points. This is the core calculation performed in every step of the K-Means clustering algorithm (not fully described here). More details about this objective below.

Complexity Analysis. To evaluate \(f(\mathbf{c})\), we must compute \(n\) distance norms. Each squared norm \(\|\mathbf{a}_i - \mathbf{c}\|_2^2\) involves a vector subtraction (\(p\) FLOPs) and an inner product with itself (\(2p-1\) FLOPs), for a total of \(O(p)\) work. The overall complexity is therefore \(O(np)\).

2.1.3 Example 3: Binary Classification

Let’s return to the data setting of Example 1, but with a different goal. Instead of predicting a price, we want to classify each item into one of two categories, which we will label as \(+1\) and \(-1\). For instance, based on a vector of medical measurements \(\mathbf{a}_i\), we want to predict whether a patient has a disease (\(y_i = +1\)) or not (\(y_i = -1\)).

The Model. As before, we can use a linear model, \(\hat{y}_i = \langle \mathbf{a}_i, \mathbf{w} \rangle\). However, we don’t interpret this scalar value directly. Instead, we use its sign. We predict class \(+1\) if \(\langle \mathbf{a}_i, \mathbf{w} \rangle > 0\) and class \(-1\) if \(\langle \mathbf{a}_i, \mathbf{w} \rangle < 0\). For more careful readers, the vector \(\mathbf{w}\) defines a hyperplane through the origin that separates the space into two half-spaces.

The Cost Function. A good classifier makes few mistakes. A mistake occurs if the true label is \(y_i = +1\) but our model predicts a negative score, or if \(y_i = -1\) and our model predicts a positive score. Notice that in both cases, the product between the scalars \(y_i \cdot \langle \mathbf{a}_i, \mathbf{w} \rangle\) will be negative. A correct classification results in a positive product.

This suggests that we want to find a \(\mathbf{w}\) that makes \(y_i \cdot \langle \mathbf{a}_i, \mathbf{w} \rangle\) positive for all \(i\). We can define a cost function that penalizes negative values. A simple and powerful choice is the hinge loss:

\[ L(\mathbf{w}; \mathbf{a}_i, y_i) = \max(0, 1 - y_i \cdot \langle \mathbf{a}_i, \mathbf{w} \rangle). \]

This function is zero if the classification is “confidently correct” (i.e., \(y_i \cdot \langle \mathbf{a}_i, \mathbf{w} \rangle \ge 1\)), and it increases linearly the more “wrong” the prediction is.

The Objective. The overall objective is to minimize the average hinge loss over the dataset:

\[ \min_{\mathbf{w} \in \mathbb{R}^p} \left\{f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n \max(0, 1 - y_i \langle \mathbf{a}_i, \mathbf{w} \rangle) \right \}. \]

Finding the \(\mathbf{w}^\star\) that minimizes this function is the basis of the Support Vector Machine (SVM), a cornerstone algorithm in ML (to be taught or at least better understood in the following ML classes).

2.2 The Quest for the Minimum: An Intro to Optimization

The examples above share a common structure. They all culminate in an optimization problem:

\[ \underset{\mathbf{x} \in \mathbb{R}^p}{\text{min}} f(\mathbf{x}). \]

Here, \(\mathbf{x}\) is the vector we are searching for (e.g., \(\mathbf{w}\) or \(\mathbf{c}\) in the examples above; \(\mathbf{x}\) is used as notation for optimization parameters in the classical optimization community), and \(f(\mathbf{x})\) is the cost function that measures how good a given \(\mathbf{x}\) is. Finding the vector \(\mathbf{x}^\star\) that achieves the lowest possible value of \(f(\mathbf{x})\) is our task.

2.2.1 A Pessimistic View

At first glance, this seems daunting. In general, optimization problems are unsolvable. If \(f(\mathbf{x})\) is an arbitrary, complicated function, the only way to find its minimum would be to evaluate it at every possible point \(\mathbf{x}\), which is impossible. For an algorithm to have any hope of succeeding, the function \(f\) must have some structure.

2.2.2 When We Can Find Exact Solutions

For a very small class of problems, we can find the exact, perfect solution using a closed-form formula. You have already mastered one such case. Consider a univariate quadratic function:

\[ f(x) = ax^2 + bx + c. \]

From basic calculus, we know that the minimum (or maximum) occurs where the derivative is zero: \(f'(x) = 2ax + b = 0\). This gives the exact solution:

\[ x^\star = -\frac{b}{2a}. \]

There is no need for approximation or iteration; there is no need of a recursive algorithm trying to improve an intermediate estimate. This is a closed-form solution.

It turns out that another one of our motivating examples, finding the center of a data cloud, also has a beautiful closed-form solution. Recall the problem: given \(n\) data points \(\mathbf{a}_1, \dots, \mathbf{a}_n\) in \(\mathbb{R}^p\), we want to find the vector \(\mathbf{c} \in \mathbb{R}^p\) that minimizes the sum of squared Euclidean distances:

\[ f(\mathbf{c}) = \sum_{i=1}^n \|\mathbf{a}_i - \mathbf{c}\|_2^2. \]

Let’s build our intuition by first considering the simplest possible case: when all our data points lie on a line (i.e., \(p=1\)). In this case, each \(\mathbf{a}_i\) is just a scalar \(a_i\), and our candidate center \(\mathbf{c}\) is a scalar \(c\). The objective function becomes:

\[ f(c) = \sum_{i=1}^n (a_i - c)^2. \]

If we expand this expression, we get:

\[ \begin{aligned} f(c) &= \sum_{i=1}^n (a_i^2 - 2a_ic + c^2) \\ &= \sum_{i=1}^n a_i^2 - \sum_{i=1}^n 2a_ic + \sum_{i=1}^n c^2 \\ &= \left(\sum_{i=1}^n a_i^2\right) - 2c\left(\sum_{i=1}^n a_i\right) + nc^2. \end{aligned} \]

This is a quadratic function of our variable \(c\), in the familiar form \(Ac^2 + Bc + C\), where \(A=n\), \(B=-2\sum a_i\), and \(C=\sum a_i^2\). Since \(A=n>0\), this is an upward-opening parabola. The minimum of a parabola occurs at its vertex, which is located at \(c = -B/(2A)\). Plugging in our values for \(A\) and \(B\):

\[ c^\star = -\frac{-2\sum_{i=1}^n a_i}{2n} = \frac{\sum_{i=1}^n a_i}{n}. \]

This is simply the arithmetic mean (the average) of the data points.

Now, the key insight is that the multi-dimensional problem can be broken down into \(p\) independent one-dimensional problems. Let’s look at the objective function again, this time expanding the norm:

\[ f(\mathbf{c}) = \sum_{i=1}^n \|\mathbf{a}_i - \mathbf{c}\|_2^2 = \sum_{i=1}^n \sum_{j=1}^p (a_{ij} - c_j)^2. \]

where \(a_{ij}\) is the \(j\)-th component of vector \(\mathbf{a}_i\) and \(c_j\) is the \(j\)-th component of our candidate center \(\mathbf{c}\). We can swap the order of summation:

\[ f(\mathbf{c}) = \sum_{j=1}^p \left( \sum_{i=1}^n (a_{ij} - c_j)^2 \right). \]

Look closely at this expression. The total cost is a sum of \(p\) terms. The first term, \(\sum_{i=1}^n (a_{i1} - c_1)^2\), only depends on the first component of our center, \(c_1\). The second term only depends on \(c_2\), and so on. To minimize the total sum, we can therefore minimize each term independently.

For each dimension \(j\), we must solve:

\[ \min_{c_j} \sum_{i=1}^n (a_{ij} - c_j)^2. \]

This is precisely the one-dimensional problem we just solved! The optimal solution for the \(j\)-th component of our center, \(c_j^\star\), must be the average of the \(j\)-th components of all the data vectors:

\[ c_j^\star = \frac{1}{n} \sum_{i=1}^n a_{ij}. \]

Since this holds for every dimension \(j=1, \dots, p\), the optimal center vector \(\mathbf{c}^\star\) is the vector whose components are these averages. This is nothing more than the vector average of all the data points:

\[ \mathbf{c}^\star = \frac{1}{n} \sum_{i=1}^n \mathbf{a}_i. \]

Thus, we have found a closed-form solution for the centroid problem without formally using multivariate calculus, by reducing it to a familiar single-variable problem.

Unfortunately, such closed-form solutions are rare. For most interesting problems in AI, including the classifier example and most variants of least squares, no such simple formula exists. We need a different approach.

2.2.3 An Iterative Approach: The Intuition of Descent

If we cannot jump to the solution directly, perhaps we can walk there. This is the core idea of iterative methods. We start with an initial guess, \(\mathbf{x}_0\), and iteratively refine it to produce a sequence of better guesses, \(\mathbf{x}_1, \mathbf{x}_2, \dots\), that hopefully converge to the solution.

The key question is: if we are at a point \(\mathbf{x}_t\), how do we choose the next point \(\mathbf{x}_{t+1}\)? Imagine you are standing on a hillside in a thick fog. Your goal is to reach the bottom of the valley. You cannot see the landscape, but you can feel the slope of the ground directly under your feet. The most rational strategy is to identify the direction of steepest descent and take a small step in that direction.

This is the central intuition behind gradient descent. We will find a “promising direction” and update our current estimate:

\[ \mathbf{x}_{t+1} = \mathbf{x}_t + (\text{a small step in a promising direction}). \]

Let’s test this intuition on a problem where we already know the answer.

Example 2.1 (Iterative Solution to a Quadratic). Consider minimizing \(f(x) = 3x^2 + 4x - 2\). From the formula, we know the exact minimum is at \(x^\star = -b/(2a) = -4/(2 \cdot 3) = -2/3 \approx -0.667\).

Let’s pretend we don’t know this. From Calculus 101, we know that the derivative of a univariate function provides information about the slope of the function. The derivative is \(f'(x) = 6x + 4\). The direction of steepest descent (i.e., of the direction where the slope points downwards and the function value decreases) is the opposite of the slope’s sign. So, a “promising direction” is proportional to \(-(6x+4)\). Let’s define our iterative update rule:

\[ x_{t+1} = x_t - \eta (6x_t + 4), \]

where \(\eta\) is a small positive number called the step size or learning rate. Remember above that our strategy is exactly to do:

\[ \mathbf{x}_{t+1} = \mathbf{x}_t + (\text{a small step in a promising direction}). \]

Thus, we just choose this small step in a promising direction to be: \(- \eta (6x_t + 4)\). Let’s choose \(\eta = 0.1\) and start with a random guess, say \(x_0 = 2\).

  • \(t=0\): \(x_1 = x_0 - 0.1(6x_0 + 4) = 2 - 0.1(12+4) = 2 - 1.6 = 0.4\).
  • \(t=1\): \(x_2 = x_1 - 0.1(6x_1 + 4) = 0.4 - 0.1(2.4+4) = 0.4 - 0.64 = -0.24\).
  • \(t=2\): \(x_3 = x_2 - 0.1(6x_2 + 4) = -0.24 - 0.1(-1.44+4) = -0.24 - 0.256 = -0.496\).
  • \(t=3\): \(x_4 = x_3 - 0.1(6x_3 + 4) = -0.496 - 0.1(-2.976+4) = -0.496 - 0.1024 = -0.5984\).

After just a few steps, our iterative method is getting very close to the true solution of \(-0.667\). This demonstrates a powerful principle: even when a closed-form solution exists, an iterative method can approximate it. For the vast majority of problems where no such formula exists, iterative methods are our only hope.

Let’s now analyze this behavior mathematically. First, rearrange the update rule to group the \(x_t\) terms:

\[ x_{t+1} = x_t - 6\eta x_t - 4\eta = (1 - 6\eta)x_t - 4\eta. \]

This is a linear recurrence relation (familiar from an algorithms course). To understand its behavior, it is helpful to analyze the distance from our iterate \(x_t\) to the true solution \(x^\star = -2/3\). Let’s define the error at step \(t\) as \(\delta_t = x_t - x^\star\). Then \(x_t = \delta_t + x^\star\). Substituting this into the recurrence gives:

\[ \begin{aligned} \delta_{t+1} + x^\star &= (1 - 6\eta)(\delta_t + x^\star) - 4\eta \\ \delta_{t+1} &= (1 - 6\eta)\delta_t + (1 - 6\eta)x^\star - x^\star - 4\eta \\ \delta_{t+1} &= (1 - 6\eta)\delta_t - 6\eta x^\star - 4\eta \end{aligned} \]

Now, we substitute the value of our solution, \(x^\star = -2/3\):

\[ \begin{aligned} \delta_{t+1} &= (1 - 6\eta)\delta_t - 6\eta(-2/3) - 4\eta \\ &= (1 - 6\eta)\delta_t + 4\eta - 4\eta \\ &= (1 - 6\eta)\delta_t. \end{aligned} \]

This reveals a very simple geometric relationship: the error at step \(t+1\) is just the error at step \(t\) multiplied by a constant factor of \((1-6\eta)\).

We can now easily unroll this recursion all the way back to our initial error, \(\delta_0 = x_0 - x^\star\):

\[ \begin{aligned} \delta_t &= (1 - 6\eta) \delta_{t-1} \\ &= (1 - 6\eta) \cdot \left((1 - 6\eta) \delta_{t-2}\right) = (1 - 6\eta)^2 \delta_{t-2} \\ &= \dots \\ &= (1 - 6\eta)^t \delta_0. \end{aligned} \]

Translating this back to our iterates \(x_t\), we have a closed-form solution for the entire sequence:

\[ x_t - x^\star = (1 - 6\eta)^t (x_0 - x^\star), \quad \text{or} \quad x_t = x^\star + (1 - 6\eta)^t(x_0 - x^\star). \]

This equation tells us everything about the convergence of the algorithm. The sequence \(\{x_t\}\) will get close to \(x^\star\) if and only if the term \((1 - 6\eta)^t\) goes to zero as \(t \to \infty\). This occurs when the base of the exponent has an absolute value less than 1:

\[ |1 - 6\eta| < 1. \]

This inequality is satisfied if and only if \(0 < \eta < 1/3\). This is a crucial finding: our iterative method is only guaranteed to converge if the learning rate is chosen within a specific range.

In our numerical example, we chose \(\eta=0.1\). Since \(0 < 0.1 < 1/3 \approx 0.333\), our choice was valid and convergence was guaranteed. The contraction factor was \(|1 - 6(0.1)| = |0.4| = 0.4\). This means that with every step, the distance to the true solution is reduced by 60%.

Let’s check our formula. For \(t=4\):

\[ \begin{aligned} x_4 &= -\frac{2}{3} + (0.4)^4 \left(2 - (-\frac{2}{3})\right) \\ &= -\frac{2}{3} + (0.0256)\left(\frac{8}{3}\right) \\ &\approx -0.6667 + 0.0683 = -0.5984. \end{aligned} \]

This matches our step-by-step calculation perfectly. This analysis not only confirms our observation but provides a powerful predictive tool and a formal justification for why the iterative method works, all while highlighting the critical importance of the step size parameter \(\eta\).

2.2.4 From Norms to Objectives: Why \(\ell_1\), \(\ell_2\), \(\ell_\infty\) Make Different Models

We have now written down three cost functions and asked what it means to minimize them. Step back and notice a unifying pattern: choosing a loss is choosing a norm, and choosing a regularizer is choosing a second norm. Chapter 1 introduced norms as a way to measure the size of a vector. Most cost functions in §2.1 are built from a norm applied to a residual or disagreement vector: the vector of errors between what our model predicts and what we observe. This single observation unifies the dozen or so named methods that the next several chapters will introduce.

Where norms enter an objective. A typical learning problem has the shape

\[ \underset{\mathbf{x} \in \mathbb{R}^p}{\text{min}} \;\; \underbrace{\|\,\mathbf{r}(\mathbf{x})\,\|_\alpha}_{\text{data-fit (residual norm)}} \;+\; \lambda \cdot \underbrace{\|\mathbf{x}\|_\beta}_{\text{regularizer (parameter norm)}}, \]

where \(\mathbf{r}(\mathbf{x})\in\mathbb{R}^n\) is a vector of \(n\) residuals (one per data point), and \(\lambda \geq 0\) controls how much we penalize large parameter vectors. The two norm choices \((\alpha,\beta)\) are independent design decisions. Different \((\alpha,\beta)\) pairs produce very different estimators, with very different sensitivity to outliers, conditioning behavior, and sparsity patterns. This entire chapter, and most of any subsequent machine-learning course, can be read as a guided tour of this \((\alpha,\beta)\) table.

Three residual norms, three stories. Suppose we are fitting a single constant \(w\) to a tiny dataset \(\mathbf{y}=[1,2,3,4,100]^\top\) (the \(100\) is an outlier). The optimal \(w^*\) depends entirely on which norm we minimize:

  • \(\ell_2^2\) residuals (least squares). Minimizing \(\tfrac{1}{n}\sum_i (y_i - w)^2\) gives \(w^* = \tfrac{1}{n}\sum_i y_i = 22.0\), the mean. The squared loss grows quadratically with the size of any single residual, so the outlier \(100\) contributes about \(10^4\) to the sum of squares when \(w\) is near the other four points; the estimate is pulled toward it.
  • \(\ell_1\) residuals (least absolute deviations). Minimizing \(\sum_i |y_i - w|\) gives \(w^* = \mathrm{median}(\mathbf{y}) = 3.0\). The absolute loss grows only linearly, so the outlier contributes \(100\): still large, but no longer dominant. The median is famously robust to outliers.
  • \(\ell_\infty\) residuals (Chebyshev / minimax). Minimizing \(\max_i |y_i - w|\) gives \(w^* = \tfrac{1}{2}(\min_i y_i + \max_i y_i) = 50.5\), the midrange. This choice is appropriate when worst-case error is what matters, as with signal-processing tolerances rather than data analysis.

The same five numbers produce three different “best constants” because the three norms ask three different questions about wrongness.

Two parameter-norm regularizers, two stories. The regularizer term \(\lambda \|\mathbf{x}\|_\beta\) exists to discourage large parameter vectors: it improves conditioning, prevents overfitting, and (depending on \(\beta\)) may force coefficients to be exactly zero. The two dominant choices are

  • \(\ell_2^2\) on parameters (ridge / Tikhonov). The penalty \(\lambda\|\mathbf{x}\|_2^2\) shrinks every coordinate smoothly toward zero in proportion to its magnitude; generically, no coordinate is set exactly to zero. The closed form is the trivial modification \(\mathbf{x}^\star = (\mathbf{A}^\top \mathbf{A} + \lambda \mathbf{I})^{-1}\mathbf{A}^\top \mathbf{y}\), which is well-defined for \(\lambda > 0\) even when \(\mathbf{A}^\top\mathbf{A}\) is rank-deficient, so ridge always produces a unique answer. (For an unregularized fix to rank-deficient \(\mathbf{A}^\top \mathbf{A}\), the Moore–Penrose pseudoinverse via the SVD of Chapter 5 is the principled alternative.)
  • \(\ell_1\) on parameters (LASSO). The penalty \(\lambda\|\mathbf{x}\|_1\) also shrinks parameters, but for large enough \(\lambda\) it sets some of them exactly to zero. This is feature selection done by the optimizer rather than by hand. The geometric reason is sharp: the \(\ell_1\) unit ball is a diamond with corners on the coordinate axes (see the unit-ball figure in Chapter 1, § Norms and Distances) and the level sets of the data-fit term generically first touch a diamond at a corner, that is, at a point where one or more coordinates vanish.

The \((\alpha,\beta)\) table. The table below summarizes the most-used combinations. Almost every named regression method you will encounter in a later machine-learning course is one of these cells.

ResidualParam. normNameOne-line bias
\(\ell_2^2\)noneOLS / least squaressmooth, sensitive to outliers
\(\ell_2^2\)\(\ell_2^2\)ridge / Tikhonovsmooth shrinkage, no sparsity
\(\ell_2^2\)\(\ell_1\)LASSOsparse solution
\(\ell_2^2\)\(\ell_1\!+\!\ell_2^2\)elastic netsparse with grouped features
\(\ell_1\)noneLAD / median regressionrobust to outliers
\(\ell_1\)\(\ell_1\)robust + sparseboth above
\(\ell_\infty\)noneChebyshev / minimax fitworst-case bounded error

Default for this chapter. For most of the rest of this chapter we will keep the default \(\alpha=2\) (squared \(\ell_2\) residuals) without a regularizer, because its gradient is the simplest and the optimization landscape is the cleanest: it is a quadratic, which we already know how to minimize from Chapter 1’s discussion of quadratic functions. The choices \(\alpha=1\) and \(\alpha=\infty\) produce non-smooth objectives that require additional machinery (subgradients, proximal operators); we revisit them later in the course. But keep the table above in mind: every time we write down a least-squares problem in what follows, we are making a deliberate norm choice, and a different norm choice would lead to a different model.

Code session · Section 2.2.4 Skip to Section 2.3

Three norms, three best constants

We fit one constant w to the five numbers 1, 2, 3, 4 and 100 under the three residual norms of this section, trying every w from -10 to 110 in steps of 0.01.

show setup
import numpy as np
1y = np.array([1.0, 2.0, 3.0, 4.0, 100.0])      # the 100 is an outlier
2w = np.linspace(-10, 110, 12001)                # candidate constants, step 0.01
3r = y[None, :] - w[:, None]                     # residuals of every candidate
4l2 = np.sum(r**2, axis=1)                       # squared l2 norm of the residuals
5l1 = np.sum(np.abs(r), axis=1)                  # l1 norm
6linf = np.max(np.abs(r), axis=1)                # l-infinity norm
7for name, loss in [("l2^2", l2), ("l1", l1), ("l_inf", linf)]:
8    print(f"{name:6} best w = {w[np.argmin(loss)]:6.2f}")
9print("mean", y.mean(), " median", np.median(y), " midrange", (y.min() + y.max()) / 2)
Recorded output
l2^2   best w =  22.00
l1     best w =   3.00
l_inf  best w =  50.50
mean 22.0  median 3.0  midrange 50.5
0 25k 50k best w = 22 ℓ₂² loss 0 240 480 best w = 3 ℓ₁ loss 0 60 120 best w = 50.5 ℓ∞ loss 0 20 40 60 80 100 candidate constant w

Each panel is one loss against w, with its best w marked. Squared residuals pick the mean, 22: the outlier pulls the answer far from the other four numbers. Absolute residuals pick the median, 3. The largest residual picks the midrange, 50.5, halfway between 1 and 100.

Recorded on an Apple M1 Max laptop, macOS 26.6.2, Python 3.13.7, NumPy 2.4.6, 2026-11-30.

2.3 Formalizing Direction: The Gradient

Our notion of “steepest descent” needs a rigorous, multi-dimensional definition. This is the role of the derivative and the gradient.

2.3.1 Derivatives

For a single-variable function \(f(x)\), the derivative \(f'(x)\) gives the slope of the line tangent to the function at point \(x\). To compute these slopes for various functions without resorting to the limit definition every time, we rely on a set of fundamental differentiation rules. Mastering these rules is essential for calculating the gradients that will guide our optimization algorithms.

Fundamental Rules of Differentiation. Let \(c\) and \(n\) be constants, and let \(f(x)\) and \(g(x)\) be differentiable univariate functions.

  • Constant Rule: The derivative of any constant is zero. \[ (c)' := \frac{\partial c}{\partial x} = 0 \]
  • Power Rule: Used for polynomials and terms involving powers of \(x\). \[ (x^n)' := \frac{\partial x^n}{\partial x} = nx^{n-1} \]
  • Sum Rule: The derivative of a sum is the sum of the derivatives. \[ (f(x) + g(x))' := \frac{\partial (f(x) + g(x))}{\partial x} = f'(x) + g'(x) \]
  • Product Rule: Used when two functions are multiplied together. \[ (f(x)g(x))' := \frac{\partial (f(x)g(x))}{\partial x} = f'(x)g(x) + f(x)g'(x) \]
  • Quotient Rule: Used when one function is divided by another. \[ \left(\frac{f(x)}{g(x)}\right)' = \frac{f'(x)g(x) - f(x)g'(x)}{[g(x)]^2} \]
  • Chain Rule (Composition Rule): Perhaps the most important rule, used for nested functions. It states that the derivative is the derivative of the “outside” function (evaluated at the “inside” function) multiplied by the derivative of the “inside” function. \[ (f(g(x)))' = f'(g(x)) \cdot g'(x) \]

Additionally, it is useful to know the derivatives of common elementary functions, such as \((e^x)' = e^x\) and \((\sin x)' = \cos x\).

Examples of Derivative Computation. Let’s apply these rules to a few examples of increasing difficulty.

Example 2.2 (Easy: A Simple Polynomial). Find the derivative of \(f(x) = 5x^3 - 7x + 2\).

  • We use the Sum Rule to differentiate term by term: \((5x^3)' - (7x)' + (2)'\).
  • For the first term, we use the Power Rule: \((5x^3)' = 5 \cdot (3x^{3-1}) = 15x^2\).
  • For the second term, we again use the Power Rule (since \(x = x^1\)): \((7x)' = 7 \cdot (1x^{1-1}) = 7x^0 = 7\).
  • For the third term, we use the Constant Rule: \((2)' = 0\).

Combining these results gives the final derivative:

\[ f'(x) = 15x^2 - 7. \]

Example 2.3 (Medium: Product of Functions). Find the derivative of \(f(x) = x^2 e^x\). This function is a product of two simpler functions, \(g(x) = x^2\) and \(h(x) = e^x\).

  • We apply the Product Rule: \(f'(x) = g'(x)h(x) + g(x)h'(x)\).
  • First, we find the derivatives of the individual parts:
    • \(g'(x) = (x^2)' = 2x\) (using the Power Rule).
    • \(h'(x) = (e^x)' = e^x\) (a standard derivative).
  • Now, we substitute these into the product rule formula: \[ f'(x) = (2x)(e^x) + (x^2)(e^x). \]

For a cleaner expression, we can factor out the common term \(e^x\):

\[ f'(x) = e^x(2x + x^2). \]

Example 2.4 (Hard: Combination of Quotient and Chain Rules). Find the derivative of \(f(x) = \frac{\sqrt{x^2+1}}{x}\). This is a quotient, and the numerator is a composite function, requiring multiple rules.

  • We apply the Quotient Rule first. Let the numerator be \(g(x) = \sqrt{x^2+1}\) and the denominator be \(h(x) = x\). The rule is \(f'(x) = \frac{g'(x)h(x) - g(x)h'(x)}{[h(x)]^2}\).
  • We need the derivatives \(g'(x)\) and \(h'(x)\).
    • The denominator is simple: \(h'(x) = (x)' = 1\).
    • For the numerator, \(g(x) = (x^2+1)^{1/2}\), we must use the Chain Rule.
      • The “outside” function is \(u^{1/2}\), whose derivative is \(\frac{1}{2}u^{-1/2}\).
      • The “inside” function is \(u(x) = x^2+1\), whose derivative is \(2x\).
      • Applying the chain rule: \(g'(x) = \frac{1}{2}(x^2+1)^{-1/2} \cdot (2x) = \frac{x}{\sqrt{x^2+1}}\).
  • Now we substitute all the pieces into the quotient rule: \[ f'(x) = \frac{\left(\frac{x}{\sqrt{x^2+1}}\right) \cdot (x) - (\sqrt{x^2+1}) \cdot (1)}{x^2}. \]
  • To simplify, we clean up the numerator: \[ f'(x) = \frac{\frac{x^2}{\sqrt{x^2+1}} - \sqrt{x^2+1}}{x^2}. \]

    To combine the terms in the numerator, we find a common denominator:

    \[ f'(x) = \frac{\frac{x^2 - (x^2+1)}{\sqrt{x^2+1}}}{x^2} = \frac{\frac{-1}{\sqrt{x^2+1}}}{x^2}. \]

The final simplified derivative is:

\[ f'(x) = -\frac{1}{x^2\sqrt{x^2+1}}. \]

2.3.2 The Taylor Series Expansion

The Taylor series provides a way to represent a function as an infinite sum of terms, calculated from the values of the function’s derivatives at a single point. It is a powerful method for approximating complex functions with simpler polynomials.

Definition 2.1 (Taylor Series). If a function \(f(x)\) is infinitely differentiable at a point \(x_0\), its Taylor series centered at \(x_0\) is given by the power series:

\[ \begin{aligned} T_{x_0}(x) &= \sum_{k=0}^{\infty} \frac{f^{(k)}(x_0)}{k!}(x - x_0)^{k} \\ &= f(x_0) + \frac{f'(x_0)}{1!}(x-x_0) + \frac{f''(x_0)}{2!}(x-x_0)^2 \\ &\quad \quad \quad + \frac{f'''(x_0)}{3!}(x-x_0)^3 + \cdots \end{aligned} \]

where \(f^{(k)}(x_0)\) denotes the \(k\)-th derivative of \(f\) evaluated at the point \(x_0\), and \(k!\) is the factorial of \(k\).

For many functions (the analytic ones) and points \(x\) close enough to \(x_0\), it holds that \(f(x) = T_{x_0}(x)\). More importantly for our purposes, even if we cannot compute the entire infinite sum, we can truncate it after a few terms to get a very good polynomial approximation of \(f(x)\) for values of \(x\) near the center point \(x_0\).

2.3.3 The First-Order Taylor Approximation

The simplest and most fundamental approximation is the first-order Taylor approximation, obtained by truncating the series after the \(k=1\) term:

\[ f(x) \approx f(x_0) + f'(x_0)(x-x_0). \]

This approximation is the foundation for gradient-based optimization. It tells us that if we are at a point \(x_0\) and make a small change to a new point \(x\), the new function value \(f(x)\) will be approximately the old value \(f(x_0)\) plus a change proportional to the derivative at \(x_0\).

This expression is called a linear approximation because its graph is a line: it is an affine function of the variable \(x\). To see this, let’s rearrange the terms. At a fixed point \(x_0\), the values \(f(x_0)\) and \(f'(x_0)\) are just constants. If we let \(m = f'(x_0)\) (the slope) and \(b = f(x_0) - f'(x_0)x_0\) (the y-intercept), the approximation becomes \(f(x) \approx mx + b\), which is the familiar equation of a line. This line is precisely the tangent line to the graph of \(f(x)\) at the point \((x_0, f(x_0))\), as illustrated in Figure 2.2.

Figure 2.2: A function f(x) and its first-order Taylor approximation at the point x₀.
Figure 2.2: A function \(f(x)\) and its first-order Taylor approximation at the point \(x_0\). The approximation is the tangent line to the function at that point, sharing both the same value and the same slope. For values of \(x\) close to \(x_0\), the line is a very good approximation of the function.

Example 2.5 (Easy: A Polynomial). Find the Taylor series for \(f(x) = 2x^2 + 3x - 1\) centered at \(x_0=1\).

  • Derivatives:
    • \(f(x) = 2x^2 + 3x - 1 \implies f(1) = 2+3-1 = 4\).
    • \(f'(x) = 4x + 3 \implies f'(1) = 4+3 = 7\).
    • \(f''(x) = 4 \implies f''(1) = 4\).
    • \(f'''(x) = 0\), and all higher derivatives are also zero.
  • Full Taylor Series: Since all derivatives beyond the second are zero, the “infinite” series terminates. \[ \begin{aligned} T_1(x) &= f(1) + \frac{f'(1)}{1!}(x-1) + \frac{f''(1)}{2!}(x-1)^2 \\ &= 4 + 7(x-1) + \frac{4}{2}(x-1)^2 \\ &= 4 + 7x - 7 + 2(x^2 - 2x + 1) = 2x^2 + 3x - 1. \end{aligned} \]

    Observe that the Taylor series for a polynomial is just the polynomial itself.

  • First-Order Approximation: Truncating the series gives: \[ f(x) \approx 4 + 7(x-1). \]

Example 2.6 (Medium: An Exponential Function). Find the Taylor series for \(f(x) = e^{2x}\) centered at \(x_0=0\).

  • Derivatives: We observe a clear pattern.
    • \(f(x) = e^{2x} \implies f(0) = e^0 = 1\).
    • \(f'(x) = 2e^{2x} \implies f'(0) = 2\).
    • \(f''(x) = 4e^{2x} \implies f''(0) = 4\).
    • \(f^{(k)}(x) = 2^k e^{2x} \implies f^{(k)}(0) = 2^k\).
  • Full Taylor Series: We substitute the general \(k\)-th derivative into the series formula: \[ T_0(x) = \sum_{k=0}^{\infty} \frac{f^{(k)}(0)}{k!}x^k = \sum_{k=0}^{\infty} \frac{2^k}{k!}x^k = 1 + 2x + \frac{4}{2!}x^2 + \frac{8}{3!}x^3 + \cdots \]
  • First-Order Approximation: The first two terms of the series give us the linear approximation: \[ f(x) \approx 1 + 2x. \]

Example 2.7 (Hard: A Logarithmic Function). Find the Taylor series for \(f(x) = \ln(1+x)\) centered at \(x_0=0\).

  • Derivatives: The derivatives follow a more complex, alternating pattern.
    • \(f(x) = \ln(1+x) \implies f(0) = \ln(1) = 0\).
    • \(f'(x) = (1+x)^{-1} \implies f'(0) = 1\).
    • \(f''(x) = -1(1+x)^{-2} \implies f''(0) = -1\).
    • \(f'''(x) = 2(1+x)^{-3} \implies f'''(0) = 2\).
    • \(f^{(k)}(x) = (-1)^{k-1}(k-1)!(1+x)^{-k} \implies f^{(k)}(0) = (-1)^{k-1}(k-1)!\) for \(k \ge 1\).
  • Full Taylor Series: We substitute this pattern into the series formula. For \(k \ge 1\): \[ \frac{f^{(k)}(0)}{k!}x^k = \frac{(-1)^{k-1}(k-1)!}{k!}x^k = \frac{(-1)^{k-1}}{k}x^k. \]

    The full series (starting from \(k=1\) since \(f(0)=0\)) is:

    \[ T_0(x) = \sum_{k=1}^{\infty} \frac{(-1)^{k-1}}{k}x^k = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \cdots \]
  • First-Order Approximation: Taking only the first non-zero term (\(k=1\)) gives: \[ f(x) \approx x. \]

This approximation is the foundation for our optimization algorithms. It tells us that if we are at a point \(x_0\) and are considering moving to a nearby point \(x\), we can predict the new function value using a simple line. Let’s define the step we take as \(\delta = x - x_0\). The new point is then \(x = x_0 + \delta\). Substituting this into the Taylor approximation gives us an estimate of the function value after taking the step \(\delta\):

\[ f(x_0 + \delta) \approx f(x_0) + f'(x_0)\delta. \]

Our goal is to choose a step \(\delta\) that causes the largest possible decrease in the function’s value. To minimize \(f(x_0 + \delta)\), we can instead minimize its linear approximation. Since \(f(x_0)\) is a constant value at our current position, this is equivalent to finding the step \(\delta\) that makes the term \(f'(x_0)\delta\) as negative as possible.

This leads to the local optimization problem for finding the best step:

\[ \min_{\delta} \{ f'(x_0)\delta \}. \]

At first, this problem seems ill-posed. If \(f'(x_0)\) is positive, we can make \(\delta\) an arbitrarily large negative number and drive the expression to \(-\infty\). If \(f'(x_0)\) is negative, we can make \(\delta\) an arbitrarily large positive number. However, we must remember that the Taylor approximation is only accurate for a small step \(\delta\). This means we cannot let \(\delta\) be arbitrarily large. We are primarily interested in finding the best direction for a small step.

To find the best direction, let’s constrain the size of our step. The direction of the step is simply its sign. So, what is the best direction \(\delta\) with a fixed small magnitude?

  • If \(f'(x_0) > 0\) (the function is sloping upwards), we need to choose a negative \(\delta\) to make \(f'(x_0)\delta\) negative. The direction is negative.
  • If \(f'(x_0) < 0\) (the function is sloping downwards), we need to choose a positive \(\delta\) to make \(f'(x_0)\delta\) negative. The direction is positive.

In both cases, the optimal direction for the step \(\delta\) is the one opposite to the sign of the derivative, \(f'(x_0)\).

Furthermore, it is natural to take a larger step when the slope is very steep and a smaller step when the slope is nearly flat. The magnitude of the derivative, \(|f'(x_0)|\), measures this steepness. A simple and powerful choice for our step \(\delta\) is one that is proportional to both the optimal direction (opposite to the sign of \(f'(x_0)\)) and the magnitude of the slope (\(|f'(x_0)|\)). Combining these, we want our step to be proportional to \(-f'(x_0)\).

Let’s introduce a small positive constant, \(\eta > 0\), called the learning rate or step size, to be our constant of proportionality. This gives us the optimal local step:

\[ \delta = -\eta f'(x_0). \]

This choice of step moves us in the direction of steepest descent, with a magnitude scaled by both the learning rate and the steepness of the function at the current point.

This logic directly gives rise to the gradient descent algorithm. If our current position is \(x_t\), we compute the derivative \(f'(x_t)\) and update our position using the step we just derived:

\[ x_{t+1} = x_t + \delta = x_t - \eta f'(x_t). \]

This formalizes the intuitive procedure we used earlier. For the example \(f(x) = 3x^2 + 4x - 2\), the derivative is \(f'(x) = 6x+4\). The gradient descent update rule derived from minimizing the first-order Taylor approximation is:

\[ x_{t+1} = x_t - \eta (6x_t + 4). \]

This is precisely the update rule we discovered through intuition. We now see that it has a solid mathematical foundation (or one of the many intuitions): each step of gradient descent is an attempt to optimally minimize a local linear model of the function.

2.3.4 Bridging the Gap: From 1D to \(p\)-D One Dimension at a Time

We have mastered the concept of a derivative for a single-variable function, \(f(x)\). It tells us the slope and guides our descent. But how do we apply this knowledge to a multivariate function, \(f(\mathbf{x}) = f(x_1, x_2, \dots, x_p)\)? The landscape is now a high-dimensional surface, and we can move in infinitely many directions.

A natural first thought is to simplify the problem: what if we restrict our movement to be only along the coordinate axes? Imagine you are at a point \(\mathbf{x}_t = (x_{1,t}, x_{2,t}, \dots, x_{p,t})\). Instead of trying to find the best direction in all \(p\) dimensions simultaneously, we could try to improve our position one coordinate at a time.

  1. Optimize for \(x_1\): Freeze all other coordinates (\(x_2, \dots, x_p\)) at their current values. The function now becomes a univariate function of just \(x_1\): \[ g(x_1) = f(x_1, x_{2,t}, x_{3,t}, \dots, x_{p,t}). \]

    We know how to find a good step for this! The best direction is given by \(-g'(x_1)\). This derivative is precisely the partial derivative of \(f\) with respect to \(x_1\).

  2. Optimize for \(x_2\): After updating \(x_1\), we can freeze the new \(x_1\) and all other coordinates, and optimize the resulting univariate function of \(x_2\).
  3. Repeat: We can cycle through all coordinates, performing a one-dimensional optimization at each step. This method is known as coordinate descent, but let’s skip this discussion for now.

Example 2.8 (Coordinate-wise Optimization). Consider the function \(f(x_1, x_2) = x_1^2 + 2x_1x_2 + 3x_2^2 - 4x_1\). Let’s start at the origin, \(\mathbf{x}_0 = \begin{bmatrix} 0 \\ 0 \end{bmatrix}\).

Step 1: Optimize along \(x_1\). We fix \(x_2=0\). The function becomes a univariate function of \(x_1\):

\[ g(x_1) = f(x_1, 0) = x_1^2 - 4x_1. \]

The derivative (which is the partial derivative of \(f\) with respect to \(x_1\)) is \(g'(x_1) = \frac{\partial f}{\partial x_1} = 2x_1 - 4\). Setting this to zero gives the minimum of this slice: \(2x_1 - 4 = 0 \implies x_1 = 2\). Our new point is \(\begin{bmatrix} 2 \\ 0 \end{bmatrix}\).

Step 2: Optimize along \(x_2\). Now we fix \(x_1=2\). The function becomes a univariate function of \(x_2\):

\[ \begin{aligned} h(x_2) &= f(2, x_2) = (2)^2 + 2(2)x_2 + 3x_2^2 - 4(2) \\ &= 4 + 4x_2 + 3x_2^2 - 8 \\ &= 3x_2^2 + 4x_2 - 4. \end{aligned} \]

The derivative (the partial derivative of \(f\) w.r.t \(x_2\)) is \(h'(x_2) = \frac{\partial f}{\partial x_2} = 6x_2 + 4\). Setting this to zero gives the minimum of this slice: \(6x_2+4=0 \implies x_2 = -2/3\). Our new point is \(\begin{bmatrix} 2 \\ -2/3 \end{bmatrix}\).

After just one cycle, we have moved from \((0,0)\) to \((2, -2/3)\), significantly decreasing the function value. Repeating this process would cause us to zig-zag towards the function’s true minimum.

This coordinate-wise approach is intuitive and sometimes practical, but it has a key limitation: it can be slow if the optimal path is diagonal to the axes. This begs the question: Can we do better? Instead of calculating the slope in each dimension separately and taking sequential steps, can we combine all this directional information into a single vector that points in the overall best direction of steepest descent?

The answer is yes. This single vector, which packages all the partial derivatives together, is precisely the gradient. It gives us the direction to take one optimal, multi-dimensional step instead of many suboptimal, axis-aligned ones.

2.3.5 The Gradient for Multivariate Functions

For a multivariate function \(f(\mathbf{x}): \mathbb{R}^p \to \mathbb{R}\), we have a partial derivative for each dimension, which measures how the function changes if we move only along that one dimension, keeping all others fixed. The gradient is simply the vector that collects all these partial derivatives:

\[ \nabla f(\mathbf{x}) = \begin{bmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_p} \end{bmatrix}. \]

The gradient vector \(\nabla f(\mathbf{x})\) points in the direction of the steepest ascent of the function at point \(\mathbf{x}\). Consequently, the vector \(-\nabla f(\mathbf{x})\) points in the direction of steepest descent.

2.3.6 Computing Gradients via Partial Derivatives

The process of finding a gradient vector boils down to repeatedly applying the rules of single-variable calculus for each component of the input vector.

Example 2.9 (Easy: A Multivariate Polynomial). Find the gradient of \(f(x_1, x_2) = 2x_1^3 + 4x_1x_2^2 - 5x_2\).

  • Partial derivative with respect to \(x_1\): Treat \(x_2\) as a constant. \[ \frac{\partial f}{\partial x_1} = \frac{\partial}{\partial x_1}(2x_1^3) + \frac{\partial}{\partial x_1}(4x_1x_2^2) - \frac{\partial}{\partial x_1}(5x_2) = 6x_1^2 + 4x_2^2 - 0. \]
  • Partial derivative with respect to \(x_2\): Treat \(x_1\) as a constant. \[ \begin{aligned} \frac{\partial f}{\partial x_2} &= \frac{\partial}{\partial x_2}(2x_1^3) + \frac{\partial}{\partial x_2}(4x_1x_2^2) - \frac{\partial}{\partial x_2}(5x_2) \\ &= 0 + 4x_1(2x_2) - 5 = 8x_1x_2 - 5. \end{aligned} \]

Assembling these components into a vector gives the gradient:

\[ \nabla f(\mathbf{x}) = \begin{bmatrix} 6x_1^2 + 4x_2^2 \\ 8x_1x_2 - 5 \end{bmatrix}. \]

Example 2.10 (Medium: A Function with an Exponential). Find the gradient of \(f(\mathbf{x}) = e^{\mathbf{a}^\top\mathbf{x}}\) for a constant vector \(\mathbf{a} \in \mathbb{R}^p\). First, let’s write out the function explicitly: \(f(\mathbf{x}) = \exp\left(\sum_{k=1}^p a_k x_k\right)\). To find the gradient, we compute the partial derivative with respect to an arbitrary component, say \(x_j\). We use the chain rule:

  • The “outside” function is \(e^u\), whose derivative is \(e^u\).
  • The “inside” function is \(u(\mathbf{x}) = \sum_{k=1}^p a_k x_k\).

The partial derivative of the inside function with respect to \(x_j\) is:

\[ \frac{\partial u}{\partial x_j} = \frac{\partial}{\partial x_j} (a_1x_1 + \dots + a_jx_j + \dots + a_px_p) = a_j. \]

Applying the chain rule, the \(j\)-th component of the gradient is:

\[ \frac{\partial f}{\partial x_j} = \exp\left(\sum_{k=1}^p a_k x_k\right) \cdot a_j = a_j e^{\mathbf{a}^\top\mathbf{x}}. \]

Since this holds for every component \(j=1, \dots, p\), we can assemble the full gradient vector:

\[ \nabla f(\mathbf{x}) = \begin{bmatrix} a_1 e^{\mathbf{a}^\top\mathbf{x}} \\ a_2 e^{\mathbf{a}^\top\mathbf{x}} \\ \vdots \\ a_p e^{\mathbf{a}^\top\mathbf{x}} \end{bmatrix} = e^{\mathbf{a}^\top\mathbf{x}} \begin{bmatrix} a_1 \\ a_2 \\ \vdots \\ a_p \end{bmatrix} = e^{\mathbf{a}^\top\mathbf{x}} \mathbf{a}. \]

Example 2.11 (Hard: The Euclidean Norm). Find the gradient of \(f(\mathbf{x}) = \|\mathbf{x}\|_2 = \sqrt{\sum_{k=1}^p x_k^2}\). This is well-defined for all \(\mathbf{x} \neq \mathbf{0}\). Let’s write this as \(f(\mathbf{x}) = (\sum_{k=1}^p x_k^2)^{1/2}\). We find the partial derivative with respect to an arbitrary component \(x_j\) using the chain rule.

  • The “outside” function is \(u^{1/2}\), whose derivative is \(\frac{1}{2}u^{-1/2}\).
  • The “inside” function is \(u(\mathbf{x}) = \sum_{k=1}^p x_k^2\).

The partial derivative of the inside function with respect to \(x_j\) is:

\[ \frac{\partial u}{\partial x_j} = \frac{\partial}{\partial x_j} (x_1^2 + \dots + x_j^2 + \dots + x_p^2) = 2x_j. \]

Applying the chain rule gives the \(j\)-th component of the gradient:

\[ \frac{\partial f}{\partial x_j} = \frac{1}{2}\left(\sum_{k=1}^p x_k^2\right)^{-1/2} \cdot (2x_j) = \frac{x_j}{\sqrt{\sum_{k=1}^p x_k^2}} = \frac{x_j}{\|\mathbf{x}\|_2}. \]

This holds for every component \(j\). Assembling the gradient vector, we get:

\[ \nabla f(\mathbf{x}) = \begin{bmatrix} x_1/\|\mathbf{x}\|_2 \\ x_2/\|\mathbf{x}\|_2 \\ \vdots \\ x_p/\|\mathbf{x}\|_2 \end{bmatrix} = \frac{1}{\|\mathbf{x}\|_2} \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_p \end{bmatrix} = \frac{\mathbf{x}}{\|\mathbf{x}\|_2}. \]

This is a beautiful result: the gradient of the Euclidean norm is the unit vector pointing in the same direction as the input vector.

2.3.7 Gradients of Our Motivating Examples

Now we apply this component-wise technique to derive the gradients for the problems we formulated at the start of the chapter.

Gradient for Least-Squares. The objective is \(f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top \mathbf{w})^2\). To find the gradient \(\nabla f(\mathbf{w})\), we compute its \(j\)-th component, \(\frac{\partial f}{\partial w_j}\). The derivative of a sum is the sum of derivatives, so:

\[ \frac{\partial f}{\partial w_j} = \frac{1}{n} \sum_{i=1}^n \frac{\partial}{\partial w_j} (y_i - \mathbf{a}_i^\top \mathbf{w})^2. \]

We focus on the derivative of a single term inside the sum. Let’s write out the inner product: \(\mathbf{a}_i^\top \mathbf{w} = \sum_{k=1}^p a_{ik}w_k\).

\[ \frac{\partial}{\partial w_j} (y_i - \sum_{k=1}^p a_{ik}w_k)^2. \]

Using the chain rule, this is:

\[ 2(y_i - \sum_{k=1}^p a_{ik}w_k) \cdot \frac{\partial}{\partial w_j}(y_i - \sum_{k=1}^p a_{ik}w_k) = 2(y_i - \mathbf{a}_i^\top\mathbf{w}) \cdot (-a_{ij}). \]

Plugging this back into the sum, the \(j\)-th component of the gradient is:

\[ \frac{\partial f}{\partial w_j} = \frac{1}{n} \sum_{i=1}^n -2(y_i - \mathbf{a}_i^\top\mathbf{w})a_{ij}. \]

To form the full gradient vector, we recognize that this expression is the \(j\)-th component of the vector sum \(\frac{-2}{n}\sum_{i=1}^n (y_i - \mathbf{a}_i^\top\mathbf{w})\mathbf{a}_i\). Therefore:

\[ \nabla f(\mathbf{w}) = \frac{-2}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top\mathbf{w})\mathbf{a}_i. \]

Gradient for Finding the Data Centroid. The objective is \(f(\mathbf{c}) = \sum_{i=1}^n \|\mathbf{a}_i - \mathbf{c}\|_2^2\). Let’s expand the norm into its components:

\[ f(\mathbf{c}) = \sum_{i=1}^n \sum_{k=1}^p (a_{ik} - c_k)^2. \]

To find the gradient \(\nabla f(\mathbf{c})\), we compute its \(j\)-th component, \(\frac{\partial f}{\partial c_j}\). We can swap the summations:

\[ \frac{\partial f}{\partial c_j} = \frac{\partial}{\partial c_j} \sum_{k=1}^p \sum_{i=1}^n (a_{ik} - c_k)^2. \]

When taking the partial derivative with respect to \(c_j\), all terms in the outer sum where \(k \neq j\) are constant and their derivative is zero. We only need to consider the case where \(k=j\):

\[ \frac{\partial f}{\partial c_j} = \frac{\partial}{\partial c_j} \sum_{i=1}^n (a_{ij} - c_j)^2 = \sum_{i=1}^n \frac{\partial}{\partial c_j} (a_{ij} - c_j)^2. \]

Using the chain rule on the term inside the sum gives \(2(a_{ij} - c_j) \cdot (-1)\). So:

\[ \frac{\partial f}{\partial c_j} = \sum_{i=1}^n -2(a_{ij} - c_j). \]

This is the \(j\)-th component of the gradient. Assembling all components from \(j=1\) to \(p\) gives the final gradient vector:

\[ \nabla f(\mathbf{c}) = \sum_{i=1}^n -2(\mathbf{a}_i - \mathbf{c}). \]

Gradient for Classification with Hinge Loss. The objective is \(f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n \max(0, 1 - y_i \langle \mathbf{a}_i, \mathbf{w} \rangle)\). This function is not differentiable everywhere (specifically, when \(1 - y_i \mathbf{a}_i^\top \mathbf{w} = 0\)). However, we can compute its gradient where it exists. We find the partial derivative \(\frac{\partial f}{\partial w_j}\) by considering a single term \(L_i(\mathbf{w})\) in the sum. We have two cases:

  1. If \(1 - y_i \mathbf{a}_i^\top \mathbf{w} < 0\): Then \(L_i(\mathbf{w}) = 0\). The derivative is \(\frac{\partial L_i}{\partial w_j} = 0\).
  2. If \(1 - y_i \mathbf{a}_i^\top \mathbf{w} > 0\): Then \(L_i(\mathbf{w}) = 1 - y_i \mathbf{a}_i^\top \mathbf{w} = 1 - y_i\sum_{k=1}^p a_{ik}w_k\). The derivative is: \[ \frac{\partial L_i}{\partial w_j} = \frac{\partial}{\partial w_j} (1 - y_i\sum_{k=1}^p a_{ik}w_k) = -y_i a_{ij}. \]

We can express this using an indicator function \(\mathbb{I}(\cdot)\) which is 1 if its argument is true and 0 otherwise. The partial derivative for a single sample is:

\[ \frac{\partial L_i}{\partial w_j} = -y_i a_{ij} \cdot \mathbb{I}(1 - y_i \mathbf{a}_i^\top \mathbf{w} > 0). \]

Averaging over all samples, the \(j\)-th component of the gradient is:

\[ \frac{\partial f}{\partial w_j} = \frac{1}{n}\sum_{i=1}^n -y_i a_{ij} \cdot \mathbb{I}(1 - y_i \mathbf{a}_i^\top \mathbf{w} > 0). \]

Assembling these components gives the full gradient vector (more accurately, a subgradient):

\[ \nabla f(\mathbf{w}) = \frac{1}{n}\sum_{i=1}^n \left( -y_i \mathbf{a}_i \cdot \mathbb{I}(1 - y_i \mathbf{a}_i^\top \mathbf{w} > 0) \right). \]

This shows that the gradient averages the feature vectors of the samples that violate the margin (\(y_i \mathbf{a}_i^\top \mathbf{w} < 1\): the misclassified samples and the correctly classified ones too close to the boundary), weighted by \(-y_i\).

2.3.8 Rules for Gradient Calculation

Computing gradients is a fundamental skill. Most gradients can be derived using a few key rules, many of which follow from their single-variable counterparts. Let \(\mathbf{x} \in \mathbb{R}^p\), \(\mathbf{a} \in \mathbb{R}^p\) be a constant vector.

  • Linear Function: For \(f(\mathbf{x}) = \mathbf{a}^\top\mathbf{x}\), the gradient is \(\nabla f(\mathbf{x}) = \mathbf{a}\).
  • Quadratic Form (Squared Norm): For \(f(\mathbf{x}) = \|\mathbf{x}\|_2^2 = \mathbf{x}^\top\mathbf{x}\), the gradient is \(\nabla f(\mathbf{x}) = 2\mathbf{x}\).
  • Sum Rule: For \(f(\mathbf{x}) = g(\mathbf{x}) + h(\mathbf{x})\), the gradient is \(\nabla f(\mathbf{x}) = \nabla g(\mathbf{x}) + \nabla h(\mathbf{x})\).
  • Chain Rule (Simple Case): For \(f(\mathbf{x}) = g(\mathbf{a}^\top\mathbf{x})\), where \(g: \mathbb{R} \to \mathbb{R}\), the gradient is \(\nabla f(\mathbf{x}) = g'(\mathbf{a}^\top\mathbf{x}) \cdot \mathbf{a}\).

2.3.9 A Cookbook of Gradient Formulas

While computing gradients from first principles using partial derivatives is a fundamental skill, for many common functions this process is repetitive. In practice, we rely on a set of pre-derived formulas for basic vector operations, much like we use a multiplication table instead of re-deriving it each time. These rules, derived from the principles of partial differentiation and the chain rule, allow us to quickly assemble the gradients of complex functions.

Table 2.1 lists common functions of a vector \(\mathbf{x} \in \mathbb{R}^p\) and their corresponding gradients. In this table, \(\mathbf{a}\) and \(\mathbf{a}_i\) are constant vectors in \(\mathbb{R}^p\), \(c\) and \(b_i\) are constant scalars, and \(g: \mathbb{R} \to \mathbb{R}\) is a differentiable scalar function.

2.3.10 Using the Rules: Composing Gradients

The true power of these rules is realized when we combine them to find gradients of more sophisticated functions without resorting to partial derivatives every time.

Example 2.12 (Easy: Ridge Regression Penalty). Consider the function:

\[ f(\mathbf{w}) = \frac{\lambda}{2} \|\mathbf{w}\|_2^2, \quad \text{for some constant } \lambda > 0. \]

This is a direct application of two rules from our table. It is a scalar multiple (\(\lambda/2\)) of the squared \(\ell_2\)-norm.

  • From the table, the gradient of \(\|\mathbf{w}\|_2^2\) is \(2\mathbf{w}\).
  • Using the scalar multiplication rule, we multiply this gradient by the constant \(\lambda/2\).
\[ \nabla f(\mathbf{w}) = \frac{\lambda}{2} \cdot (2\mathbf{w}) = \lambda\mathbf{w}. \]

Example 2.13 (Medium: Logistic Loss Function). In classification, a standard loss function is the logistic loss. For a single data point \((\mathbf{a}, y)\) where \(y \in \{-1, +1\}\), the loss is:

\[ f(\mathbf{w}) = \log(1 + e^{-y(\mathbf{a}^\top\mathbf{w})}). \]

This perfectly fits the “Scalar Composition” pattern, \(g(\mathbf{c}^\top\mathbf{w})\), if we set:

  • The constant vector \(\mathbf{c} = -y\mathbf{a}\).
  • The scalar function \(g(u) = \log(1+e^u)\). Its derivative is \(g'(u) = \frac{e^u}{1+e^u} = \frac{1}{1+e^{-u}}\), which is the sigmoid function, \(\sigma(u)\).

Using the rule \(\nabla f(\mathbf{w}) = g'(\mathbf{c}^\top\mathbf{w}) \cdot \mathbf{c}\), we substitute our parts back in:

\[ \nabla f(\mathbf{w}) = \sigma(-y(\mathbf{a}^\top\mathbf{w})) \cdot (-y\mathbf{a}). \]

This result is central to training logistic regression models.

Example 2.14 (Hard: Least-Squares Revisited). Let’s re-derive the gradient for our full least-squares objective using these rules, confirming the result we found earlier with partial derivatives.

\[ f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top \mathbf{w})^2. \]
  1. Apply the Sum Rule: The gradient of the sum is the sum of the gradients. We can also pull out the constant factor \(\frac{1}{n}\). \[ \nabla f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n \nabla \left( (y_i - \mathbf{a}_i^\top \mathbf{w})^2 \right). \]
  2. Focus on a Single Term: Let’s analyze the gradient of one term inside the summation, \(L_i(\mathbf{w}) = (y_i - \mathbf{a}_i^\top \mathbf{w})^2\). This is a composition of functions.
    • The “outside” function is \(g(u) = u^2\), whose derivative is \(g'(u) = 2u\).
    • The “inside” function is \(u(\mathbf{w}) = y_i - \mathbf{a}_i^\top \mathbf{w}\).
  3. Apply the Chain Rule: The general chain rule states that \(\nabla(g(u(\mathbf{w}))) = g'(u(\mathbf{w})) \cdot \nabla u(\mathbf{w})\).
    • The gradient of the inside function, \(\nabla u(\mathbf{w}) = \nabla(y_i - \mathbf{a}_i^\top\mathbf{w})\), is simply \(-\mathbf{a}_i\) (using the sum rule and the linear function rule).
    • Now, we assemble the pieces: \[ \nabla L_i(\mathbf{w}) = \underbrace{2(y_i - \mathbf{a}_i^\top\mathbf{w})}_{g'(u(\mathbf{w}))} \cdot \underbrace{(-\mathbf{a}_i)}_{\nabla u(\mathbf{w})} = -2(y_i - \mathbf{a}_i^\top\mathbf{w})\mathbf{a}_i. \]
  4. Substitute Back into the Sum: Finally, we place this result back into our sum from step 1. \[ \nabla f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n -2(y_i - \mathbf{a}_i^\top\mathbf{w})\mathbf{a}_i. \]

This confirms our previous result, but this time we arrived at the answer by systematically applying a sequence of known rules, demonstrating the power of the cookbook approach.

Table 2.1: A Cookbook of Common Gradient Formulas for Vector Functions.
Function NameFunction \(f(\mathbf{x})\)Gradient \(\nabla f(\mathbf{x})\)
Constant\(c\)\(\mathbf{0}\)
Linear (’Inner Product’)\(\mathbf{a}^\top \mathbf{x}\)\(\mathbf{a}\)
Squared \(\ell_2\)-Norm\(\|\mathbf{x}\|_2^2 = \mathbf{x}^\top\mathbf{x}\)\(2\mathbf{x}\)
\(\ell_2\)-Norm\(\|\mathbf{x}\|_2\)\(\frac{\mathbf{x}}{\|\mathbf{x}\|_2}\)   (for \(\mathbf{x} \neq \mathbf{0}\))
Scalar Composition\(g(\mathbf{a}^\top\mathbf{x})\)\(g'(\mathbf{a}^\top\mathbf{x}) \cdot \mathbf{a}\)
Exponential\(e^{\mathbf{a}^\top \mathbf{x}}\)\(e^{\mathbf{a}^\top \mathbf{x}} \mathbf{a}\)
Logistic / Softplus\(\log(1 + e^{\mathbf{a}^\top\mathbf{x}})\)\(\frac{1}{1+e^{-\mathbf{a}^\top\mathbf{x}}} \mathbf{a}\)   (or \(\sigma(\mathbf{a}^\top\mathbf{x})\mathbf{a}\))
Log-Sum-Exp\(\log \left(\sum_{i=1}^m e^{\mathbf{a}_i^\top \mathbf{x} + b_i}\right)\)\(\sum_{i=1}^m p_i \mathbf{a}_i\), where \(p_i = \frac{e^{\mathbf{a}_i^\top \mathbf{x} + b_i}}{\sum_{j=1}^m e^{\mathbf{a}_j^\top \mathbf{x} + b_j}}\)
General Rules: \(\nabla(g(\mathbf{x})+h(\mathbf{x})) = \nabla g(\mathbf{x}) + \nabla h(\mathbf{x})\) (Sum Rule)
\(\nabla(c \cdot g(\mathbf{x})) = c \cdot \nabla g(\mathbf{x})\) (Scalar Multiplication Rule)

2.3.11 The Taylor Approximation for Multivariate Functions

Just as we used the derivative to build a linear approximation for a single-variable function, we can use the gradient to build a linear approximation for a multivariate function. This is achieved through the multivariate Taylor series, which is a direct generalization of the univariate case.

Representing a multivariate function as an infinite polynomial series is more complex, as it involves higher-order derivatives in the form of tensors (multi-dimensional arrays of numbers; see Chapter 3, § Beyond Matrices: A Glimpse at Tensors). The first few terms, however, have a clean and intuitive structure built from the gradient and the Hessian matrix (the matrix of second partial derivatives; to be defined in future chapters of this class).

Definition 2.2 (Multivariate Taylor Series). If a function \(f(\mathbf{x}): \mathbb{R}^p \to \mathbb{R}\) is infinitely differentiable at a point \(\mathbf{x}_0\), its Taylor series centered at \(\mathbf{x}_0\) can be written as:

\[ \begin{aligned} f(\mathbf{x}) = f(\mathbf{x}_0) &+ \langle \nabla f(\mathbf{x}_0), \mathbf{x}-\mathbf{x}_0 \rangle \\ &+ \frac{1}{2!}(\mathbf{x}-\mathbf{x}_0)^\top \nabla^2 f(\mathbf{x}_0) (\mathbf{x}-\mathbf{x}_0) + \dots \end{aligned} \]

where \(\nabla f(\mathbf{x}_0) \in \mathbb{R}^p\) is the gradient at \(\mathbf{x}_0\), and \(\nabla^2 f(\mathbf{x}_0) \in \mathbb{R}^{p \times p}\) is the Hessian matrix evaluated at \(\mathbf{x}_0\). The "\(\dots\)" represents higher-order terms involving third and higher derivatives, which are more complex to write.

As in the univariate case, we can truncate this series to create powerful polynomial approximations of the function \(f(\mathbf{x})\) for vectors \(\mathbf{x}\) near the center point \(\mathbf{x}_0\).

2.3.12 The First-Order Multivariate Taylor Approximation

By truncating the series after the gradient term, we obtain the multivariate first-order Taylor approximation. This is the cornerstone of all first-order optimization methods.

\[ f(\mathbf{x}) \approx f(\mathbf{x}_0) + \langle \nabla f(\mathbf{x}_0), \mathbf{x}-\mathbf{x}_0 \rangle. \]

This approximation represents the tangent hyperplane to the surface of the function at the point \(\mathbf{x}_0\). It provides a local linear model of our function. The expression is an affine function of \(\mathbf{x}\) because, for a fixed point \(\mathbf{x}_0\), the terms \(f(\mathbf{x}_0) \in \mathbb{R}\) and the gradient vector \(\nabla f(\mathbf{x}_0) \in \mathbb{R}^p\) are constants. If we let \(\mathbf{a} = \nabla f(\mathbf{x}_0)\) and \(b = f(\mathbf{x}_0) - \langle \nabla f(\mathbf{x}_0), \mathbf{x}_0 \rangle \in \mathbb{R}\), the approximation takes the form \(f(\mathbf{x}) \approx \langle \mathbf{a}, \mathbf{x} \rangle + b\), which defines a hyperplane.

This geometric relationship is the multi-dimensional analogue of the tangent line. While in 2D we have a line touching a curve, in 3D we have a plane touching a surface at a single point, sharing the same “tilt” in all directions at that point.

Figure 2.3: A multivariate function f(x) depicted as a surface (in blue).
Figure 2.3: A multivariate function \(f(\mathbf{x})\) depicted as a surface (in blue). At the point \(\mathbf{x}_0\), the first-order Taylor approximation forms a tangent hyperplane (in teal) that touches the surface at a single point and shares its local slope in all directions.

2.3.13 Examples of First-Order Taylor Approximations

Example 2.15 (Easy: An Affine Function). Find the first-order Taylor approximation for \(f(\mathbf{x}) = \mathbf{a}^\top\mathbf{x} + b\) centered at an arbitrary point \(\mathbf{x}_0\).

  • Function Value: \(f(\mathbf{x}_0) = \mathbf{a}^\top\mathbf{x}_0 + b\).
  • Gradient: We know that \(\nabla f(\mathbf{x}) = \mathbf{a}\) for all \(\mathbf{x}\). So, \(\nabla f(\mathbf{x}_0) = \mathbf{a}\).
  • Approximation: \[ f(\mathbf{x}) \approx f(\mathbf{x}_0) + \langle \nabla f(\mathbf{x}_0), \mathbf{x}-\mathbf{x}_0 \rangle = (\mathbf{a}^\top\mathbf{x}_0 + b) + \langle \mathbf{a}, \mathbf{x}-\mathbf{x}_0 \rangle. \]

    Distributing the inner product gives:

    \[ f(\mathbf{x}) \approx \mathbf{a}^\top\mathbf{x}_0 + b + \mathbf{a}^\top\mathbf{x} - \mathbf{a}^\top\mathbf{x}_0 = \mathbf{a}^\top\mathbf{x} + b. \]

    As expected, the first-order approximation of an affine function is the function itself, so the approximation is exact.

Example 2.16 (Easy: A Simple Quadratic). Find the first-order Taylor approximation for \(f(\mathbf{x}) = \|\mathbf{x}\|_2^2\) centered at \(\mathbf{x}_0 = \begin{bmatrix} 1 \\ 2 \end{bmatrix}\).

  • Function Value: First, we evaluate the function at the center point \(\mathbf{x}_0\). \[ f(\mathbf{x}_0) = f(1, 2) = 1^2 + 2^2 = 5. \]
  • Gradient via Partial Derivatives: Next, we compute the gradient by finding each partial derivative individually (of course we could use the rules before, but we do that again to practice). The function in component form is \(f(x_1, x_2) = x_1^2 + x_2^2\).
    • To find the partial derivative with respect to \(x_1\), we treat \(x_2\) as a constant: \[ \frac{\partial f}{\partial x_1} = \frac{\partial}{\partial x_1}(x_1^2 + x_2^2) = 2x_1 + 0 = 2x_1. \]
    • To find the partial derivative with respect to \(x_2\), we treat \(x_1\) as a constant: \[ \frac{\partial f}{\partial x_2} = \frac{\partial}{\partial x_2}(x_1^2 + x_2^2) = 0 + 2x_2 = 2x_2. \]

    The gradient vector is therefore \(\nabla f(\mathbf{x}) = \begin{bmatrix} 2x_1 \\ 2x_2 \end{bmatrix} = 2\mathbf{x}\). Evaluating this at our specific point \(\mathbf{x}_0\):

    \[ \nabla f(\mathbf{x}_0) = \nabla f(1, 2) = \begin{bmatrix} 2(1) \\ 2(2) \end{bmatrix} = \begin{bmatrix} 2 \\ 4 \end{bmatrix}. \]
  • Approximation: We now plug these values into the first-order Taylor approximation formula: \[ f(\mathbf{x}) \approx f(\mathbf{x}_0) + \langle \nabla f(\mathbf{x}_0), \mathbf{x}-\mathbf{x}_0 \rangle = 5 + \left\langle \begin{bmatrix} 2 \\ 4 \end{bmatrix}, \begin{bmatrix} x_1-1 \\ x_2-2 \end{bmatrix} \right\rangle. \]

    Expanding this gives the equation of the tangent plane at the point \((1, 2)\):

    \[ \begin{aligned} f(\mathbf{x}) &\approx 5 + 2(x_1-1) + 4(x_2-2) \\ &= 5 + 2x_1 - 2 + 4x_2 - 8 = 2x_1 + 4x_2 - 5. \end{aligned} \]

The figure visualizes the function \(f(\mathbf{x}) = x_1^2 + x_2^2\) (a paraboloid) and its linear approximation, which is the plane tangent to the surface at the point where \(\mathbf{x}_0 = (1,2)\) and \(f(\mathbf{x}_0)=5\).

Figure 2.4: The function f(x) = ‖x‖₂² (blue paraboloid) and its first-order Taylor approximation (teal plane) at the point x₀=(1,2).
Figure 2.4: The function \(f(\mathbf{x}) = \|\mathbf{x}\|_2^2\) (blue paraboloid) and its first-order Taylor approximation (teal plane) at the point \(\mathbf{x}_0=(1,2)\). The plane is tangent to the surface at the point \((1,2,5)\).

Example 2.17 (Medium: A Non-linear Function). Find the first-order Taylor approximation for \(f(x_1, x_2) = x_1 e^{x_2}\) centered at \(\mathbf{x}_0 = \begin{bmatrix} 2 \\ 0 \end{bmatrix}\).

  • Function Value: \(f(\mathbf{x}_0) = 2 \cdot e^0 = 2\).
  • Gradient: We compute the partial derivatives.
    • \(\frac{\partial f}{\partial x_1} = e^{x_2}\). At \(\mathbf{x}_0\), this is \(e^0 = 1\).
    • \(\frac{\partial f}{\partial x_2} = x_1 e^{x_2}\). At \(\mathbf{x}_0\), this is \(2e^0 = 2\).

    So, \(\nabla f(\mathbf{x}_0) = \begin{bmatrix} 1 \\ 2 \end{bmatrix}\).

  • Approximation: \[ f(\mathbf{x}) \approx f(\mathbf{x}_0) + \langle \nabla f(\mathbf{x}_0), \mathbf{x}-\mathbf{x}_0 \rangle = 2 + \left\langle \begin{bmatrix} 1 \\ 2 \end{bmatrix}, \begin{bmatrix} x_1-2 \\ x_2-0 \end{bmatrix} \right\rangle. \]

    Expanding gives the tangent plane:

    \[ f(\mathbf{x}) \approx 2 + 1(x_1-2) + 2(x_2) = x_1 + 2x_2. \]

2.3.14 From Local Approximation to an Algorithm

The first-order Taylor approximation is the foundation for our primary optimization algorithm. If we are at a point \(\mathbf{x}_t\) and want to find a better point \(\mathbf{x}_{t+1}\), we can model the function locally and find the best direction to step.

Let our step be a vector \(\boldsymbol{\delta}\). The new point is \(\mathbf{x}_{t+1} = \mathbf{x}_t + \boldsymbol{\delta}\). Using the Taylor approximation, the new function value is:

\[ f(\mathbf{x}_t + \boldsymbol{\delta}) \approx f(\mathbf{x}_t) + \langle \nabla f(\mathbf{x}_t), \boldsymbol{\delta} \rangle. \]

Our goal is to choose a step \(\boldsymbol{\delta}\) that makes the function value decrease as much as possible. Since \(f(\mathbf{x}_t)\) is a fixed constant, we need to choose \(\boldsymbol{\delta}\) to make the inner product \(\langle \nabla f(\mathbf{x}_t), \boldsymbol{\delta} \rangle\) as negative as possible.

From the geometric definition of the inner product (Chapter 1), we know:

\[ \langle \nabla f(\mathbf{x}_t), \boldsymbol{\delta} \rangle = \|\nabla f(\mathbf{x}_t)\|_2 \|\boldsymbol{\delta}\|_2 \cos\theta, \]

where \(\theta\) is the angle between the gradient vector and our step vector. To make this inner product most negative, we need to make \(\cos\theta\) as negative as possible. The minimum value of \(\cos\theta\) is \(-1\), which occurs when \(\theta = 180^\circ\). This means the optimal direction for the step vector \(\boldsymbol{\delta}\) is exactly opposite to the direction of the gradient vector \(\nabla f(\mathbf{x}_t)\).

Therefore, the direction of steepest descent is given by the negative gradient:

\[ \text{Optimal Direction} \propto -\nabla f(\mathbf{x}_t). \]

We define our step vector \(\boldsymbol{\delta}\) to be a small step in this direction, scaled by a learning rate \(\eta > 0\):

\[ \boldsymbol{\delta} = -\eta \nabla f(\mathbf{x}_t). \]

This leads directly to the multivariate gradient descent update rule. If our current estimate is \(\mathbf{x}_t\), our next, improved estimate is:

\[ \mathbf{x}_{t+1} = \mathbf{x}_t + \boldsymbol{\delta} = \mathbf{x}_t - \eta \nabla f(\mathbf{x}_t). \]

This is the workhorse algorithm of modern AI. Each step is an attempt to achieve the maximum possible decrease in the objective, based on a local linear approximation of the function’s landscape.

Definition 2.3 (Gradient Descent). Given a differentiable function \(f(\mathbf{x})\) and a starting point \(\mathbf{x}_0\), the gradient descent algorithm generates a sequence of vectors via the update rule:

\[ \mathbf{x}_{t+1} = \mathbf{x}_t - \eta \nabla f(\mathbf{x}_t), \]

for \(t = 0, 1, 2, \dots\). The scalar \(\eta > 0\) is the learning rate.

The algorithm’s behavior is critically dependent on the choice of \(\eta\). If \(\eta\) is too small, the algorithm will be very slow to find a good solution. If \(\eta\) is too large, the updates will be too aggressive, causing the algorithm to “overshoot” the minimum and potentially diverge to random points and directions. A discussion about details on how we choose \(\eta\) will be provided later in the class.

2.4 Solving Our Problems with Gradient Descent

Let’s now apply this algorithm to the problems we formulated at the start of the chapter.

2.4.1 Gradient Descent for Least-Squares

Our objective was \(f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top \mathbf{w})^2\). We need its gradient with respect to \(\mathbf{w}\). This is already calculated in the discussion above, so we will provide directly the answer:

\[ \nabla f(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^n -2(y_i - \mathbf{a}_i^\top \mathbf{w})\mathbf{a}_i. \]

The gradient descent update rule for least-squares is therefore:

\[ \mathbf{w}_{t+1} = \mathbf{w}_t + \frac{2\eta}{n} \sum_{i=1}^n (y_i - \mathbf{a}_i^\top \mathbf{w}_t)\mathbf{a}_i. \]

Complexity Analysis: Each gradient computation requires summing \(n\) vectors of size \(p\), where each term’s scalar multiple costs \(O(p)\). The total complexity of one gradient descent step is \(O(np)\). If we were to run gradient descent for \(T\) iterations, we would have to “pay” \(O(Tnp)\) total complexity.

Code session · Section 2.4.1 Skip to Section 2.4.2

Gradient descent on least squares: three step sizes

The same 40 gradient steps on a small least-squares problem (50 data points, 3 features), with three step sizes.

show setup
import numpy as np
1rng = np.random.default_rng(1)
2A = rng.normal(size=(50, 3))                    # 50 data points, 3 features
3y = A @ np.array([2.0, -1.0, 0.5]) + 0.1 * rng.normal(size=50)
4curves = {}
5for eta in [0.02, 0.3, 1.2]:
6    w = np.zeros(3)
7    curves[eta] = [np.mean((A @ w - y) ** 2)]   # the loss at the start
8    for t in range(40):
9        w = w - eta * (2 / 50) * A.T @ (A @ w - y)   # the gradient step
10        curves[eta].append(np.mean((A @ w - y) ** 2))
11    print(f"eta = {eta:<5} loss after 40 steps = {curves[eta][-1]:.4g}")
Recorded output
eta = 0.02  loss after 40 steps = 0.385
eta = 0.3   loss after 40 steps = 0.009004
eta = 1.2   loss after 40 steps = 2.976e+05
10⁻² 1 10² 10⁴ 10⁶ 0 10 20 30 40 loss (log scale) step t η = 0.02 η = 0.3 η = 1.2

Loss against step, on a log scale. With a step of 0.02 the loss falls slowly, from 3.9 at the start to 0.39 after 40 steps. With 0.3 it reaches the best possible loss for this data, about 0.009, within 40 steps. With 1.2 each step overshoots by more than the last, and the loss explodes to about 300,000. Steps above about 1.1 diverge on this problem; Chapter 6 shows where that limit comes from.

Recorded on an Apple M1 Max laptop, macOS 26.6.2, Python 3.13.7, NumPy 2.4.6, 2026-11-30.

2.4.2 Gradient Descent for Finding the Data Centroid

Our objective was \(f(\mathbf{c}) = \sum_{i=1}^n \|\mathbf{a}_i - \mathbf{c}\|_2^2\). We know the total gradient is the sum:

\[ \nabla f(\mathbf{c}) = \sum_{i=1}^n -2(\mathbf{a}_i - \mathbf{c}). \]

The gradient descent update rule is:

\[ \mathbf{c}_{t+1} = \mathbf{c}_t + 2\eta \sum_{i=1}^n (\mathbf{a}_i - \mathbf{c}_t). \]

As noted before, setting the gradient to zero yields the exact solution \(\mathbf{c}^\star = \frac{1}{n}\sum \mathbf{a}_i\). Gradient descent will iteratively converge to this exact mean.

Example 2.18 (On-Paper Gradient Descent Step). Let’s find the center of three 2D points: \(\mathbf{a}_1=\begin{bmatrix}1 \\ 1\end{bmatrix}, \mathbf{a}_2=\begin{bmatrix}2 \\ 3\end{bmatrix}, \mathbf{a}_3=\begin{bmatrix}3 \\ 2\end{bmatrix}\). By the analysis above, the true center is \(\mathbf{c}^\star = \frac{1}{3}(\mathbf{a}_1+\mathbf{a}_2+\mathbf{a}_3) = \frac{1}{3}\begin{bmatrix}6 \\ 6\end{bmatrix} = \begin{bmatrix}2 \\ 2\end{bmatrix}\).

Let’s perform one step of gradient descent. Start with \(\mathbf{c}_0 = \begin{bmatrix}0 \\ 0\end{bmatrix}\) and let \(\eta = 0.1\).

  1. Calculate the Gradient at \(\mathbf{c}_0\): \[ \begin{aligned} \nabla f(\mathbf{c}_0) &= -2(\mathbf{a}_1 - \mathbf{c}_0) -2(\mathbf{a}_2 - \mathbf{c}_0) -2(\mathbf{a}_3 - \mathbf{c}_0) \\ &= -2\mathbf{a}_1 -2\mathbf{a}_2 -2\mathbf{a}_3 \\ &= -2 \begin{bmatrix}1 \\ 1\end{bmatrix} -2 \begin{bmatrix}2 \\ 3\end{bmatrix} -2 \begin{bmatrix}3 \\ 2\end{bmatrix} \\ &= \begin{bmatrix}-2 \\ -2\end{bmatrix} + \begin{bmatrix}-4 \\ -6\end{bmatrix} + \begin{bmatrix}-6 \\ -4\end{bmatrix} \\ &= \begin{bmatrix}-12 \\ -12\end{bmatrix}. \end{aligned} \]
  2. Perform the Update: \[ \begin{aligned} \mathbf{c}_1 &= \mathbf{c}_0 - \eta \nabla f(\mathbf{c}_0) \\ &= \begin{bmatrix}0 \\ 0\end{bmatrix} - 0.1 \begin{bmatrix}-12 \\ -12\end{bmatrix} = \begin{bmatrix}1.2 \\ 1.2\end{bmatrix}. \end{aligned} \]

After just one step, our estimate has moved from the origin to \((1.2, 1.2)\), which is significantly closer to the true center at \((2, 2)\). Subsequent iterations would continue this process, refining the estimate until it converges.

2.5 The Chain Rule and Automatic Differentiation

Every gradient in this chapter was computed by hand: write the function down, apply the rules of calculus, simplify. That works for a function that fits on a page. A neural network is a function of millions of parameters built from dozens of operations, and nobody differentiates it by hand. A program does, and the program is short: it applies the chain rule to the function one elementary operation at a time. This is called automatic differentiation, or autodiff. It is what runs when you type loss.backward() in PyTorch.

2.5.1 A Function Is a Sequence of Elementary Steps

Take

\[ \begin{aligned} y = (x_1 + x_2) \cdot x_1 \qquad \text{at } (x_1, x_2) = (3, 4). \end{aligned} \]

A computer does not evaluate this in one go. It evaluates it in two steps, each an elementary operation whose derivative we know:

\[ \begin{aligned} v = x_1 + x_2 = 7, \qquad y = v \cdot x_1 = 21. \end{aligned} \]

Figure 2.5 draws these steps as a computation graph. There is one rule for building it, and it is the order of evaluation you would follow on a calculator, innermost operation first.

Definition 2.4 (Computation graph). Evaluate the expression one elementary operation at a time and:

  1. Make one box for every input, and one box for the result of every elementary operation. Write the value in it.
  2. Draw an arrow into that box from each box whose value the operation used. An arrow from \(u\) to \(w\) means one thing only: the value of \(u\) was used to compute \(w\).
  3. Stop when the output has its box.

There is nothing else to decide. A box with several arrows going out is a quantity that is used several times; a box with several arrows coming in is an operation with several inputs. The graph is nothing but the record of the forward pass, and that is how the code builds it: every operation creates a box that remembers which boxes it was computed from. Reading the black entries of Figure 2.5 left to right is the forward pass. The picture already shows the one thing that will matter: \(x_1\) has two arrows going out, because it is used twice, once inside \(v\) and once as the multiplier of \(v\). Every function you can program, however large, is such a graph of additions, multiplications, exponentials and a handful of other elementary operations.

2.5.2 Step 1: A Number on Every Arrow

One fact makes everything that follows mechanical: a box only sees the numbers that arrive at it. The multiplication box computes \(a \cdot b\) from whatever two numbers arrive, here \(a = v = 7\) and \(b = x_1 = 3\). It does not know, and does not need to know, where they came from.

The edge number of an arrow into a box is the derivative of that box’s operation with respect to the number arriving along that arrow, evaluated at the stored values. One calculus rule per arrow, nothing else:

arrowthe box computesderivative with respect to the arriving numberedge number
\(x_1 \to v\)\(v = a + b\), \(a = x_1\), \(b = x_2\)\(\partial(a + b)/\partial a = 1\)\(1\)
\(x_2 \to v\)\(v = a + b\), \(a = x_1\), \(b = x_2\)\(\partial(a + b)/\partial b = 1\)\(1\)
\(v \to y\)\(y = a \cdot b\), \(a = v\), \(b = x_1\)\(\partial(a b)/\partial a = b = x_1\)\(3\)
\(x_1 \to y\)\(y = a \cdot b\), \(a = v\), \(b = x_1\)\(\partial(a b)/\partial b = a = v\)\(7\)
Figure 2.5: The graph of y = (x₁ + x₂)· x₁ at (3, 4) after Step 1.
Figure 2.5: The graph of \(y = (x_1 + x_2)\cdot x_1\) at \((3, 4)\) after Step 1. Black, in the boxes: the values of the forward pass. Blue, on the arrows: the edge numbers of the table above.

The last row deserves a second look. The \(7\) answers a narrow question: if the number arriving along the arrow \(x_1 \to y\) changes by one unit and the other input \(a = v\) stays put, then \(y\) changes by \(7\). That \(x_1\) also changes \(v\) is not this arrow’s business. That effect travels along the other arrow, \(x_1 \to v\), and then along \(v \to y\), and Step 2 adds it in as a second path. Every arrow carries one local fact, and that is exactly how the code works: the multiplication’s backward rule is “send \(b\) to \(a\) and \(a\) to \(b\)”, with no idea what \(a\) and \(b\) are made of.

2.5.3 Step 2: Multiply Along a Path, Add the Paths

The chain rule of § Rules for Gradient Calculation, extended to several paths and read on the graph, says: the derivative of \(y\) with respect to an input is the sum, over all paths from that input to \(y\), of the product of the edge numbers along the path.

  • From \(x_2\) there is one path, \(x_2 \to v \to y\): \[ \begin{aligned} \frac{\partial y}{\partial x_2} = \underbrace{1}_{\text{edge } x_2 \to v} \cdot \underbrace{3}_{\text{edge } v \to y} = 3. \end{aligned} \]
  • From \(x_1\) there are two paths, the direct arrow \(x_1 \to y\) and the detour \(x_1 \to v \to y\), and they add: \[ \begin{aligned} \frac{\partial y}{\partial x_1} = \underbrace{7}_{\text{edge } x_1 \to y} + \underbrace{1}_{\text{edge } x_1 \to v} \cdot \underbrace{3}_{\text{edge } v \to y} = 7 + 3 = 10. \end{aligned} \]

Check by hand: \(y = x_1^2 + x_1 x_2\), so \(\partial y / \partial x_1 = 2x_1 + x_2 = 10\) and \(\partial y / \partial x_2 = x_1 = 3\). Everything here is trivial except one thing: an input with two arrows leaving it gets two contributions, and they add. That addition is the only idea in this section beyond the single-variable chain rule.

2.5.4 Step 3: Send Messages Back Along the Arrows

Adding up paths is fine for a graph with two paths. A deep network has more paths from an input to the output than a program could ever enumerate, so no program adds up paths. Instead, every box gets a box number,

\[ \begin{aligned} \frac{\partial y}{\partial(\text{box})}, \end{aligned} \]

how much \(y\) changes per unit change of that box, with everything downstream adjusting. The box numbers of the input boxes are the partial derivatives we want. They are computed from the output backwards by two rules:

  • Message. Every arrow sends, backwards from its head to its tail, the product (box number at its head) \(\times\) (its edge number).
  • Box. A box’s number is the sum of the messages on the arrows leaving it. The output box starts with the number \(1\).
Figure 2.6: The same graph after Step 3.
Figure 2.6: The same graph after Step 3. Red, below each arrow: its message, the box number at the arrow’s head times the edge number. Red, in each box: the box number, the sum of the messages on the arrows leaving the box. The box \(x_1\) receives two messages, \(7\) and \(3\), and adds them.

Walked through on Figure 2.6:

  1. Box \(y\) gets \(1\).
  2. The two arrows into \(y\) send messages back: \(v \to y\) sends \(1 \times 3 = 3\) to \(v\), and \(x_1 \to y\) sends \(1 \times 7 = 7\) to \(x_1\).
  3. Box \(v\) has one arrow leaving it, so its number is \(3\). Its two incoming arrows now send: \(x_1 \to v\) sends \(3 \times 1 = 3\) to \(x_1\), and \(x_2 \to v\) sends \(3 \times 1 = 3\) to \(x_2\).
  4. Box \(x_2\) receives one message, so its number is \(3\). Box \(x_1\) receives two and adds them: \(7 + 3 = 10\).

The same \(10\) and \(3\) as in Step 2, but each arrow carried exactly one message. The work is the size of the graph, not the number of paths. Written as a formula, the two rules say that if the arrows leaving a box \(v\) go to the boxes \(c_1, \dots, c_k\), then

\[ \begin{aligned} \frac{\partial y}{\partial v} = \sum_{j=1}^{k} \frac{\partial y}{\partial c_j} \cdot \frac{\partial c_j}{\partial v}, \end{aligned} \]

which is the chain rule taken one step at a time.

Example 2.19 (A worked exercise: the diamond). Take \(y = (x_1 x_2 + 1)\cdot(x_1 - x_2)\) at \((x_1, x_2) = (3, 2)\), so that both inputs have two arrows leaving them. Forward pass: \(v_1 = x_1 x_2 = 6\), \(v_3 = x_1 - x_2 = 1\), \(v_2 = v_1 + 1 = 7\), \(y = v_2 v_3 = 7\) (Figure 2.7).

Step 1, edge numbers. The box \(v_1 = a \cdot b\) with \(a = x_1\), \(b = x_2\) gives \(b = 2\) on \(x_1 \to v_1\) and \(a = 3\) on \(x_2 \to v_1\). The box \(v_3 = a - b\) gives \(1\) on \(x_1 \to v_3\) and \(-1\) on \(x_2 \to v_3\). The box \(v_2 = a + 1\) gives \(1\) on \(v_1 \to v_2\). The box \(y = a \cdot b\) with \(a = v_2\), \(b = v_3\) gives \(b = v_3 = 1\) on \(v_2 \to y\) and \(a = v_2 = 7\) on \(v_3 \to y\).

Step 3, messages and box numbers. Box \(y\) gets \(1\). From \(y\): \(v_2 \to y\) sends \(1 \times 1 = 1\), so box \(v_2 = 1\); \(v_3 \to y\) sends \(1 \times 7 = 7\), so box \(v_3 = 7\). From \(v_2\): \(v_1 \to v_2\) sends \(1 \times 1 = 1\), so box \(v_1 = 1\). From \(v_1\): \(x_1 \to v_1\) sends \(1 \times 2 = 2\) and \(x_2 \to v_1\) sends \(1 \times 3 = 3\). From \(v_3\): \(x_1 \to v_3\) sends \(7 \times 1 = 7\) and \(x_2 \to v_3\) sends \(7 \times (-1) = -7\). Each input adds its two messages: box \(x_1 = 2 + 7 = 9\) and box \(x_2 = 3 - 7 = -4\).

Check by hand. \(y = x_1^2 x_2 - x_1 x_2^2 + x_1 - x_2\), so \(\partial y/\partial x_1 = 2 x_1 x_2 - x_2^2 + 1 = 9\) and \(\partial y/\partial x_2 = x_1^2 - 2 x_1 x_2 - 1 = -4\).

Figure 2.7: The diamond y = (x₁ x₂ + 1)(x₁ - x₂) at (3, 2) with all four kinds of numbers: values in black, edge numbers in blue above the arrows, messages in...
Figure 2.7: The diamond \(y = (x_1 x_2 + 1)(x_1 - x_2)\) at \((3, 2)\) with all four kinds of numbers: values in black, edge numbers in blue above the arrows, messages in red below the arrows, box numbers in red in the boxes. Both inputs receive two messages.

Three details turn the two rules into an algorithm.

  1. Order. A box can send its messages only once its own number is complete, that is, once every arrow leaving it has delivered. Visiting the boxes in the reverse of the order in which the forward pass created them guarantees this. Such an order, in which every quantity comes after the quantities it was computed from, is called a topological order.
  2. Storage. Each box keeps its value from the forward pass, because the edge numbers need it, plus its box number, which the code calls grad. Each message is added into the grad of the box it arrives at. Adding, not overwriting, is the branch sum. Overwriting is the most common bug in every implementation of this idea.
  3. Cost. Every arrow carries one message, so the backward pass costs a small constant multiple of one evaluation of \(y\), whatever the number of inputs. A loss over \(10^9\) parameters gets all \(10^9\) partial derivatives from one forward pass and one backward pass. This is the reason training a neural network is computationally possible at all.

The technical name of the procedure is reverse-mode automatic differentiation. Everything in it is the chain rule plus bookkeeping.

2.5.5 Autodiff on Least Squares

Our three problems are built from a few elementary operations, so the engine handles them; it is worth seeing where the branching is. For least squares, one house contributes \(\ell_i = (y_i - \mathbf{a}_i^\top \mathbf{w})^2\), a chain of three steps: inner product, subtraction, square. Nothing branches inside the chain. The branching is across houses: the same \(\mathbf{w}\) feeds all \(n\) chains (Figure 2.8). Sending messages back along one chain from \(f = \frac{1}{n}\sum_i \ell_i\) gives box \(\ell_i = \frac{1}{n}\), then box \(r_i = \frac{2 r_i}{n}\) with \(r_i = y_i - \mathbf{a}_i^\top \mathbf{w}\), then box \(u_i = -\frac{2 r_i}{n}\) for the inner product \(u_i = \mathbf{a}_i^\top \mathbf{w}\). The arrow \(\mathbf{w} \to u_i\) has the vector edge number \(\mathbf{a}_i\), the cookbook entry \(\nabla_{\mathbf{w}} (\mathbf{a}_i^\top \mathbf{w}) = \mathbf{a}_i\), so its message is \(-\frac{2 r_i}{n}\,\mathbf{a}_i\), and since \(n\) arrows leave \(\mathbf{w}\), its box collects \(n\) messages:

\[ \begin{aligned} \nabla f(\mathbf{w}) = \sum_{i=1}^n \frac{\partial f}{\partial u_i}\,\mathbf{a}_i = -\frac{2}{n}\sum_{i=1}^n (y_i - \mathbf{a}_i^\top \mathbf{w})\,\mathbf{a}_i, \end{aligned} \]

the formula of § Gradients of Our Motivating Examples. The \(\sum_i\) we wrote there by hand is the sum of messages at \(\mathbf{w}\). The centroid and the hinge loss are the same story with a different three-step chain; run the engine on the three points of the on-paper gradient descent step in § Gradient Descent for Finding the Data Centroid and it returns \((-12, -12)\), the gradient computed there by hand.

Figure 2.8: Least squares as a graph.
Figure 2.8: Least squares as a graph. Each house has its own three-step chain, and the chains meet only at the two ends: the parameter \(\mathbf{w}\) on the left, which every chain uses, and the average \(f\) on the right. Blue: edge numbers, each a cookbook entry. Red: box numbers, filled in by the backward pass from right to left; the \(n\) arrows out of \(\mathbf{w}\) carry the \(n\) terms of the hand-derived gradient.

2.5.6 Why an Engine and Not Pen and Paper

For the three problems of this chapter, pen and paper was fine. Each objective is a short chain per data point, and § Gradients of Our Motivating Examples derived all three gradients in a page. So a fair question is: who cares? Three answers.

  1. Every change to the objective restarts the derivation on paper, and changes one box on the graph. Add a penalty \(\lambda \|\mathbf{w}\|_2^2\) to least squares: on paper, a new derivation; on the graph, one more arrow leaving \(\mathbf{w}\), carrying the message \(2\lambda\mathbf{w}\), which the engine adds to the rest. Swap the square for the hinge: the same chain with one box replaced, and the engine already knows that box’s rule. The engine knows nothing about least squares or hinge losses. It knows a dozen elementary operations and their backward rules, written once and tested once.
  2. Composition creates branching, and branching is where pen and paper breaks. A model with one hidden layer feeds every input into every hidden unit and every hidden unit into every output. Its graph is a mesh, not a chain, and the number of paths from a parameter to the loss grows exponentially with the depth. The by-hand chain rule is a sum over those paths. The backward pass sends one message per arrow.
  3. The by-hand derivation is where the bugs live. Numerical gradient checkers exist because hand-derived gradients are wrong often enough to need a test. A backward rule written once per elementary operation is checked once and is correct forever, and every gradient the engine produces is exact.

From this point on, deriving a gradient by hand is a check, not a prerequisite. You write the forward pass and ask for the gradient.

2.5.7 Connection to Gradient Descent

Gradient descent, \(\mathbf{x}_{t+1} = \mathbf{x}_t - \eta \nabla f(\mathbf{x}_t)\), needs one gradient per step, and until now we supplied it by hand. With autodiff, any function we can program is differentiable: build the forward pass, run the backward pass, read the box numbers of the inputs. Every optimizer in the rest of this book, gradient descent here, Newton’s method and its adaptive variants in Chapter 6, is a recipe applied on top of the gradient the engine provides. The engine itself is about a hundred lines of Python.

Exercises

Below is a set of exercises related to the content of Chapter 2. The exercises assume knowledge from Chapter 1 (vectors, norms, inner products) and basic Python programming.

EASY EXERCISES

  1. E1.
    Conceptual Understanding. In your own words, define the three core components required to frame a problem as an optimization task, as described in this chapter.
  2. E2.
    Univariate Derivative. Compute the derivative \(f'(x)\) for the function \(f(x) = 4x^5 - \frac{1}{2}x^2 + 10\).
  3. E3.
    Simple Partial Derivatives. For the function \(f(x_1, x_2) = 3x_1^2 + 5x_1x_2 - x_2^4\), compute the partial derivatives \(\frac{\partial f}{\partial x_1}\) and \(\frac{\partial f}{\partial x_2}\).
  4. E4.
    Gradient Descent by Hand. Perform two steps of gradient descent for the function \(f(x) = x^2\) starting at \(x_0=4\) with a learning rate of \(\eta=0.2\).
  5. E5.
    Direction of Descent. If the gradient of a function \(f(\mathbf{x})\) at a point \(\mathbf{x}_t\) is \(\nabla f(\mathbf{x}_t) = \begin{bmatrix} -2 \\ 3 \end{bmatrix}\), what is the vector direction of steepest descent?
  6. E6.
    First-Order Taylor Approximation (1D). Write down the first-order Taylor approximation for the function \(f(x) = \sin(x)\) centered at the point \(x_0 = 0\).
  7. E7.
    Cost Function Vocabulary. In the least-squares objective \(f(\mathbf{w}) = \frac{1}{n}\sum_{i=1}^n (y_i - \mathbf{a}_i^\top\mathbf{w})^2\), what is the mathematical term for the quantity \(r_i = y_i - \mathbf{a}_i^\top\mathbf{w}\)?
  8. E8.
    Gradient of an Affine Function. Using the “Cookbook” rules, what is the gradient of the function \(f(\mathbf{x}) = 5 + \mathbf{c}^\top\mathbf{x}\) for a constant vector \(\mathbf{c}\)?
  9. E9.
    Closed-Form vs. Iterative. Briefly explain the difference between a closed-form solution and an iterative solution to an optimization problem. Give one example of each from the chapter.
  10. E10.
    Python: Single Prediction. Write a Python function predict(a, w) that takes a feature vector a (as a NumPy array) and a weight vector w (as a NumPy array) and computes the linear model prediction \(\hat{y} = \mathbf{a}^\top\mathbf{w}\).

MEDIUM EXERCISES

  1. M1.
    Gradient Calculation. Compute the gradient of the function \(f(x_1, x_2) = \log(x_1^2 + x_2^2 + 1)\) with respect to \(\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \end{bmatrix}\).
  2. M2.
    First-Order Taylor Approximation (2D). Find the first-order Taylor approximation for the function \(f(x_1, x_2) = x_1^2 x_2\) around the point \(\mathbf{x}_0 = \begin{bmatrix} 2 \\ 3 \end{bmatrix}\).
  3. M3.
    Role of the Learning Rate. The update rule for finding the minimum of \(f(x) = 5x^2\) is \(x_{t+1} = x_t - \eta(10x_t) = (1-10\eta)x_t\).
    1. a)
      For what range of \(\eta > 0\) is the algorithm guaranteed to converge to the minimum at \(x=0\)?
    2. b)
      Describe what happens to the sequence \(x_t\) if you choose \(\eta=0.25\).
  4. M4.
    FLOPs Calculation. For the data centroid objective \(f(\mathbf{c}) = \sum_{i=1}^n \|\mathbf{a}_i - \mathbf{c}\|_2^2\), what is the exact number of FLOPs required to compute the gradient, \(\nabla f(\mathbf{c}) = \sum_{i=1}^n -2(\mathbf{a}_i - \mathbf{c})\)? Express your answer in terms of \(n\) and \(p\).
  5. M5.
    Gradient Descent Step for Least-Squares. You have a single data point \((p=2)\) with features \(\mathbf{a}_1 = \begin{bmatrix} 3 \\ 1 \end{bmatrix}\) and true value \(y_1=5\). Your current model weights are \(\mathbf{w}_0 = \begin{bmatrix} 1 \\ 1 \end{bmatrix}\). Using a learning rate \(\eta=0.1\), compute the next weight vector, \(\mathbf{w}_1\), using the gradient descent update for the least-squares objective (with \(n=1\)).
  6. M6.
    Geometric Interpretation of Gradient. Consider the function \(f(x_1, x_2) = x_1^2 + x_2^2\). The level sets of this function are circles centered at the origin. Compute the gradient at the point \(\mathbf{x} = \begin{bmatrix} 1 \\ 1 \end{bmatrix}\). Show that this gradient vector is orthogonal to the tangent line of the level set at that point.
  7. M7.
    Finding Stationary Points. Find all points \((x_1, x_2)\) where the gradient of the function \(f(x_1, x_2) = x_1^2 - 4x_1 + x_2^2 + 2x_2\) is the zero vector.
  8. M8.
    Python: Centroid GD Path. Given the data points \(\mathbf{a}_1=\begin{bmatrix}1 \\ 5\end{bmatrix}, \mathbf{a}_2=\begin{bmatrix}2 \\ 1\end{bmatrix}, \mathbf{a}_3=\begin{bmatrix}6 \\ 3\end{bmatrix}\), write a Python script that:
    1. a)
      Calculates the true centroid \(\mathbf{c}^*\).
    2. b)
      Runs 10 iterations of gradient descent for the centroid problem, starting from \(\mathbf{c}_0=\begin{bmatrix}0\\0\end{bmatrix}\) with \(\eta=0.1\).
    3. c)
      Prints the final estimate \(\mathbf{c}_{10}\) and the true centroid \(\mathbf{c}^*\).
  9. M9.
    Deriving a Gradient from Rules. Using the rules from the “Cookbook” table, derive the gradient of the function \(f(\mathbf{w}) = \frac{1}{2}\|\mathbf{w}\|_2^2 - \mathbf{b}^\top\mathbf{w}\), where \(\mathbf{b}\) is a constant vector.
  10. M10.
    Big-O Complexity. You are running gradient descent for the least-squares problem for \(T=1000\) iterations. You have \(n=5000\) data points and \(p=200\) features. In Big-O notation, what is the overall computational complexity of the entire training process?
  11. M11.
    The Diamond at a New Point. Section 2.5 works the diamond \(y = (x_1 x_2 + 1)\cdot(x_1 - x_2)\) at \((3, 2)\). Redo it at \((x_1, x_2) = (1, 3)\): (a) forward pass and graph; (b) the edge number on every arrow, stating for each the operation and the arriving number it differentiates with respect to; (c) the messages and box numbers, from \(y\) back to \(x_1\) and \(x_2\); (d) check against \(\partial y/\partial x_1 = 2 x_1 x_2 - x_2^2 + 1\) and \(\partial y/\partial x_2 = x_1^2 - 2 x_1 x_2 - 1\).

HARD EXERCISES

  1. H1.
    Gradient of Softmax Loss. In multi-class classification, a common function is the cross-entropy loss with a softmax model. For a single data point \((\mathbf{a}, \mathbf{y})\), where \(\mathbf{y}\) is a one-hot vector (e.g., \(\begin{bmatrix}0 & 1 & 0\end{bmatrix}^\top\)), the model’s prediction is a vector \(\hat{\mathbf{y}}\) where each component is \(\hat{y}_k = \frac{e^{\mathbf{w}_k^\top\mathbf{a}}}{\sum_j e^{\mathbf{w}_j^\top\mathbf{a}}}\). The objective is \(f(\mathbf{W}) = -\sum_k y_k \log(\hat{y}_k)\). Show that the gradient with respect to one of the weight vectors, \(\mathbf{w}_j\), is given by \((\hat{y}_j - y_j)\mathbf{a}\). (This is a challenging chain rule application).
  2. H2.
    Convergence Analysis of GD for Centroid. The update rule for the centroid problem is \(\mathbf{c}_{t+1} = \mathbf{c}_t + 2\eta \sum_{i=1}^n (\mathbf{a}_i - \mathbf{c}_t)\). Let \(\mathbf{c}^* = \frac{1}{n}\sum_i \mathbf{a}_i\) be the true solution. Show that the error vector \(\boldsymbol{\delta}_t = \mathbf{c}_t - \mathbf{c}^*\) follows the recursion \(\boldsymbol{\delta}_{t+1} = (1 - 2\eta n)\boldsymbol{\delta}_t\). For what range of \(\eta\) does this algorithm converge?
  3. H3.
    Python: Full Least-Squares Solver. Write a Python function solve_ls_gd(A, y, eta, num_iterations) that implements gradient descent for the full least-squares problem.
    1. a)
      The inputs are A (a list of NumPy feature vectors), y (a list of outcomes), eta, and num_iterations.
    2. b)
      Initialize the weight vector w to zeros.
    3. c)
      In a loop, compute the full gradient over all data points and update w.
    4. d)
      Return the final weight vector.

    Test your function on a small, randomly generated dataset.

  4. H4.
    Derivation of Optimal Learning Rate. For the quadratic function \(f(x)=ax^2+bx+c\) (with \(a>0\)), the gradient descent update is \(x_{t+1} = x_t - \eta(2ax_t+b)\). By analyzing the error recursion \(x_{t+1}-x^\star = (1-2a\eta)(x_t-x^\star)\), show that the absolute value of the contraction factor \(|1-2a\eta|\) is minimized when \(\eta = 1/(2a)\). What is the significance of this value in relation to the function’s second derivative?
  5. H5.
    Alternative Cost Function. Instead of minimizing the sum of squared distances for the centroid problem, suppose we want to minimize the sum of distances: \(f(\mathbf{c}) = \sum_{i=1}^n \|\mathbf{a}_i - \mathbf{c}\|_2\). This point is called the geometric median.
    1. a)
      Derive the gradient \(\nabla f(\mathbf{c})\). (Hint: Use the chain rule and the gradient of the \(\ell_2\)-norm).
    2. b)
      Set the gradient to zero. Can you find a simple closed-form solution for \(\mathbf{c}^*\) like you could for the squared-distance case? Explain why or why not.