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 w1∗ and intercept w0∗ that minimized mean squared error,
Rsq(w0,w1)=n1i=1∑n(yi−(w0+w1xi))2
by computing ∂w0∂Rsq (the partial derivative with respect to w0) ∂w1∂Rsq, 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
Rsq(w)=n1∥y−Xw∥2=n1i=1∑n(yi−w⋅Aug(xi))2
where X is the n×(d+1) design matrix, y∈Rn is the observation vector, and w∈Rd+1 is the parameter vector we’re trying to pick. In Chapter 2.10, we minimized Rsq(w) by arguing that the optimal w∗ had to create an error vector, e=y−Xw∗, that was orthogonal to colsp(X), 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 Rsq for any d, that doesn’t involve computing d 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.
As we saw in Chapter 2.9 when we first introduced the concept of the inverse of a matrix, the notation
f:Rd→Rn
means that f is a function whose inputs are vectors with d components and whose outputs are vectors with n components. Rd is the domain of the function, and Rn is the codomain. I’ve used d and n to match the notation we’ve used for matrices and linear transformations. In general, if A is an n×d matrix, then any vector x multiplied by A (on the right) must be in Rd and the result Ax will be in Rn.
Given this framing, consider the following four types of functions.
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 f(A)=rank(A) 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.
Rsq(w)=n1∥y−Xw∥2
is one such function, and it’s the focus of this section.
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
f(x)=x2sin(x)
then its derivative,
dxdf=2xsin(x)+x2cos(x)
itself is a scalar-to-scalar function, which describes how quickly f is changing at any point x in the domain of f. At x=3, for instance, the instantaneous rate of change is
dxdf(3)=2⋅3sin(3)+32cos(3)≈−8.06
meaning that at x=3, f is decreasing at a rate of (approximately) 8.06 per unit change in x. 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 f at x=3.
The steeper the slope, the faster f is changing at that point; the sign of the slope tells us whether f 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
f(x,y,z)=x2+2xy+3xz+4(y−z)2
In the language of Chapter 4.1, we’d call such a function a vector-to-scalar function, and might use the notation
f(x)=x12+2x1x2+3x1x3+4(x2−x3)2
This function has three partial derivatives, each of which describes the instantaneous rate of change of f 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.
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 f is changing, rather than just looking at its rates of change in each dimension independently.
As usual, we’ll start with an example. Suppose x∈R2, and let
f(x)=x1e−x12−x22
from new_grad_utils import make_3D_surface
make_3D_surface(
f = lambda x, y: x * np.e ** (-x ** 2 - y ** 2),
lim = 2,
xaxis_title = 'x₁',
yaxis_title = 'x₂',
zaxis_title = 'f(x₁, x₂)',
title='',
)
Loading...
To find ∇f(x), we need to compute the partial derivatives of f with respect to each component of x. The “input variables” to f are x1 and x2, so we need to compute ∂x1∂f and ∂x2∂f, but if you’d like, replace x1 and x2 with x and y if it makes the algebra a little cleaner, and then replace x and y with x1 and x2 at the end.
What does ∇f([−10])=[−1/e0] really tell us? In order to visualize it, let me introduce another way of visualizing f, called a contour plot.
from new_grad_utils import make_3D_contour
fig = make_3D_contour(
f = lambda x, y: x * np.e ** (-x ** 2 - y ** 2),
lim = 2,
xaxis_title = 'x₁',
yaxis_title = 'x₂',
title=r'$$\text{Contour plot of } f(\vec x) = x_1 e^{-x_1^2 - x_2^2}$$',
)
fig.update_layout(width=700, height=700)
Loading...
I think of the contour plot as a birds-eye view 🦅 of f 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 f(x1,x2)=0.1.
Visualizing the fact that ∇f([−10])=[−1/e0] 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.
import numpy as np
def plot_gradient_on_contour(f, dfx1, dfx2, point, lim=2, **kwargs):
# Set a longer arrow for demonstration when using the (-1, 0) point
is_minus1_0 = np.allclose(point, (-1, 0))
# Remove 'arrow_len' from kwargs before passing into make_3D_contour
# since make_3D_contour does not accept 'arrow_len'
filtered_kwargs = dict(kwargs)
if 'arrow_len' in filtered_kwargs:
filtered_kwargs.pop('arrow_len')
# Don't add 'arrow_len' for make_3D_contour; let 3D surface handle it instead
return make_3D_contour(
f=f,
dfx1=dfx1,
dfx2=dfx2,
lim=lim,
with_gradient=True,
grad_point=point,
**filtered_kwargs
)
def plot_gradient_on_surface(f, dfx1, dfx2, point, lim=2, **kwargs):
"""
Plot 3D surface of f, mark the given point, and plot the gradient vector
as a dotted arrow (dashed line with a cone/arrows) coming out of that point.
Args:
f: function of two variables (x, y)
dfx1: function, df/dx1(x, y)
dfx2: function, df/dx2(x, y)
point: tuple/list/np.array of shape (2,) representing the location (x0, y0)
lim: limits for the plot axes
**kwargs: keyword args for customization
Returns:
Plotly figure.
"""
fig = make_3D_surface(
f=f,
lim=lim,
xaxis_title=kwargs.get('xaxis_title', 'x₁'),
yaxis_title=kwargs.get('yaxis_title', 'x₂'),
zaxis_title=kwargs.get('zaxis_title', 'f(x₁, x₂)'),
title=kwargs.get('surface_title', '3D Surface with Gradient Arrow')
)
x0, y0 = point
z0 = f(x0, y0)
# Compute the gradient vector at the given point
dx = dfx1(x0, y0)
dy = dfx2(x0, y0)
# Draw the starting (base) point as a marker
fig.add_scatter3d(
x=[x0], y=[y0], z=[z0],
mode='markers',
marker=dict(size=8, color='gold'),
showlegend=False
)
# Draw the gradient vector as a dotted (dashed) arrow out of that point
# Make the arrow longer if the gradient is small, as at (-1, 0)
is_minus1_0 = np.allclose([x0, y0], [-1, 0])
arrow_len = 1 # kwargs.get('arrow_len', 0.5)
if is_minus1_0:
arrow_len = 1.0 # Draw a relatively long arrow for this specific point
arrow_color = kwargs.get('arrow_color', 'gold')
# Use actual gradient magnitude for visual length, scaled by arrow_len
grad_norm = (dx**2 + dy**2) ** 0.5
if grad_norm == 0:
ax, ay = 0, 0
else:
# Scale the actual gradient components by arrow_len to control overall scale
ax = dx * arrow_len
ay = dy * arrow_len
# print(ax, ay)
# Approximate change in z using the tangent plane direction: dz = gradient dot (Δx, Δy)
dz = dx * ax + dy * ay
# Draw a dotted line for the "arrow body"
fig.add_trace(dict(
type='scatter3d',
x=[x0, x0 + ax],
y=[y0, y0 + ay],
z=[z0, z0 + dz],
mode='lines',
line=dict(color=arrow_color, width=5, dash='dot'),
showlegend=False
))
# Draw a cone (arrowhead) at the tip
fig.add_trace(
dict(
type="cone",
x=[x0 + ax],
y=[y0 + ay],
z=[z0 + dz],
u=[ax],
v=[ay],
w=[dz],
showscale=False,
colorscale=[[0, arrow_color],[1, arrow_color]],
sizemode="absolute",
sizeref=0.18 * arrow_len,
anchor="tip"
)
)
# Optionally, plot a marker at the tip of the arrow for emphasis
fig.add_scatter3d(
x=[x0 + ax], y=[y0 + ay], z=[z0 + dz],
mode='markers',
marker=dict(size=2, color=arrow_color, symbol='diamond'),
showlegend=False
)
return fig
def plot_gradient_side_by_side(f, dfx1, dfx2, point, lim=2, **kwargs):
return show_surface_and_contour_side_by_side(
f=f,
dfx1=dfx1,
dfx2=dfx2,
lim=lim,
with_gradient=True,
grad_point=point,
**kwargs
)
# Correct usage: Pass only the functions for gradient computation and the point.
fig = plot_gradient_on_contour(
f=lambda x, y: x * np.e ** (-x ** 2 - y ** 2),
dfx1=lambda x, y: (1 - 2 * x ** 2) * np.e ** (-x ** 2 - y ** 2),
dfx2=lambda x, y: -2 * x * y * np.e ** (-x ** 2 - y ** 2),
point=(-1, 0),
xaxis_title='x₁',
yaxis_title='x₂',
)
# Ensure the grid is square by setting aspectmode='equal' for both axes.
fig.update_layout(
width=700,
height=700,
)
fig
Loading...
At the point [−10], which is at the tail of the vector drawn in gold, f is near the global minimum, meaning there are lots of directions in which we can move to increase f. But, the gradient vector at this point is [−1/e0], which points in the direction of steepest ascent starting at [−10]. The gradient describes the “quickest way up”.
As another example, consider the fact that ∇f([1.25−0.5])≈[−0.3470.204].
fig = plot_gradient_on_contour(
f=lambda x, y: x * np.e ** (-x ** 2 - y ** 2),
dfx1=lambda x, y: (1 - 2 * x ** 2) * np.e ** (-x ** 2 - y ** 2),
dfx2=lambda x, y: -2 * x * y * np.e ** (-x ** 2 - y ** 2),
point=(1.25, -0.5),
xaxis_title='x₁',
yaxis_title='x₂',
)
fig.update_layout(
width=700,
height=700
)
Loading...
Again, the gradient at [1.25−0.5] gives us the direction in which f 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.
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.
Here’s an extremely important example that shows up everywhere in machine learning. Find the gradients of:
f(x)=∥x∥2
f(x)=∥x∥
Solution
As we did in the previous example, we can expand f(x)=∥x∥2 to get
f(x)=x⋅x=x12+x22+⋯+xn2
For each i, ∂xi∂f=2xi. So,
∇f(x)=⎣⎡2x12x2⋮2xn⎦⎤=2x
Think of this as the equivalent of the “power rule” for vectors.
There are two ways to find the gradient of f(x)=∥x∥: 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 f(x)=∥x∥ like we did above.
f(x)=x⋅x=(x⋅x)1/2=(x12+x22+⋯+xn2)1/2
For each i, the (regular, scalar-to-scalar) chain rule tells us that
Chain rule method: Let me start by writing f(x) in terms of a composition of two functions.
f(x)=∥x∥=∥x∥2=h(g(x))
where g(x)=∥x∥2 and h(x)=x. Note that g:Rn→R is the vector-to-scalar function we found the gradient of above, and h:R→R is a scalar-to-scalar function.
Then, generalizing the calculation we did with the first method, we have a “chain rule” for a function h(g(x)) (where h is scalar-to-scalar and g is vector-to-scalar):
∇f(x)=h′(g(x))(dxdh(g(x)))∇g(x)
Remember that h(x)=x, so dxdh(x)=2x1 and dxdh(g(x))=2g(x)1=2∥x∥1. This means
If x∈Rn, we can define the log sum exp function as
f(x)=log(i=1∑nexi)
What is ∇f(x)? (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 xi.
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 Rn→Rn, meaning its a vector-to-vector function.
Let’s suppose we have the matrix ⎣⎡35−1⎦⎤. 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 ⎣⎡010⎦⎤ in this case.)
is called a quadratic form, and its gradient is given by
∇f(x)=(A+AT)x
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 A=[acbd]. Expand out f(x)=xTAx and compute ∇f(x) directly by computing partial derivatives, and verify that the result you get matches the formula above.
In quadratic forms, we typically assume that A is symmetric, meaning that A=AT. Why do you think this assumption is made (what does it help with)?
Hint: Let A=[3621] and B=[3441]. Compute ∇(xTAx) and ∇(xTBx).
If A is any symmetric n×n matrix, what is ∇f(x)?
Suppose A is symmetric and n×n, b∈Rn, and c∈R. Find the gradient of
For a particular quadratic form, there are infinitely many choices of matrices A that represent it. To illustrate, let’s look at A=[3621] and B=[3441] as provided in the hint.
Note that both xTAx and xTBx are equal to the expression 3x12+8x1x2+x22. In fact, any matrix of the form [3cb1] where b+c=8 would produce the same quadratic form.
So, to avoid this issue of having infinitely many choices of the matrix A, we pick the symmetric matrix A, where A=AT. As we’re about to see, this choice of A simplifies the calculation of the gradient.
If A is any symmetric n×n matrix, then A=AT, and A+AT=2A. So,
∇(xTAx)=(A+AT)x=2Ax
This is also an important rule; don’t forget it.
Think of f(x)=xTAx+b⋅x+c as the matrix-vector equivalent of a quadratic function, ax2+bx+c. The derivative of ax2+bx+c is 2ax+b. Check out what the gradient of f(x) ends up being!
f(x)∇f(x)=xTAx+b⋅x+c=(A+AT)x+b=2Ax+b(since A is symmetric)
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.
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
f(x)=xT[3441]x+[12]⋅x+3
As we computed earlier, the gradient of f(x)=xTAx+b⋅x+c is ∇f(x)=2Ax+b for symmetric A. So,
∇f(x)=2[3441]x+[12]=[6x1+8x2+18x1+2x2+2]
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 A, if we happen to have it:
∇f(x)=0⟹2Ax+b=0⟹x∗=−21A−1b
Either way, we find that x∗=[−7/261/13] satisfies ∇f(x∗)=0, which corresponds to a local minimum.
import numpy as np
import plotly.graph_objs as go
# Define the function
def f(x, y):
return 3 * x ** 2 + 8 * x * y + y ** 2 + x + 2 * y + 3
fig = plot_gradient_on_surface(
f = f,
lim = 5,
xaxis_title = 'x₁',
yaxis_title = 'x₂',
zaxis_title = 'f(x₁, x₂)',
title='',
dfx1 = lambda x, y: 6 * x + 8 * y + 1,
dfx2 = lambda x, y: 8 * x + 2 * y + 2,
point = np.array([-7/26, 1/13]),
)
fig.update_layout(title='', scene_camera=dict(eye=dict(x=1, y=2, z=2)))
# Annotate the local minimum point
x_star = -7/26
y_star = 1/13
z_star = f(x_star, y_star)
fig.add_trace(
go.Scatter3d(
x=[x_star],
y=[y_star],
z=[z_star],
mode='markers+text',
marker=dict(size=12, color='gold', symbol='circle'),
text=["local minimum"],
textposition="top center",
textfont=dict(color='gold', size=14),
name="local minimum"
)
)
Remember, the goal of this section is to minimize mean squared error,
Rsq(w)=n1∥y−Xw∥2
In the general case, X is an n×(d+1) matrix, y∈Rn, and w∈Rd+1.
We’re now equipped with the tools to minimize Rsq(w) by taking its gradient and setting it to zero. Hopefully, we end up with the same conditions on w∗ that we derived in Chapter 2.10.
In the most recent example we saw, the optimal vector x∗ corresponded to a local minimum. We know that we won’t run into such an issue here since Rsq(w) 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 w∗.
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 y and Xw. Ideally, I want to express each term as a dot product of w with something, since I’m taking the gradient with respect to w. Remember, the dot product is a scalar, and the transpose of a scalar is just that same scalar. So,
yTXw=(yTXw)T=wTXTy=wT(XTy)
so, performing this substitution in for both orange terms gives us
Finally, to find the minimizer w∗, we set the gradient to zero and solve.
n2(XTXw∗−XTy)=0⟹XTXw∗=XTy
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 w∗ that we derived in Chapter 2.10, since we were solving the same problem.
We’ve now shown that the minimizer of
Rsq(w)=n1∥y−Xw∥2
is given by solving XTXw∗=XTy. These equations have a unique solution if XTX is invertible, and infinitely many solutions otherwise. If w∗ satisfies the normal equations, then Xw∗ is the vector in colsp(X) that is closest to y. 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 Rsq(w) but involves another term. There, you’ll minimize
Rridge(w)=∥y−Xw∥2+λ∥w∥2
where λ>0 is a constant, called the regularization hyperparameter. (Notice the missing n1.) A good way to practice what you’ve learned (and to get a head start on the homework) is to compute the gradient of Rridge(w) and set it to zero. We’ll walk through what the significance of Rridge(w) is in the homework.