The big theme in our course so far has been the three-step modeling recipe, of choosing a model, choosing a loss function, and then minimizing empirical risk (i.e. average loss) to find optimal model parameters.
In Chapter 1.4, we used calculus to find the slope and intercept that minimized mean squared error,
by computing (the partial derivative with respect to ) , setting both to zero, and solving the resulting system of equations.
Then, in Chapters 2 and 3, we focused on the multiple linear regression model and the squared loss function, which saw us minimize
where is the design matrix, is the observation vector, and is the parameter vector we’re trying to pick. In Chapter 2.10, we minimized by arguing that the optimal had to create an error vector, , that was orthogonal to , which led us to the normal equations.
It turns out that there’s a way to use our calculus-based approach from Chapter 1.4 to minimize the more general version of for any , that doesn’t involve computing partial derivatives. To see how this works, we need to define a new object, the gradient vector, which we’ll do here in Chapter 4.1. After we’re familiar with how the gradient vector works, we’ll use it to build a new approach to function minimization, one that works even when there isn’t a closed-form solution for the optimal parameters: that technique is called gradient descent, which we’ll see in Chapter 4.2.
Domain and Codomain¶
As we saw in Chapter 2.9 when we first introduced the concept of the inverse of a matrix, the notation
means that is a function whose inputs are vectors with components and whose outputs are vectors with components. is the domain of the function, and is the codomain. I’ve used and to match the notation we’ve used for matrices and linear transformations. In general, if is an matrix, then any vector multiplied by (on the right) must be in and the result will be in .
Given this framing, consider the following four types of functions.
| Type | Domain and Codomain | Examples |
|---|---|---|
| Scalar-to-scalar | ||
| Vector-to-scalar | ||
| Scalar-to-vector | ||
| Vector-to-vector | |
The first two types of functions are “scalar-valued”, while the latter two are “vector-valued”. These are not the only types of functions that exist; for instance, the function is a matrix-to-scalar function.
The type of function we’re most concerned with at the moment are vector-to-scalar functions, i.e. functions that take in a vector (or equivalently, multiple scalar inputs) and output a single scalar.
is one such function, and it’s the focus of this section.
Rates of Change¶
Let’s think from the perspectives of rates of change, since ultimately what we’re building towards is a technique for minimizing functions. We’re most familiar with the concept of rates of change for scalar-to-scalar functions.
If
then its derivative,
itself is a scalar-to-scalar function, which describes how quickly is changing at any point in the domain of . At , for instance, the instantaneous rate of change is
meaning that at , is decreasing at a rate of (approximately) 8.06 per unit change in . Perhaps a more intuitive way of thinking about the instantaneous rate of change is to think of it as the slope of the tangent line to at .
The steeper the slope, the faster is changing at that point; the sign of the slope tells us whether is increasing or decreasing at that point.
In Chapter 1.4, we saw how to compute derivatives of functions that take in multiple scalar inputs, like
In the language of Chapter 4.1, we’d call such a function a vector-to-scalar function, and might use the notation
This function has three partial derivatives, each of which describes the instantaneous rate of change of with respect to one of its inputs, while holding the other two inputs constant. There’s a good animation of what it means to hold an input constant in Chapter 1.4 that is worth revisiting.
Here,
The big idea of this section, the gradient vector, packages all of these partial derivatives into a single vector. This will allow us to think about the direction in which is changing, rather than just looking at its rates of change in each dimension independently.
To find , we need to compute the partial derivatives of with respect to each component of . The “input variables” to are and , so we need to compute and , but if you’d like, replace and with and if it makes the algebra a little cleaner, and then replace and with and at the end.
Putting these together, we have
Remember, itself is a function. If we plug in a value of , we get a new vector back.
What does really tell us? In order to visualize it, let me introduce another way of visualizing , called a contour plot.
I think of the contour plot as a birds-eye view 🦅 of when you look at it from above. when you look at the surface from above. Notice the correspondence between the colors in both graphs.
The circle-like traces in the contour plot are called level curves; they represent slices through the surface at a constant height. On the right, the circle labeled 0.1 represents the set of points where .
Visualizing the fact that is easier to do in the contour plot, since the contour plot is 2-dimensional, like the gradient vector is. Remember that red values are high and blue values are low.
At the point , which is at the tail of the vector drawn in gold, is near the global minimum, meaning there are lots of directions in which we can move to increase . But, the gradient vector at this point is , which points in the direction of steepest ascent starting at . The gradient describes the “quickest way up”.
As another example, consider the fact that .
Again, the gradient at gives us the direction in which is increasing the quickest at that very point. If we move even a little bit in any direction (in the direction of the gradient or some other direction), the gradient will change.
As you might guess, to find the critical points of a function – that is, places where it is neither increasing nor decreasing – we need to find points where the gradient is zero. Hold that thought.
Examples¶
More typically, the functions we’ll need to take the gradient of will themselves be defined in terms of matrix and vector operations. In all of these examples, remember that we’re working with vector-to-scalar functions.
Example: Dot Product¶
Let be some fixed vector (the equivalent of a constant in this context). Let’s find the gradient of
I find it helpful to think about in its expanded form,
Remember, contains all of the partial derivatives of , which we now need to compute.
What is ? To me, that looks like , since the first term is and none of the other terms involve .
Similarly, .
In general, .
Putting these together, we get
Example: Norm and Chain Rule¶
Here’s an extremely important example that shows up everywhere in machine learning. Find the gradients of:
Solution
As we did in the previous example, we can expand to get
For each , . So,
Think of this as the equivalent of the “power rule” for vectors.
There are two ways to find the gradient of : directly, or by using the chain rule. It’s not immediately obvious how the chain rule should work here, so we’ll start with the direct method and reason about how the chain rule may arise.
Direct method: Let’s start by expanding like we did above.
For each , the (regular, scalar-to-scalar) chain rule tells us that
So,
Chain rule method: Let me start by writing in terms of a composition of two functions.
where and . Note that is the vector-to-scalar function we found the gradient of above, and is a scalar-to-scalar function.
Then, generalizing the calculation we did with the first method, we have a “chain rule” for a function (where is scalar-to-scalar and is vector-to-scalar):
Remember that , so and . This means
which is what we found earlier.
Example: Norm to an Exponent¶
Find the gradient of , where is some real number.
Solution
We can treat this as a composition of two functions, and , and use the chain rule introduced in the solution to the previous example.
and . Putting these together yields
Example: Log Sum Exp¶
If , we can define the log sum exp function as
What is ? (The answer is called the softmax function, and comes up all the time in machine learning, when we want our models to output predicted probabilities in a classification problem.)
Solution
Let’s look at the partial derivatives with respect to each .
Then,
There isn’t really a way to simplify the expression using matrix-vector operations, so I’ll leave it as-is. As mentioned above, the gradient we’re looking at is called the softmax function. The softmax function maps , meaning its a vector-to-vector function.
Let’s suppose we have the matrix . What does passing it through the softmax function yield?
The output vector has the same number of elements as the input vector, but each element is between 0 and 1, and the sum of elements is 1, meaning that we can interpret the outputted vector as a probability distribution. Larger values in the output correspond to larger values in the input, and almost all of the “mass” is concentrated at the maximum element of the input vector (position 2), hence the name “soft” max. (The “hard” max might be in this case.)
Example: Quadratic Forms¶
Suppose and is an matrix. The function
is called a quadratic form, and its gradient is given by
We won’t directly cover the proof of this formula here; one place to find it is here. Instead, we’ll focus our energy on understanding how it works, since it’s extremely important.
Let . Expand out and compute directly by computing partial derivatives, and verify that the result you get matches the formula above.
In quadratic forms, we typically assume that is symmetric, meaning that . Why do you think this assumption is made (what does it help with)?
Hint: Let and . Compute and .
If is any symmetric matrix, what is ?
Suppose is symmetric and , , and . Find the gradient of
Solution
If , then
Then,
since , meaning .
For a particular quadratic form, there are infinitely many choices of matrices that represent it. To illustrate, let’s look at and as provided in the hint.
Note that both and are equal to the expression . In fact, any matrix of the form where would produce the same quadratic form.
So, to avoid this issue of having infinitely many choices of the matrix , we pick the symmetric matrix , where . As we’re about to see, this choice of simplifies the calculation of the gradient.
If is any symmetric matrix, then , and . So,
This is also an important rule; don’t forget it.
Think of as the matrix-vector equivalent of a quadratic function, . The derivative of is . Check out what the gradient of ends up being!
Summary of Important Gradient Rules¶
These are the core rules you need to know moving forward, not just because we’re about to use them in an important proof, but because they’ll come up repeatedly in your future machine learning work.
| Function | Name | Gradient |
|---|---|---|
| dot product | ||
| squared norm | ||
| quadratic form | if is symmetric, |
Optimization¶
In the calculus of scalar-to-scalar functions, we have a well-understood procedure for finding the extrema of a function. The general strategy is to take the derivative, set it to zero, and solve for the inputs (called critical points) that satisfy that condition. To be thorough, we’d perform a second derivative test to check whether each critical point is a maximum, minimum, or neither.
In the land of vector-to-scalar functions, the equivalent is to solve for where the gradient is zero, which corresponds to finding where all partial derivatives are zero. Assessing whether we’ve arrived at a maximum or minimum is more difficult to do in the vector-to-scalar case, and we will save a discussion of this for Chapter 4.2.
As an example, consider
As we computed earlier, the gradient of is for symmetric . So,
To find the critical points, we set the gradient to zero and solve the resulting system. We can also accomplish this by using the inverse of , if we happen to have it:
Either way, we find that satisfies , which corresponds to a local minimum.
Minimizing Mean Squared Error¶
Remember, the goal of this section is to minimize mean squared error,
In the general case, is an matrix, , and .
We’re now equipped with the tools to minimize by taking its gradient and setting it to zero. Hopefully, we end up with the same conditions on that we derived in Chapter 2.10.
In the most recent example we saw, the optimal vector corresponded to a local minimum. We know that we won’t run into such an issue here since cannot output a negative number (it is the average of squared losses), so its minimum possible output is 0, meaning that there will be some global minimizer .
Let’s start by rewriting the squared norm as a dot product and eventually matrix multiplication.
Let’s focus on the two terms in orange. They are both equal: they are both the dot product of and . Ideally, I want to express each term as a dot product of with something, since I’m taking the gradient with respect to . Remember, the dot product is a scalar, and the transpose of a scalar is just that same scalar. So,
so, performing this substitution in for both orange terms gives us
Now, we’re ready to take the gradient, which we’ll do term by term.
, since is a constant with respect to
using the dot product rule, since this is the dot product between (a vector) and (a vector)
, using the quadratic form rule, since is a symmetric matrix
Plugging these terms in gives us
Finally, to find the minimizer , we set the gradient to zero and solve.
Stop me if this feels familiar... these are the normal equations once again! It shouldn’t be a surprise that we ended up with the same conditions on that we derived in Chapter 2.10, since we were solving the same problem.
We’ve now shown that the minimizer of
is given by solving . These equations have a unique solution if is invertible, and infinitely many solutions otherwise. If satisfies the normal equations, then is the vector in that is closest to . All of that interpretation from Chapter 2.10 and Chapter 3 carry over; we’ve just introduced a new way of finding the solution.
Heads up: In Homework 9, you’ll follow similar steps to minimize a new objective function, that resembles but involves another term. There, you’ll minimize
where is a constant, called the regularization hyperparameter. (Notice the missing .) A good way to practice what you’ve learned (and to get a head start on the homework) is to compute the gradient of and set it to zero. We’ll walk through what the significance of is in the homework.