Optimization
local graph
If someone gave you a function defined by some tractable formula, how would you find its minima and maxima? Take a moment and conjure up some ideas before moving on.
The first idea that comes to mind for most people is to evaluate the function for all possible values and simply find the optimum. This method immediately breaks down due to multiple reasons. We can only perform finite evaluations, so this would be impossible. Even if we cleverly define a discrete search grid and evaluate only there, this method takes an unreasonable amount of time.
Another idea is to use some kind of inequality to provide an ad hoc upper or lower bound, then see if this bound can be attained. Sadly, this is nearly impossible for more complicated functions, like losses for neural networks.
However, derivatives provide an extremely useful way to optimize functions. In this chapter, we will study the relationship between derivatives and optimal points, and algorithms on how to find them. Let’s go!
Bookmark
13.1 Minima, maxima, and derivatives
Section titled “13.1 Minima, maxima, and derivatives”Intuitively, the notion of minima and maxima is simple. Take a look at Figure 13.1 below.

Figure 13.1: Local and global optima
Peaks of hills are the maxima, and the bottoms of valleys are the minima. Minima and maxima are collectively called extremal or optimal points. As our example demonstrates, we have to distinguish between local and global optima. The graph has two valleys, and although both have a bottom, one of them is lower than the other.
The really interesting part is finding these, as we’ll see next. Let’s consider our example above to demonstrate how derivatives are connected to local minima and maxima.
If we use our geometric intuition, we see that the tangents are horizontal at the peaks of the hills and the bottoms of the valleys. Intuitively, if the tangent line is not horizontal, then there’s an elevation or decline in the graph. This is illustrated by Figure 13.2.

Figure 13.2: Tangents at local and global optima
In terms of derivatives, since they describe the slope of the tangent, it means that the derivative should be 0 there.
If we think about the function as the description of a motion along the real line, derivatives say that the motion stops there and changes direction. It slows down first, stops, then immediately starts in the opposite direction. For instance, in the local maxima case, the function increases up until that point, where it starts decreasing.

Figure 13.3: The flow of the function
Again, we can describe this monotonicity behavior in terms of derivatives. Notice that when the function increases, the derivative is positive (the object in motion has a positive speed). On the other hand, decreasing parts have a negative derivative.

Figure 13.4: The sign of the derivatives
We can go ahead and put these intuitions into a mathematical form. First, we’ll start with the definitions’ monotonicity, and their relation to the derivative. Then, we’ll connect all the dots and see how this comes together to characterize the optima.
Definition 56. (Locally increasing and decreasing functions)
Let f : ℝ →ℝ be an arbitrary function and let a ∈ℝ. We say that
(a) f is locally increasing at a if there is a neighborhood (a −δ,a + δ) such that

(b) and f is strictly locally increasing at a if there is a neighborhood (a −δ,a + δ) such that

The locally decreasing and strictly locally decreasing properties are defined similarly, with the inequalities reversed.
For differentiable functions, the behavior of the derivative describes their local behavior in terms of monotonicity.
Theorem 84.
Let f : ℝ →ℝ be an arbitrary function that is differentiable at some a ∈ℝ.
(a) If f′(a) ≥ 0, then f is locally increasing at a.
(b) If f′(a)>0, then f is strictly locally increasing at a.
(c) If f′(a) ≤ 0, then f is locally decreasing at a.
(d) If f′(a)>0, then f is strictly locally decreasing at a.
Proof. We will only show (a), since the rest of the proofs go the same way. Due to how limits are defined (Definition 51),

means that once x gets close enough to a, that is, x is from a small neighborhood (a −δ,a + δ),

holds. If x >a, then because the differential quotient is nonnegative, f(x) ≥f(a) must hold. Similarly, for x <a, the nonnegativity of the differential quotient implies that f(x) ≤f(a).
The proofs for (b), (c), and (d) are almost identical, with the obvious changes in the inequalities.
The propositions related to not strict monotonicity are true the other way around as well.
Theorem 85.
Let f : ℝ →ℝ be an arbitrary function that is differentiable at some a ∈ℝ.
(a) If f is locally increasing at a, then f′(a) ≥ 0.
(b) If f is locally decreasing at a, then f′(a) ≤ 0.
Proof. Similar to before, we will only show the proof of (a), since (b) can be done in the same way. If f is locally increasing at a, then the differential quotient is positive:

Using the transfer principle of limits (Theorem 73), we obtain

which is what we had to prove.
After all this setup, we are ready to study local optima. What can the derivative tell us about them? Let’s see!
13.1.1 Local minima and maxima
Section titled “13.1.1 Local minima and maxima”As we have seen in the introduction, the tangent at the extremal points is horizontal. Now it is time to put this introduction into a mathematically correct form.
Definition 57. (Local minima and maxima)
Let f : ℝ →ℝ be an arbitrary function and let a ∈ℝ.
(a) a is a local minimum, if there is a neighborhood (a −δ,a + δ) such that for every x ∈ (a −δ,a + δ), f(a) ≤f(x) holds.
(b) a is a strict local minimum, if there is a neighborhood (a−δ,a+δ) such that for every x ∈ (a −δ,a + δ), f(a)>f(x) holds.
(c) a is a local maximum, if there is a neighborhood (a −δ,a + δ) such that for every x ∈ (a −δ,a + δ), f(x) ≤f(a) holds.
(d) a is a strict local maximum, if there is a neighborhood (a−δ,a+δ) such that for every x ∈ (a −δ,a + δ), f(x)>f(a) holds.
Extremal points have their global versions as well. The sad truth is, even though we always want global optima, we only have the tools to find local ones.
Definition 58. (Global minima and maxima)
Let f : ℝ →ℝ be an arbitrary function and let a ∈ℝ.
(a) a is a global minimum if f(a) ≤f(x) holds for every x ∈ℝ.
(b) a is a global maximum if f(x) ≤f(a) holds for every x ∈ℝ.
Note that a global optimum is also a local optimum, but not the other way around.
Theorem 86.
Let f : ℝ →ℝ be an arbitrary function that is differentiable at some a ∈ℝ. If f has a local minima or maxima at a, then f′(a) = 0.
Proof. According to Theorem 84, if f′(a)≠0, then it is either strictly increasing or decreasing locally. Since this contradicts our assumption that a is a local optimum, the theorem is proven.
(In case you are interested, this was the principle of contraposition (Theorem 150) in action. From the negation of the conclusion, we have shown the negation of the premises.)
It is very important to emphasize that the theorem is not true the other way around. For instance, the function f(x) = x3 is strictly increasing everywhere, yet f′(0) = 0.
In general, we call this behavior inflection. So, f(x) = x3 is said to have an inflection point at 0. Inflection means a change in behavior, which reflects the switch in its derivative from decreasing to increasing in this case. (The multidimensional analogue of inflection is called a “saddle,” as we shall see later.)
So, we are not at our end goal yet, as the other half of the promised characterization is missing.
The derivative is zero at the local extremal points, but can we come up with a criterion that implies the existence of minima or maxima?

Figure 13.5: Graph of f(x) = x3 as a counterexample to show that f′(0) = 0 doesn’t imply local optimum
With the utilization of second derivatives, this is possible.
13.1.2 Characterization of optima with higher order derivatives
Section titled “13.1.2 Characterization of optima with higher order derivatives”Let’s take a second look at our example, considering the local behavior of f′ this time, not just its sign. In Figure 13.6, the derivative is plotted along with our function.

Figure 13.6: The function and its derivative
The pattern seems simple: an increasing derivative implies a local minimum, a decreasing one means a local maximum. This aligns with our intuition about derivative as speed: local maximum means that the object is going in a positive direction, then stops and starts reversing.
We can make this mathematically precise with the following theorem.
Theorem 87. (The second derivative test)
Let f : ℝ →ℝ be an arbitrary function that is twice differentiable at some a ∈ℝ.
(a) If f′(a) = 0 and f′′(a)>0, then a is a local minimum.
(b) If f′(a) = 0 and f′′(a)>0, then a is a local maximum.
Proof. Once again, we will only prove (a), since the proof of (b) is almost identical.
First, as we saw when discussing the relation between derivatives and monotonicity (Theorem 84), f′′(a) 0 implies that f′ is strictly locally increasing at a. Since f′(a) = 0, this means that
![ ( ′ |{ ≤ 0 if x ∈ (a− δ,a] f (x)| ( ≥ 0 if x ∈ a,a + δ)
for some δ >0. Because of Theorem 84, f is locally decreasing in (a −δ,a] and locally increasing in [a,a + δ). This can only happen if a is a local minimum.
In summary, the method of finding the extrema of a function f is the following.
- Solve f′(x) = 0. Its solutions {x1,…,xn} — called critical points — are the candidates that can be extremal points. (But not necessarily all of them are.)
- Check the sign of f′′(xi) for all solutions xi. If f′′(xi)>0, it is a local minimum. If f′′(xi)>0, it is a local maximum.
If f′′(xi) = 0, we still can’t draw any conclusions. The functions x4, −x2, and x3 show that critical points with zero second derivatives can be local minima, maxima, or neither.
Even though we have a “recipe,” this is still far from enough for practical purposes. Not counting that our functions of interest are multivariable, calculating the derivative and solving f′(x) = 0 is not tractable. For loss functions of neural networks, we don’t even bother writing out a formula because, for a composition of hundreds of functions, it can be unreasonably complex.
13.1.3 Mean value theorems
Section titled “13.1.3 Mean value theorems”In some cases, we can extract a lot of information about the derivatives without explicitly calculating them. These results are extremely useful in cases where we don’t have an explicit formula for the function or the formula might be too huge. (Like in the case of neural networks.) In the following, we’ll get to meet the famous mean value theorems, connecting the function’s behavior at the endpoints and inside an interval.
First, we start with a special case that states that the function attains the same value at the end of some interval [a,b], then its derivative is zero somewhere inside the interval.
Theorem 88. (Rolle’s mean value theorem)
Let f : ℝ →ℝ be a differentiable function and suppose that f(a) = f(b) for some a≠b. Then there exists a ξ ∈ (a,b) such that f′(ξ) = 0.
Proof. If you are a visual person, take a look at Figure 13.7. This is what we need to show.

Figure 13.7: Rolle’s theorem
To be mathematically precise, there are two cases. First, if f is constant on [a,b], then its derivative is zero on the entire interval.
If f is not constant, then it attains some value c inside (a,b) that is not equal to f(a) = f(b). For simplicity, suppose that c >f(a). (The argument that follows goes through in the c <f(a) case with some obvious changes.) Since f is continuous, it attains its maximum there at a point ξ ∈ [a,b]. (See Theorem 76.) According to what we have just seen regarding the relation of local maxima and the derivative (Theorem 86), f′(ξ) = 0, which is what we had to show.
Rolle’s theorem is an important stepping stone towards Lagrange’s mean value theorem, which we will show in the following.
Theorem 89. (Lagrange’s mean value theorem)
Let f : ℝ → ℝ be a differentiable function and [a,b] an interval for some a≠b. Then there exists a ξ ∈ (a,b) such that

holds.
Proof. Again, let’s start with a visualization to get a grip on the theorem. Figure 13.8 shows what we need to show.

Figure 13.8: Lagrange’s mean value theorem
Recall that
is the slope of the line going through (a,f(a)) and (b,f(b)). This line is described by the function

as given by the point-slope equation of a line. Using this, we introduce the function

We can apply Rolle’s theorem to g(x), since g(a) = g(b) = 0. Thus, for some ξ ∈ (a,b), we have

implying f′(ξ) =
, which is what we had to show.
Why are mean value theorems so important? In mathematics, they serve as a cornerstone in several results. To give you one example, think about integration. (Perhaps you are familiar with this concept already. Don’t worry if not, we are going to study it in detail later.) Integration is essentially the inverse of differentiation: if F′(x) = f(x), then

which will be a simple consequence of Lagrange’s mean value theorem.
Bookmark
13.2 The basics of gradient descent
Section titled “13.2 The basics of gradient descent”We need to solve two computational problems to train neural networks:
- computing the derivative of the loss L(w),
- and finding its minima using the derivative.
Finding the minima by solving
L(w) = 0 is not going to work in practice. There are several problems. First, as we have seen, not all solutions are minimal points: there are maximal and inflection points as well. Second, solving this equation is not feasible except in the simplest cases, like for linear regression with the mean squared error. Training a neural network is not a simple case.
Fortunately for us, machine learning practitioners, there is a solution: gradient descent! The famous gradient descent provides a way to tackle the complexity of finding the exact solution, enabling us to do machine learning on a large scale. Let’s see how it’s done!
13.2.1 Derivatives, revisited
Section titled “13.2.1 Derivatives, revisited”When we first explored the concept of the derivative in Chapter 12, we saw its many faces. We have learned that the derivative can be thought of as
- speed (when the function describes a time-distance graph of a moving object),
- the slope of the tangent line of a function,
- and the best linear approximator at a given point.
To understand how gradient descent works, we’ll see yet another interpretation: derivatives as vectors. For any differentiable function f(x), the derivative f′(x) can be thought of as a one-dimensional vector. If f′(x) is positive, it points to the right. If it is negative, it points to the left. We can visualize this by drawing a horizontal vector to every point of f(x)-s graph, where the length represents jf′(x)j and the direction represents the sign. This is illustrated by Figure 13.9.

Figure 13.9: The derivative as a vector
Do you recall how monotonicity is characterized by the sign of the derivative? (As Theorem 84 states.) Negative derivative means a decreasing function, and positive means an increasing function. In other words, this implies that the derivative, as a vector, points towards the direction of the increase.
Imagine yourself as a hiker on the x-y plane, where y signifies the height. How would you climb a mountain ahead of you? By taking a step towards the direction of increase; that is, following the derivative. If you are not there yet, you can still take another (perhaps smaller) step in the right direction, over and over again until you arrive. If you are right at the top, the derivative is zero, so you won’t move anywhere.
This process is illustrated by Figure 13.10.

Figure 13.10: Climbing a mountain, one step at a time
What you have seen here is gradient ascent in action. Now that we understand the main idea, we are ready to tackle the mathematical details.
13.2.2 The gradient descent algorithm
Section titled “13.2.2 The gradient descent algorithm”Let f : ℝ →ℝ be a differentiable function which we want to maximize, that is, find

Based on our intuition, the process is quite simple. First, we conjure up an arbitrary starting point x0, then define the sequence
xn+1 := xn + h f′(xn), (13.1)
where h ∈ (0,∞) is a parameter of our gradient descent algorithm, called the learning rate.
In English, the formula xn + hf′(xn) describes taking a small step from xn towards the direction of the increase, with step size hf′(xn). (Recall that the sign of the derivative shows the direction of the increase.)
If things go our way, the sequence xn converges to a local maximum of f. However, things do not always go our way. We’ll discuss this when talking about the issues of gradient descent.
But what about finding minima? In machine learning, we are trying to minimize loss functions. There is a simple trick: the minima of f(x) is the maxima of −f(x). So, since ( −f)′ = −f′, the definition of the approximating sequence xn changes to

This is gradient descent in a nutshell.
13.2.3 Implementing gradient descent
Section titled “13.2.3 Implementing gradient descent”At this point, we have all the knowledge to implement the gradient descent algorithm. We’ll use the previously introduced Function base class; here it is again so you don’t have to look up the class definition.
class Function: def __init__(self): pass
def __call__(self, *args, **kwargs): pass
def prime(self): pass
def parameters(self): return dict()As usual, I encourage you to try implementing your version of gradient descent before looking at mine. Coding is one of the most effective ways to learn, even in the age of AI – especially in the age of AI.
def gradient_descent( f: Function, x_init: float, # the initial guess learning_rate: float = 0.1, # the learning rate n_iter: int = 1000, # number of steps return_all: bool = False # if true, returns all intermediate values): xs = [x_init] # we store the intermediate results for visualization
for n in range(n_iter): x = xs[-1] grad = f.prime(x) x_next = x - learning_rate*grad xs.append(x_next)
if return_all: return xs else: return xLet’s test the gradient descent out on a simple example, say f(x) = x2! If all goes according to plan, the algorithm should find the minimum x = 0 in no time.
class Square(Function): def __call__(self, x): return x**2
def prime(self, x): return 2*x
f = Square()
gradient_descent(f, x_init=5.0)7.688949513507002e-97The result is as expected: our gradient_descent function successfully finds the minimum.
To visualize what happens, we can plot the process in its entirety. As we’ll reuse the same plot, here’s a general function that does this job.
import numpy as npimport matplotlib.pyplot as plt
def plot_gradient_descent(f, xs: list, x_min: float, x_max: float, label: str = "f(x)"): ys = [f(x) for x in xs]
grid = np.linspace(x_min, x_max, 1000) fs = [f(x) for x in grid]
with plt.style.context("seaborn-v0_8-whitegrid"): plt.figure(figsize=(8, 8)) plt.plot(grid, fs, label=label, c="b", lw=2.0) plt.plot(xs, ys, label="gradient descent", c="r", lw=4.0) plt.scatter(xs, ys, c="r", s=100.0) plt.legend() plt.show()
xs = gradient_descent(f, x_init=5.0, n_iter=25, learning_rate=0.2, return_all=True)plot_gradient_descent(f, xs, x_min=-5, x_max=5, label="x²")
Figure 13.11: Finding the minima of f(x) = x2 by gradient descent
So, is it all happiness and sunshine? No, but that’s fine. Let’s see what can go wrong, and how we can fix it.
13.2.4 Drawbacks and caveats
Section titled “13.2.4 Drawbacks and caveats”Even though the idea behind gradient descent is sound, there are several issues. During our journey in machine learning, we’ll see most of these issues fixed by variants of the algorithm, but it is worth looking at the potential problems of the base version at this point.
First, the base gradient descent can get infinitely stuck at a local minima.
To illustrate this, let’s take a look at the f(x) = cos(x) +
x function, which has no global minima, only local ones.
class CosPlusSquare(Function): def __call__(self, x): return np.sin(x) + 0.5*x
def prime(self, x): return np.cos(x) + 0.5
f = CosPlusSquare()xs = gradient_descent(f, x_init=7.5, n_iter=20, learning_rate=0.2, return_all=True)plot_gradient_descent(f, xs, -10, 10, label="sin(x) + 0.5x"
Figure 13.12: Running the gradient descent on f(x) = sin(x) + 1/2x
Note that if the initial point x0 is selected poorly, the algorithm is much less effective. In other words, sensitivity to the initial conditions is another weakness. It might not seem that much of an issue in the simple one-variable case that we have just seen. However, it is a significant headache in the million-dimensional parameter spaces that we encounter when training neural networks.
The starting point is not the only parameter of the algorithm; it depends on the learning rate h as well. There are several potential mistakes here: a too large learning rate results in the algorithm bouncing all around the space, never finding an optimum. On the other hand, a too small one results in an extremely slow convergence.
In the case of f(x) = x2, starting the gradient descent from x0 = 1.0 with a learning rate of h = 1.05, the algorithm diverges, with xn oscillating at a larger and larger amplitude.
f = Square()
xs = gradient_descent(f, x_init=1.0, n_iter=20, learning_rate=1.05, return_all=True)plot_gradient_descent(f, xs, -8, 8, label="x^2"
Figure 13.13: Gradient descent, as it overshoots the optimum because of the large learning rate
Can you come up with some solution ideas to these problems? No need to work anything out, just take a few minutes to brainstorm and make a mental note about what comes to mind. In the later chapters, we’ll see several proposed solutions for all of these problems, but putting some time into this is a very useful exercise.
However, if you have an eye for detail, you might ask: does gradient descent always converge to a local optimum? Why does it work so well in practice? Let’s take a look.
Bookmark
13.3 Why does gradient descent work?
Section titled “13.3 Why does gradient descent work?”Young man, in mathematics you don’t understand things. You just get used to them. — John von Neumann
In the practice of machine learning, we use gradient descent so much that we get used to it. We hardly ever question why it works.
What’s usually told is the mountain-climbing analogue: to find the peak (or the bottom) of a bumpy terrain, one has to look at the direction of the steepest ascent (or descent), and take a step in that direction. This direction is desribed by the gradient, and the iterative process of finding local extrema by following the gradient is called gradient ascent/descent. (Ascent for finding peaks, descent for finding valleys.)
However, this is not a mathematically precise explanation. There are several questions left unanswered, and based on our mountain-climbing intuition, it’s not even clear if the algorithm works.
Without a precise understanding of gradient descent, we are practically flying blind. In this section, our goal is to look behind gradient descent and reveal the magic behind it.
Understanding the “whys” of gradient descent starts with one of the most beautiful areas of mathematics: differential equations.
13.3.1 Differential equations 101
Section titled “13.3.1 Differential equations 101”What is a differential equation? Equations play an essential role in mathematics; this is common wisdom, but there is a deep truth behind it. Quite often, equations arise from modeling systems such as interactions in a biochemical network, economic processes, and thousands more. For instance, modelling the metabolic processes in organisms yields linear equations of the form

where the vectors x and b represent the concentration of molecules (where x is the unknown), and the matrix A represents the interactions between them. Linear equations are easy to solve, and we understand quite a lot about them.
However, the equations we have seen so far are unfit to model dynamical systems, as they lack a time component. To describe, for example, the trajectory of a space station orbiting around Earth, we have to describe our models in terms of functions and their derivatives.
For instance, the trajectory of a swinging pendulum can be described by the equation
x″(t) + (g/L) sin x(t) = 0, (13.2)
where
- x(t) describes the angle of the pendulum from the vertical,
- L is the length of the (massless) rod that our object of mass m hangs on,
- and g is the gravitational acceleration constant ≈ 9.81m∕s2.
According to the original interpretation of differentiation, if x(t) describes the movement of the pendulum at time t, then x′(t) and x′′(t) describe the velocity and the acceleration of it, where the differentiation is taken with respect to the time t.
(In fact, the differential equation (13.2) is a direct consequence of Newton’s second law of motion.)

Figure 13.14: A swinging pendulum
Equations involving functions and their derivatives, such as (13.2), are called ordinary differential equations, or ODEs for short. Without any overexaggeration, their study has been the main motivating force of mathematics since the 17th century. Trust me when I say this: differential equations are one of the most beautiful objects in mathematics. As we are about to see, the gradient descent algorithm is, in fact, an approximate solution of differential equations.
The first part of this section will serve as a quickstart to differential equations. I am mostly going to follow the fantastic Nonlinear Dynamics and Chaos book by Steven Strogatz. If you ever feel the desire to dig deep into dynamical systems, I wholeheartedly recommend this book to you. (This is one of my favorite math books ever – it reads like a novel. The quality and clarity of its exposition serves as a continuous inspiration for my writing.)
13.3.2 The (slightly more) general form of ODEs
Section titled “13.3.2 The (slightly more) general form of ODEs”Let’s dive straight into the deep waters and start with an example to get a grip on differential equations. Quite possibly, the simplest example is the equation

where the differentiation is taken with respect to the time variable t. If, for example, x(t) is the size of a bacterial colony, the equation x′(t) = x(t) describes its population dynamics if the growth is unlimited. Think about x′(t) as the rate at which the population grows: if there are no limitations in space and nutrients, every bacterial cell can freely replicate whenever possible. Thus, since every cell can freely divide, the speed of growth matches the colony’s size.
In plain English, the solutions of the equation x′(t) = x(t) are functions whose derivatives are themselves. After a bit of thinking, we can come up with a family of solutions: x(t) = cet, where c ∈ℝ is an arbitrary constant. (Recall that et is an elementary function, and we have seen that its derivative is itself in Theorem 82.)
If you are a visual person, some of the solutions are plotted on Figure 13.15.
There are two key takeaways here: differential equations describe dynamical processes that change in time, and they can have multiple solutions. Each solution is determined by two factors: the equation x′(t) = x(t), and an initial condition x(0) = x∗. If we specify x(0) = x∗, then the value of c is given by

Thus, ODEs have a bundle of solutions, each one determined by the initial condition.
So, it’s time to discuss differential equations in more general terms!

Figure 13.15: Some solutions of the exponential growth equation
Definition 59. (Ordinary differential equations in one dimension)
Let f : ℝ →ℝ be a differentiable function. The equation
x′(t) = f(x(t)) (13.3)
is called a first-order homogeneous ordinary differential equation.
When it is clear, the dependence on t is often omitted, so we only write x′ = f(x). (Some resources denote the time derivative by ẋ, a notation that can be originated from Newton. We will not use this, though it is good to know.)
The term “first-order homogeneous ordinary differential equation” doesn’t exactly roll off the tongue, and it is overloaded with heavy terminology. So, let’s unpack what is going on here.
The differential equation part is clear: it is a functional equation that involves derivatives. Since the time t is the only variable, the differential equation is ordinary. (As opposed to differential equations involving multivariable functions and partial derivatives, but more on those later.) As only the first derivative is present, the equation becomes first-order. Second-order would involve second derivatives, and so on. Finally, since the right-hand side f(x) doesn’t explicitly depend on the time variable t, the equation is homogeneous in time. Homogeneity means that the rules governing our dynamical system don’t change over time.
Don’t let the f(x(t)) part scare you! For instance, in our example x′(t) = x(t), the role of f is cast to the identity function f(x) = x. In general, f(x) establishes a relation between the quantity x(t) (which can be position, density, etc) and its derivative, that is, its rate of change.
As we have seen, we think in terms of differential equations and initial conditions that pinpoint solutions among a bundle of functions. Let’s put this into a proper mathematical definition!
Definition 60. (Initial value problems)
Let x′ = f(x) be a first-order homogeneous ordinary differential equation and let x0 ∈ℝ be an arbitrary value. The system

is called an initial value problem. If a function x(t) satisfies both conditions, it is said to be a solution to the initial value problem.
Most often, we select t0 to be 0. After all, we have the freedom to select the origin of the time as we want.
Unfortunately, things are not as simple as they seem. In general, differential equations and initial value problems are tough to solve. Except for a few simple ones, we cannot find exact solutions. (And when I say we, I include every person on the planet.) In these cases, there are two things that we can do: either we construct approximate solutions via numeric methods or turn to qualitative methods that study the behavior of the solutions without actually finding them.
We’ll talk about both, but let’s turn to the qualitative methods first. As we’ll see, looking from a geometric perspective gives us a deep insight into how differential equations work.
13.3.3 A geometric interpretation of differential equations
Section titled “13.3.3 A geometric interpretation of differential equations”When finding analytic solutions is not feasible, we look for a qualitative understanding of the solutions, focusing on the local and long-term behavior instead of formulas.
Imagine that, given a differential equation

you are interested in a particular solution that assumes the value x∗ at time t0.
For instance, you could be studying the dynamics of a bacterial colony and want to provide a predictive model to fit your latest measurement x(t0) = x∗. In the short term, where will your solutions go?
We can immediately notice that if x(t0) = x∗ and f(x) = 0, then the constant function x(t) = x is a solution! These are called equilibrium solutions, and they are extremely important. So, let’s make a formal definition!
Definition 61. (Equilibrium solutions)
Let
x′(t) = f(x(t)) (13.4)
be a first-order homogeneous ODE, and let x∗∈ℝ be an arbitrary point. If f(x∗) = 0, then x∗ is called an equilibrium point of the equation x′ = f(x).
For equilibrium points, the constant function x(t) = x∗ is a solution of (13.4). This is called an equilibrium solution.
Think about our recurring example, the simplest ODE x′(t) = x(t). As mentioned, we can interpret this equation as a model of unrestricted population growth under ideal conditions. In that case, f(x) = x, and this is zero only for x = 0. Therefore, the constant x(t) = 0 function is a solution. This makes perfect sense: if a population has zero individuals, no change is going to happen in its size. In other words, the system is in equilibrium.
This is like a pendulum that stopped moving and reached its resting point at the bottom. However, pendulums have two equilibria: one at the top and one at the bottom. (Let’s suppose that the mass is held by a massless rod. Otherwise, it would collapse.) At the bottom, you can push the hanging mass all you want and it’ll return to rest. However, at the top, any small push would disrupt the equilibrium state, to which it would never return.
To shed light on this phenomenon, let’s look at another example: the famous logistic equation
x′(t) = x(t)(1 − x(t)). (13.5)
From a population dynamics perspective, if our favorite equation x′(t) = x(t) describes the unrestricted growth of a bacterial colony, the logistic equation models the population growth under a resource constraint. If we assume that 1 is the total capacity of our population, the growth becomes more difficult as the size approaches this limit. Thus, the population’s rate of change x′(t) can be modelled as x(t)(1 −x(t)), where the term 1 −x(t) slows down the process as the colony nears the sustain capacity.
We can write the logistic equation in the general form (13.3) by casting the role f(x) = x(1 −x). Do you recall Theorem 84 about the relation of derivatives and monotonicity? Translated to the differential equation x′ = f(x), this reveals the flow of our solutions! To be specific,

We can visualize this in the so-called phase portrait.

Figure 13.16: The flow of solutions for x′ = x(1 −x), visualized on the phase portrait. (The arrows represent the direction where the solutions for given initial values are headed.)
Thus, the monotonicity describes long-term behavior:
.png)
(13.6)
With a little bit of calculation (whose details are not essential for us), we can obtain that we can write the solutions as noindent

where c ∈ℝ is an arbitrary constant. For c = 1, this is the famous sigmoid function.
You can check by hand that these are indeed solutions. We can even plot them, as shown in Figure 13.17 below.

Figure 13.17: Solutions of the logistic differential equation x′ = x(1 −x)
As we can see in Figure 13.17, the monotonicity of the solutions are as we predicted in (13.6).
We can characterize the equilibria based on the long-term behavior of nearby solutions. (In the case of our logistic equation, the equilibria are 0 and 1.) This can be connected to the local behavior of f: if it decreases around the equilibrium x∗, it attracts the nearby solutions. On the other hand, if f increases around x∗, then the nearby solutions are repelled.
This gives rise to the concept of stable and unstable equilibria.
Definition 62. (Stable and unstable equilibria)
Let x′ = f(x) be a first-order homogeneous ordinary differential equation, and suppose that f is differentiable. Moreover, let x∗ be an equilibrium of the equation.
x∗ is called a stable equilibrium if there is a neighborhood (x∗−𝜀,x∗ + 𝜀) around x∗ such that for all x0 ∈ (x∗−𝜀,x∗ + 𝜀), the solution of the initial value problem

converges towards x∗. (That is, limt→∞x(t) = x∗ holds.)
If x∗ is not stable, it is called unstable.
In the case of the logistic ODE x′ = x(1 −x), x∗ = 1 is a stable and x∗ = 0 is an unstable equilibrium. This makes sense given its population dynamics interpretation: the equilibrium x∗ = 1 means that the population is at maximum capacity. If the size is slightly above or below the capacity 1, some specimens die due to starvation, or the colony reaches its constraints. On the other hand, no matter how small the population is, it won’t ever go extinct in this ideal model.
Recall how the derivatives characterize the monotonicity of differentiable functions by Theorem 84? With this, we have a simple tool that can help us decide whether a given equilibrium is stable or not.
Theorem 90.
Let x′ = f(x) be a first-order homogeneous ordinary differential equation, and suppose that f is differentiable. Moreover, let x∗ be an equilibrium point of the equation.
If f′(x)>0, then x is a stable equilibrium.
The concept of stable equilibrium is fundamental, even in the most general cases. At this point, it’s time to take a few steps backward and remind ourselves why we are here: to understand gradient descent. If stable equilibria remind you of a local minimum which a gradient descent process converges towards, it is not an accident. We are ready to see what’s behind the scenes.
13.3.4 A continuous version of gradient ascent
Section titled “13.3.4 A continuous version of gradient ascent”Now, let’s talk about maximizing a function F : ℝ →ℝ. Suppose that F is twice differentiable, and we denote its derivative by F′ = f. Luckily, the local maxima of F can be found with the help of its second derivative (Theorem 87) by looking for x∗ where f(x) = 0 and f′(x)>0.
Does this look familiar? If f(x) = 0 indeed holds, then x(t) = x is an equilibrium solution; and since f′(x∗)>0, it attracts the nearby solutions as well. This means that if x0 is drawn from the basin of attraction and x(t) is the solution of the initial value problem

(13.7)
then limt→∞x(t) = x∗. In other words, the solution converges towards x∗, a local maxima of F! This is gradient ascent in a continuous version.
We are happy, but there is an issue. We’ve talked about how hard solving differential equations are. For a general F, we have no prospects to actually find the solutions. Fortunately, we can approximate them.
13.3.5 Gradient ascent as a discretized differential equation
Section titled “13.3.5 Gradient ascent as a discretized differential equation”When studying differentiation in practice, we have seen that derivatives can be approximated numerically by the forward difference

where h>0 is a small step size. If x(t) is indeed the solution for the initial value problem (13.7), we are in luck! Using forward differences, we can take a small step from 0 and approximate x(h) by substituting the forward difference into the differential equation. To be precise, we have

from which

follows. By defining x0 and x1 by

we have x1 ≈x(h). If this looks like the first step of the gradient ascent (13.1) to you, you are on the right track. Using the forward difference once again, this time from the point x(h), we obtain

thus by defining x2 := x1 + hf(x1), we have x2 ≈x(2h). Notice that in x2, two kinds of approximation errors are accumulated: first the forward difference, then the approximation error of the previous step.
This motivates us to define the recursive sequence

(13.8)
which approximates x(nh) with xn, as this is implied by the very definition. This recursive sequence is the gradient ascent itself, and the small step h is the learning rate!
Check (13.1) if you don’t believe me. (13.8) is called the Euler method.
Without going into the details, if h is small enough and f “behaves properly,” the Euler method will converge to the equilibrium solution x∗. (Whatever proper behavior might mean.)
We only have one more step: to turn everything into gradient descent instead of ascent. This is extremely simple, as gradient descent is just applying gradient ascent to −f. Think about it: minimizing a function f is the same as maximizing its negative −f. And with that, we are done! The famous gradient descent is a consequence of dynamical systems converging towards their stable equilibria, and this is beautiful.
13.3.6 Gradient ascent in action
Section titled “13.3.6 Gradient ascent in action”To see gradient ascent (that is, the Euler method) in action, we should go back to our good old example: the logistic equation (13.5). So, suppose that we want to find the local maxima of the function

plotted in Figure 13.18.

Figure 13.18: The graph of F(x) =
x2 −
x3
First, we can use what we learned and find the maxima using the derivative f(x) = F′(x) = x(1 −x), concluding that there is a local maximum at x∗ = 1. (Don’t just take my word for it, check out Theorem 87 and work it out!)
Since f(x) = F′(x) = 0 and f′(x)>0, the point x is a stable equilibrium of the logistic equation

Thus, if the initial value x(0) = x0 is sufficiently close to x∗ = 1, the solution x(t) of the initial value problem

then limt→∞x(t) = x∗. (In fact, we can select any initial value x0 from the infinite interval (0,∞), and the convergence will hold). Upon discretization via the Euler method, we obtain the recursive sequence

This process is visualized by Figure 13.19.

Figure 13.19: Solving x′ = x(1 −x) via the Euler method. (For visualization purposes, the initial value was set at t0 = −5.)
We can even take the discrete solution provided by the Euler method, and plot it on the x −F(x) plane.

Figure 13.20: Mapping the Euler method on the x, F(x) plane
If you check Figure 13.20 out, you can see that this is the gradient ascent for F! If you consider that F′ = f and consider that the solution given by the Euler method is

(13.9)
you can notice that (13.9) is exactly how we defined gradient ascent.
Bookmark
13.4 Summary
Section titled “13.4 Summary”Finally, we’ve done it. Until this chapter, we haven’t been that close to machine learning, but now, we are right at the heart of it. Gradient descent is the number one algorithm to train neural networks. Yes, even state-of-the-art ones.
It all starts with calculus. To reach the heights of gradient descent, we studied the relations between monotonicity, local extrema, and the derivative. The pattern is simple: if f′(a)>0, then f is increasing, but if f′(a)>0, then f is decreasing around a. Speaking in terms of physics, if the speed is positive, the object is moving away, but if the speed is negative, the object is coming closer.
Based on this observation, we can deduce necessary and sufficient conditions to find local minima and maxima: if f′(a) = 0
- and if f′′(a)>0, then a is a local minimum,
- but if f′(a) = 0 and f′′(a)>0, then a is a local maximum.
So, finding the local extrema should be as simple as solving f′(a) = 0, right? In theory, no, because the case f′′(a) = 0 is undetermined. In practice, still no, because even finding f′ is hard for complex f-s, let alone solving f′(x) = 0.
However, there’s a way. We can take an iterative approach with gradient descent: if the learning rate h and starting point x0 are selected appropriately, the recursive sequence defined by

converges to a local minimum.
As always, when one problem is solved, a dozen others are created. For example, the gradient descent can fail to converge or get stuck in the local minimum instead of finding the global one. But that’s the least of our problems. The real issue is that we have to optimize functions of multiple variables in practice, often in the range of billions of parameters.
Before we move on to the study of multivariable calculus, there’s one more topic to go. I’ve hinted at integration, the mysterious “inverse differentiation” a couple of times. It’s time to see what it is and why it is indispensable to study advanced mathematics.
Bookmark
13.5 Problems
Section titled “13.5 Problems”Problem 1. Find the local minima and maxima of f(x) = sinx.
Problem 2. Use the second derivative test to find the local minima and maxima of f(x) = 2x3 + 5x2 + 4x + 6.
Problem 3. Let f : ℝ →ℝ be a differentiable function. The recursive sequence defined by

where δ0 = 0 and x0 is arbitrary, is called gradient descent with momentum. Implement it!