Partial derivatives, the gradient and directional derivatives
Before this lesson: lesson 01 (derivative, linear approximation, gradient descent in one variable) and linear algebra lesson 01 (vectors). You need the dot product , the length , and the angle between two vectors: . Time: about 60 minutes, plus the notebook.
Why this matters #
- Training. A network with weights has a loss . Gradient descent and all its variants (momentum, Adam) need the vector of partial derivatives . Backpropagation computes it at the cost of a few forward passes (lessons 04–06).
- Conditioning. In a stretched bowl the gradient direction is poor, and gradient descent needs many small steps. Momentum, Adam, normalization layers and preconditioning exist largely to fix this (optimization track).
- Gradients with respect to inputs. Saliency maps use of a class score to see which pixels matter. Adversarial examples move the input along the gradient of the loss.
- ML for science. In molecular dynamics, the force on the atoms is minus the gradient of the potential energy: . Machine-learned interatomic potentials predict and get the forces by differentiation.
1. Predict first #
2. The picture #
Two ways to draw . The graph is the surface over the -plane. The contour plot (level-set plot) draws, in the plane, the curves where has a fixed value: the level sets for a few values of . A hiking map shows a mountain this way. Where the contour lines (for equally spaced ) are close together, the function is steep. In ML, think of as a loss and of as two weights.
Slices. Fix . Then is a function of one variable: the curve where the plane cuts the surface. Its slope at is the partial derivative . Fixing instead gives the other slice and .
Move and , and rotate the figure. The orange slice keeps fixed; the slope of its dashed tangent is . The yellow slice keeps fixed; its slope is . The gradient combines both numbers into one arrow. Notice that it lies in the flat input plane , under the point, not on the surface.
The gradient on the contour map. Draw the arrow at a point of the contour plot. Two facts are visible at once: the arrow points uphill (to higher contour values), and it crosses the contour line at a right angle. Its length is the steepness: long where the contour lines are close.
Drag the point. The contour lines are computed from alone; the gradient is computed from the two partial derivatives. Still, the arrow always crosses the line at a right angle (the dashed tangent is the direction of the contour). Turn on the gradient field, and try the saddle, Rosenbrock and the logistic loss of a tiny classifier. The orange arrow is the direction that gradient descent takes.
On a contour plot with equally spaced levels, the contour lines are close together near point and far apart near point . What do you know about the gradients?
Between two neighbouring lines, changes by the same step . At this happens over a short distance, so the slope in the steepest direction, , is large. The gradient never points along a contour line; it is perpendicular to it.
3. Definitions and main results #
From now on, and . The pictures use and the names .
Partial derivatives #
Definition. The partial derivative of with respect to at is
where is the -th standard basis vector. In words: change only , keep all other variables fixed, and take the ordinary derivative. Other notations: , , .
To compute it, treat the other variables as constants. Examples:
For with respect to , the factor is a constant, so the derivative is . With respect to , the factor is the constant, so the derivative is .
An ML example. Logistic regression with two weights , one input and a label has the loss . Write (the margin). The chain rule of lesson 01, with and , gives
For , and : and , so the partial derivatives are and .
The gradient #
Definition. The gradient of at is the column vector of all partial derivatives:
It has the same shape as : it is a vector in the input space, not a point on the surface. In the logistic example, , a vector in the plane of the weights.
(Some books, for example Mathematics for Machine Learning, write the gradient as a row vector. This track uses columns. Lesson 03 explains how the two fit together.)
Linear approximation in several variables #
In one variable, . In variables the step is a vector, and the number becomes a dot product with the gradient.
Definition. is differentiable at if there is a vector with
Then : put , divide by and let ; the left side becomes and the right side becomes . So the gradient is the only possible . Lesson 03 extends this definition to functions with vector outputs.
Example. at , with and the step :
- exact: ;
- linear approximation: , that is, ;
- error: , of order .
Directional derivatives #
The partial derivatives measure the slope along the axes. Along any other direction :
Definition. The directional derivative of at along is
For a unit vector () it is the slope of when you walk in the direction . The partial derivatives are the special cases .
Theorem 1. If is differentiable at , then for every .
Proof.
- Put in the definition of differentiability: .
- Divide by : .
- For , , because . (For both sides are 0.)
So one vector, , gives the slope in every direction, by a dot product. Note that scales with : . To compare directions, use unit vectors.
Steepest ascent and steepest descent #
With the angle between and a unit vector , Theorem 1 gives
The slope is largest when , zero when , and smallest when .
Predict first: at which angle of does the curve on the right have its peak? Then drag the tip of around the circle. The slope follows a cosine. Its peak is at the direction of the gradient (blue line), its lowest value at the opposite direction (orange line), and it is 0 along the contour. The limit check computes with a small and agrees with . The dashed segment drops from the gradient tip onto the line of : the part of along is .
Theorem 2 (steepest ascent). Let be differentiable at with . Among all unit vectors , the directional derivative is largest for , with value , and smallest for , with value .
Proof.
- By Theorem 1, .
- The Cauchy–Schwarz inequality says , with equality exactly when is a multiple of . With : .
- Equality on the right needs with ; the length 1 forces . Then . In the same way the left equality needs .
So is the direction of steepest descent (measured with the usual length ), and gradient descent takes a step in this direction.
The gradient is perpendicular to the level set #
Let lie on the level set , and let be a smooth curve that stays in the level set, with . Its velocity is a tangent direction of the level set.
Theorem 3. If is differentiable at , then : the gradient is perpendicular to every tangent direction of the level set.
Proof. for all , so its derivative is 0. By the chain rule for a function along a curve, (lesson 04 proves the general chain rule). At this gives .
In words: walking along a contour line, does not change, so the slope in that direction is 0. By , a zero slope with means . In 2-D, if , the tangent direction is .
. What is the directional derivative at in the direction of ?
and . The value 22 uses without normalizing it to length 1. is the slope in the steepest direction, which is not . It is 0 only along the contour line.
Steepest descent zig-zags in a stretched bowl #
Take at the point . The minimum is at , in the direction . But points almost straight down. The angle between them is
The gradient is perpendicular to the contour ellipse, and an ellipse's normal does not point at its center. Gradient descent on this function multiplies each coordinate by its own factor per step: and (the one-variable rule of lesson 01, twice).
- Stability needs , so . The steep direction limits the step size.
- With such a small , the factor for is at least : the flat direction converges slowly.
- The best fixed step, , makes both factors . From it needs 71 steps to reach . On the round bowl with , one step is enough.
For a stretch (the function ) the best factor is . The number is the condition number of the problem. Lesson 03 shows how the Hessian measures it, and how Newton's method removes the zig-zag.
Use the presets, then the sliders. The path of gradient descent starts at the violet point. Its first step follows the blue arrow , which misses the dashed straight line to the minimum. With round bowl the path is straight. With stretched it zig-zags across the valley, and with η too large the -coordinate grows at every step. Compare the step counts.
Partial derivatives are not enough #
In one variable, "the derivative exists" is the whole story. In several variables, all partial derivatives can exist at a point where the function is not differentiable. Take
- On the -axis, ; on the -axis, . So .
- If were differentiable at 0, its gradient would be , and ; in particular as .
- But on the diagonal : . Points on the diagonal come arbitrarily close to 0, so is not even continuous at 0. It is not differentiable there.
On the line , : every line through 0 sees a different constant. The directional derivative along does not exist either: for , so has no limit. Choose xy/(x² + y²) in the first figure to see the surface.
Theorem 4 (a sufficient condition). If all partial derivatives of exist near and are continuous at , then is differentiable at . Such a function is called (continuously differentiable).
Proof for two variables
Let be small. Go from to in two moves, one variable at a time:
- Each bracket is a change of a one-variable function. By the mean value theorem, the first is for some between and , and the second is for some between and .
- Subtract . The rest is .
- , so is at most the sum of the two brackets in absolute value.
- As , the points and go to . The partial derivatives are continuous there, so both brackets go to 0. Hence .
For variables, change one coordinate at a time in the same way.
In ML practice, losses built from smooth pieces (linear maps, , , sigmoid, softmax) are , so their gradients behave as in this lesson. ReLU networks are differentiable everywhere except on a set of kinks of measure zero.
A function has . Which statement is true?
(with ) has both partial derivatives 0 at the origin, yet it is not continuous there, and its directional derivative along does not exist. Continuous partial derivatives () are a sufficient condition for differentiability. Even then, only gives a critical point, which may be a saddle.
Steepest descent in another norm
"Steepest" means: the most decrease per unit of step length. Theorem 2 measures length with the Euclidean norm. Other norms give other directions.
- A quadratic norm with symmetric positive definite: substitute , so that and . Cauchy–Schwarz gives the minimizer , that is, . The steepest direction is : a preconditioned gradient. For with (the Hessian, lesson 03), at : , exactly towards the minimum. This is Newton's direction.
- The norm ( for all ): the most decrease comes from , entry by entry. The fast gradient sign method (FGSM) for adversarial examples uses to increase the loss, and signSGD uses of the gradient.
- The norm (): the best moves only the coordinate with the largest . This is greedy coordinate descent.
Answers to section 1. (1) No. is away from the direction to the minimum, which is why gradient descent zig-zags here. (2) At a right angle (Theorem 3), whenever . (3) No. has both partial derivatives 0 at the origin but equals on the diagonal arbitrarily close to it.
4. Worked example #
Take at the point , where .
(a) Partial derivatives and gradient. With fixed, ; with fixed, . At :
(b) Linear approximation. For the step : . Exact: . The error is .
(c) A directional derivative. For the unit vector (check: ): . The angle to the gradient has , so .
(d) Steepest ascent and descent. Steepest ascent: , slope . Steepest descent: , slope . No unit direction has a slope outside ; the value of part (c) is inside, as it must be.
(e) The tangent of the level set. The level set through is , the curve . Its slope at is , so its tangent direction is . Check: . The gradient is perpendicular to the level set. ✓ (The 2-D rule gives the tangent , the same line.)
5. In code #
NumPy checks the worked example. The partial derivatives are checked one coordinate at a time with central differences; lesson 07 explains how to choose the step.
import numpy as np
f = lambda p: p[0]**2 * p[1] # f(x, y) = x^2 y
grad = lambda p: np.array([2 * p[0] * p[1], p[0]**2])
x = np.array([1.0, 2.0])
g = grad(x)
print(g, np.linalg.norm(g)) # [4. 1.] 4.123105625617661
# partial derivatives by central differences, one coordinate at a time
h = 1e-6
num = np.array([(f(x + h * e) - f(x - h * e)) / (2 * h) for e in np.eye(2)])
print(num) # [4. 1.] (up to about 1e-10)
# directional derivative: formula vs. the limit
v = np.array([3.0, 4.0]) / 5
t = 1e-6
print(g @ v, (f(x + t * v) - f(x)) / t) # 3.2 3.20000167963741
# linear approximation
dx = np.array([0.1, -0.1])
print(f(x + dx), f(x) + g @ dx) # 2.2990000000000004 2.3
# the tangent of the level set is perpendicular to the gradient
tau = np.array([-g[1], g[0]]) / np.linalg.norm(g)
print(g @ tau, f(x + 1e-3 * tau) - f(x)) # 0.0 -3.5288e-07 (order t^2, not t)
The last line shows Theorem 3 numerically: a step of along the tangent changes by about , not , because the first-order change is 0.
6. Where it shows up #
- Gradient descent and its variants. Every update in deep learning, or a modified version of it, uses the vector of partial derivatives. The zig-zag of section 3 is the reason for momentum (which averages out the oscillation) and for per-coordinate step sizes as in Adam (optimization track).
- Loss-landscape pictures. Li et al. (2018) visualize a network's loss as a function of two variables, along two random directions , and draw its contour plot: the same kind of picture as in this lesson.
- Saliency maps and adversarial examples. of a class score with respect to the input pixels shows which pixels change the score fastest (Simonyan et al., 2013). FGSM (Goodfellow et al., 2015) adds to an image: the steepest-ascent step in the norm (see the folded block in section 3).
- Forces from energies. Machine-learned interatomic potentials predict an energy from the atom positions and compute the forces as . This guarantees a conservative force field (energy is conserved in simulations).
- Physics-informed losses. A neural field enters a PDE residual through its partial derivatives and , computed by automatic differentiation (lesson 05).
7. Common mistakes #
- Holding the wrong variable fixed. , not (the factor stays) and not (that is ).
- Drawing the gradient on the surface. lives in the input space , under the surface. For it has 2 entries, not 3.
- Forgetting to normalize the direction. is the slope per unit step only when . For you get times the slope.
- " points at the minimum." Only in round bowls. In general it is perpendicular to the contour line, which can be far from the direction to the minimum ( in our example).
- "The gradient is tangent to the contour line." It is perpendicular to it. The tangent is the direction of zero slope.
- "All partial derivatives exist, so is differentiable." False: at 0. You need, for example, continuous partial derivatives.
8. Check yourself #
- Compute for at .
Answer
, and . So . - For at : what is the largest slope over all unit directions, and in which direction?
Answer
, so the largest slope is , in the direction : straight away from the origin. - At a point, . Give a unit vector along which does not change to first order.
Answer
Any unit with : (or its negative). This is the tangent direction of the level set. - Gradient descent on : for which step sizes does it converge, and which gives the fastest worst-case rate?
Answer
The factors are and . Both have absolute value below 1 when . The best balances : , so , with factor for . - Show that , , takes the value on the line (). What does this say about continuity at 0?
Answer
, independent of . Different lines give different values ( for , for ), all arbitrarily close to 0. So has no limit at 0 and is not continuous there. - For a differentiable , why is linear in ? Give a test that can show a function is not differentiable at a point.
Answer
, a dot product with a fixed vector, so it is linear in . Test: if some directional derivative does not exist, or if for some , then is not differentiable there.
Define the partial derivative at .
: the derivative in with all other variables fixed.
What is the gradient of , and what shape does it have?
The column vector of partial derivatives , a vector in the input space (same shape as ).
Write the directional derivative in terms of the gradient.
(for differentiable ); for a unit it equals .
Which unit direction gives the steepest descent, and what is the slope there?
, with slope . Proof: Cauchy–Schwarz.
Why is the gradient perpendicular to the level set?
Along a curve in the level set, is constant, so : the slope along every tangent direction is 0.
Compute at .
.
Give a function with both partial derivatives at 0 that is not differentiable there.
, : both partials are 0, but on the diagonal, so is not even continuous at 0.
What condition on the partial derivatives guarantees differentiability?
They exist near and are continuous at ( is ).
Why does gradient descent zig-zag on ?
is perpendicular to the elongated contour ellipses, not aimed at the center; the steep -direction forces , so the flat -direction converges slowly.
9. Interview angle #
- "Why does the gradient point in the direction of steepest ascent?" — , then Cauchy–Schwarz: for unit , with equality only at .
- "Why is the gradient perpendicular to the contour lines?" — Along a contour line is constant, so the directional derivative along it is 0, so .
- "Why is gradient descent slow on ill-conditioned problems, and what helps?" — The step size is limited by the steepest direction, so flat directions move slowly; the rate is about per step. Momentum, preconditioning (Adam's diagonal scaling) or Newton-type methods help.
- "If all partial derivatives exist, is the function differentiable?" — No; give . Continuous partials are enough.
- "What is the gradient of ?" — .
10. Practice #
The notebook for this lesson runs in Colab. It has five short exercises, each with a check cell and a folded solution:
- Write the gradients of , and by hand, and check them with central differences.
- Compute a directional derivative two ways: with and with the limit.
- Draw contours and a gradient field with
quiver, and verify numerically that the gradient is perpendicular to the level set. - Run gradient descent on and count the steps to as grows.
- Show numerically that has different limits along different lines through 0.
11. Watch and read #
- Deisenroth, Faisal and Ong, Mathematics for Machine Learning (free PDF): §5.2 (partial differentiation and gradients). Note that the book writes the gradient as a row vector.
- OpenStax, Calculus Volume 3 (free): chapter 4 (functions of several variables, partial derivatives, directional derivatives and the gradient).
- MIT 18.02, Multivariable Calculus, Fall 2007 (OpenCourseWare): lecture notes and problem sets for partial derivatives and gradients.
- Li et al., Visualizing the loss landscape of neural nets (NeurIPS 2018): two-variable slices of real losses.
- Goodfellow, Shlens and Szegedy, Explaining and harnessing adversarial examples (ICLR 2015): the fast gradient sign method.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.