Optimization in Multiple Variables
local graph
Hey! We are at the last checkpoint of our calculus study. What’s missing? Gradient descent, of course.
In the previous eight chapters, we lined up all of our ducks in a row, and now it’s time to take that shot. First, we’ll put multivariable functions to code. Previously, we built a convenient interface in the form of our Function class to represent differentiable functions. After the lengthy setup in the previous chapter, we can easily extend it, and with the power of vectorization, we don’t even have to change that much. Let’s go!
Bookmark
17.1 Multivariable functions in code
Section titled “17.1 Multivariable functions in code”It’s been a long time since we put theory into code. So, let’s take a look at multivariable functions!
Last time, we built a Function base class with two main methods: one for computing the derivative (Function.prime) and one for getting the dictionary of parameters (Function.parameters).
This won’t be much of a surprise: the multivariate function base class is not much different. For clarity, we’ll appropriately rename the prime method to grad.
class MultivariableFunction: def __init__(self): pass
def __call__(self, *args, **kwargs): pass
def grad(self): pass
def parameters(self): return dict()Let’s see a few examples right away. The simplest one is the squared Euclidean norm f(x) = ∥x∥2, a close relative to the mean squared error function. Its gradient is given by

thus everything is ready to implement it. As we’ve used NumPy arrays to represent vectors, we’ll use them as the input as well.
import numpy as np
class SquaredNorm(MultivariableFunction): def __call__(self, x: np.array): return np.sum(x**2)
def grad(self, x: np.array): return 2*xNote that SquaredNorm is different from f(x) = ∥x∥2 in a mathematical sense, as it accepts any NumPy array, not just an n-dimensional vector. This is not a problem now, but will be later, so keep that in mind.
Another example can be given with the parametric linear function

where a,b ∈ℝ are arbitrary parameters. Let’s see how g(x,y) is implemented!
class Linear(MultivariableFunction): def __init__(self, a: float, b: float): self.a = a self.b = b
def __call__(self, x: np.array): """ x: np.array of shape (2, ) """ x = x.reshape(2) return self.a*x[0] + self.b*x[1]
def grad(self, x: np.array): return np.array([self.a, self.b]).reshape(2, 1)
def parameters(self): return {"a": self.a, "b": self.b}To check if our implementation works correctly, we can quickly test it out on a simple example.
g = Linear(a=1, b=-1)
g(np.array([1, 0]))np.int64(1)Perhaps we might have overlooked this question until now, but trust me, specifying the input and output shapes is of crucial importance. When doing mathematics, we can be flexible in our notation and treat any vector x ∈ℝn as a column or row vector, but painfully, this is not the case in practice.
Correctly keeping track of array shapes is of utmost importance and can save you hundreds of hours. No joke.
Bookmark
17.2 Minima and maxima, revisited
Section titled “17.2 Minima and maxima, revisited”In a single variable, we have successfully used the derivatives to find the local optima of differentiable functions.
Recall that if f : ℝ →ℝ is differentiable everywhere, then Theorem 87 gives that
(a) f′(a) = 0 and f′′(a)>0 implies a local minimum. (b) f′(a) = 0 and f′′(a)>0 implies a local maximum.
(A simple f′(a) = 0 is not enough, as the example f(x) = x3 shows at 0.)
Can we do something similar in multiple variables?
Right from the start, there seems to be an issue: the derivative is not a scalar (thus, we can’t equate it to 0).
This is easy to solve: the analogue of the condition f′(a) = 0 is ∇f(a) = (0,0,…,0). For simplicity, the zero vector (0,0,…,0) will also be denoted by 0. Don’t worry, this won’t be confusing; it’s all clear from the context. Introducing a new notation for the zero vector would just add more complexity.
We can visualize what happens with the tangent plane at critical points. In a single variable, we have already seen this: as Figure 17.1 illustrates, f′(a) = 0 implies that the tangent line is horizontal.

Figure 17.1: Local extrema in a single variable
In multiple variables, the situation is similar: ∇f(a) = 0 implies that the best local linear approximation (16.3) is constant; that is, the tangent plane is horizontal. (As visualized by Figure 17.2.)

Figure 17.2: Local extrema in multiple variables
So, what does ∇f(a) = 0 imply? Similarly to the single-variable case, an a ∈ℝn is called a critical point of f if ∇f(a) = 0 holds. The similarity doesn’t stop at the level of terminologies. We also have three options in multiple variables as well: a is
- a local minimum,
- a local maximum,
- or neither.
In multiple variables, a non-extremal critical point is called a saddle point, because the two-dimensional case bears a striking resemblance to an actual horse saddle, as you are about to see. Saddle points are the high-dimensional analogues of the one-dimensional inflection points. The functions

at (0,0) provide an example for all three, as Figure 17.3, Figure 17.4, and Figure 17.5 show. (Keep in mind that a local extremum might be global.)

Figure 17.3: A (local) maximum

Figure 17.4: A (local) minima

Figure 17.5: A saddle point
To put things into order, let’s start formulating definitions and theorems.
Definition 73. (Critical points)
Let f : ℝn →ℝ be an arbitrary vector-scalar function. We say that a ∈ℝn is a critical point of f if either

holds, or f is not partially differentiable at a in at least one variable.
The second case (where f is not differentiable at a) is there to handle situations like f(x,y) = jxj + jyj.
For the sake of precision, let’s define local extrema in multiple dimensions as well.
Definition 74. (Local minima and maxima)
Let f : ℝn →ℝ be an arbitrary vector-scalar function and let a ∈ℝn be an arbitrary point.
(a) a is a local minimum if there exists an 𝜀>0 such that

(b) a is a strict local minimum if there exists an 𝜀>0 such that

(c) a is a local maximum if there exists an 𝜀>0 such that

(d) a is a strict local maximum if there exists an 𝜀>0 such that

As the example of x2 −y2 shows, a critical point is not necessarily a local extremum, but a local extremum is always a critical point. The next result, which is the analogue of Definition 73, makes this mathematically precise.
Theorem 106.
Let f : ℝn →ℝ be an arbitrary vector-scalar function, and suppose that f is partially differentiable with respect to all variables at some a ∈ℝn.
If f has a local extremum at a, then ∇f(a) = 0.
Proof. This is a direct consequence of Theorem 86, as if a = (a1,…,an) is a local extremum of the vector-scalar function f, then it is a local extremum of the single-variable functions h→f(a + hei), where ei is the vector whose i-th component is 1, while the others are 0.
According to the very definition of the partial derivative given by Definition 66,

Thus, Theorem 86 gives that

for all i = 1,…,n, giving that ∇f(a) = 0.
So, how can we find the local extrema with the derivative? As we have already suggested, studying the second derivative will help us pinpoint the extrema among critical points. Unfortunately, things are much more complicated in n variables, so let’s focus on the two-variable case first.
Theorem 107. (The two-variable second derivative test)
Let f : ℝ2 →ℝ be an arbitrary vector-scalar function, and suppose that f is partially differentiable at some a ∈ℝ2. Also suppose that a is a critical point, that is, ∇f(a) = 0.
(a) If detHf(a)>0 and
>0, then a is a local minimum.
(b) If detHf(a)>0 and
>0, then a is a local maximum.
(c) If detHf(a)>0, then a is a saddle point.
We will not prove this, but some remarks are in order. First, as the determinant of the Hessian can be 0, Theorem 107 does not cover all possible cases.
It’s probably best to see a few examples, so let’s revisit the previously seen functions

All three have a critical point at 0, so the Hessians can provide a clearer picture. The Hessians are given by the matrices

For functions of two variables, Theorem 107 says that it is enough to study detHf(a) and
(a).
In the case of f(x,y) = x2 + y2, we have Hf(0,0) = 4 and
(0,0) = 2, giving that 0 is a local minimum of f(x,y) = x2 + y2.
Similarly, we can conclude that 0 is a local maximum of g(x,y) = −(x2 + y2) (which shouldn’t surprise you, as g = −f).
Finally, for h(x,y) = x2 −y2, the second derivative test confirms that 0 is indeed a saddle point.
So, what’s up with the general case? Unfortunately, just studying the determinant of the Hessian matrix is not enough. We need to bring in the heavy-hitters: eigenvalues. (See Definition 23.) Here is the second derivative test in its full glory.
Theorem 108. (The multivariable second derivative test)
Let f : ℝn →ℝ be an arbitrary vector-scalar function, and suppose that f is partially differentiable with respect to all variables at some a ∈ℝn. Also suppose that a is a critical point, that is, ∇f(a) = 0.
(a) If all the eigenvalues of Hf(a) are positive, then a is a local minimum.
(b) If all the eigenvalues of Hf(a) are negative, then a is a local maximum.
(c) If all the eigenvalues of Hf(a) are either positive or negative, then a is a saddle point.
That’s right: if any of the eigenvalues are 0, then the test is inconclusive. You might recall from linear algebra that in practice, computing the eigenvalues is not as fast as computing the second-order derivatives, but there are plenty of numerical methods (like the QR-algorithm, as we saw in Section 7.5).
To sum it up, the method of optimizing (differentiable) multivariable functions is a simple two-step process:
- find the critical points by solving the equation ∇f(x) = 0,
- then use the second derivative test to determine which critical points are extrema.
Do we use this method in practice to optimize functions? No. Why? Most importantly, because computing the eigenvalues of the Hessian for a vector-scalar function with millions of variables is extremely hard. Why is the second derivative test so important? Because understanding the behavior of functions around their extremal points is essential to truly understand gradient descent. Believe it or not, this is the key behind the theoretical guarantees for convergence.
Speaking of gradient descent, now is the time to dig deep into the algorithm that powers neural networks.
Bookmark
17.3 Gradient descent in its full form
Section titled “17.3 Gradient descent in its full form”Gradient descent is one of the most important algorithms in machine learning. We have talked about this a lot, although up until this point, we have only seen it for single-variable functions (which is, I admit, not the most practical use case).
However, now we have all the tools we need to talk about gradient descent in its general form. Let’s get to it!
Suppose that we have a differentiable vector-scalar function f : ℝn →ℝ that we want to maximize. This can describe the return on investment of an investing strategy, or any other quantity. Calculating the gradient and finding the critical points is often not an option, as solving the equation ∇f(x) = 0 can be computationally unfeasible. Thus, we resort to an iterative solution.
The algorithm is the same as for single-variable functions (as seen in Section 13.2):
- Start from a random point.
- Calculate its gradient.
- Take a step towards its direction.
- Repeat until convergence.
This is called gradient ascent. We can formalize it in the following way.
(The gradient ascent algorithm) Step 1. Initialize the starting point x0 ∈ℝn and select a learning rate h ∈ (0,∞). Step 2. Let

Step 3. Repeat Step 2. until convergence.
If we want to minimize f, we might as well maximize −f. The only effect of this is a sign change for the gradient. In this form, the algorithm is called gradient descent, and this is the version that’s widely used to train neural networks.
(The gradient descent algorithm) Step 1. Initialize the starting point x0 ∈ℝn and select a learning rate h ∈ (0,∞). Step 2. Let

Step 3. Repeat Step 2. until convergence.
After all of this setup, implementing gradient descent is straightforward.
def gradient_descent( f: MultivariableFunction, x_init: np.array, # the initial guess learning_rate: float = 0.1, # the learning rate n_iter: int = 1000, # number of steps): x = x_init
for n in range(n_iter): grad = f.grad(x) x = x - learning_rate*grad
return xNotice that it is almost identical to the single-variable version in Section 13.2. To see if it works correctly, let’s test it out on the squared Euclidean norm function, implemented by SquaredNorm earlier!
squared_norm = SquaredNorm()local_minimum = gradient_descent( f=squared_norm, x_init=np.array([10.0, -15.0]))
local_minimumarray([ 1.23023192e-96, -1.84534788e-96])There is nothing special to it, really. The issues with multivariable gradient descent are the same as what we discussed with the single-variable version: it can get stuck in local minima, it is sensitive to our choice of learning rate, and the gradient can be computationally hard to calculate in high dimensions.
Bookmark
17.4 Summary
Section titled “17.4 Summary”Although this chapter was short and sweet, we took quite a big step by dissecting the fine details of gradient descent in high dimensions. The chapter’s brevity is a testament to the power of vectorization: same formulas, code, and supercharged functionality. It’s quite unbelievable, but the simple algorithm

is behind most of the neural network models. Yes, even state-of-the-art ones.
This lies on the same theoretical foundations as the univariate case, but instead of checking the positivity of the second derivatives, we have to study the full Hessian matrix Hf. To be more precise, we have learned that a critical point ∇f(a) = 0 is
- a local minimum if all the eigenvalues of Hf(a) are positive,
- and a local maximum if all the eigenvalues of Hf(a) are negative.
Deep down, this is the reason why gradient descent works. And with this, we have finished our study of calculus, both in single and multiple variables.
Take a deep breath and relax a bit. We are approaching the final stretch of our adventure: our last stop is the theory of probability, the thinking paradigm that is behind predictive modeling. For instance, the most famous loss functions, like the mean-squared error or the cross-entropy, are founded upon probabilistic concepts. Understanding and taming uncertainty is one of the biggest intellectual feats of science, and we are about to undertake this journey ourselves.
See you in the next chapter!
Bookmark
17.5 Problems
Section titled “17.5 Problems”Problem 1. Let y ∈ℝn be an arbitrary vector. The general version of the famous mean-squared error is defined by

Compute its gradient and implement it using the MultivariateFunction base class!
Problem 2. Let f : ℝ2 →ℝ be the function defined by

Does f have a local extremum in x = (0,0)?
Problem 3. Use the previously implemented gradient_descent function to find the minimum of

Experiment with various learning rates and initial values!
Problem 4. In the problem section of Chapter 13, we saw the improved version of gradient descent, called gradient descent with momentum. We can do the same in multiple variables: define

where d0 = 0 and x0 is arbitrary. Implement it!