Type at least 2 letters. Enter opens the first result, Esc closes.

    Calculus for ML · Lesson 2 · Derivatives in one and many variables

    Partial derivatives, the gradient and directional derivatives

    Beginner 60 min 4 interactive figures 5 videos Colab notebook

    Before this lesson: lesson 01 (derivative, linear approximation, gradient descent in one variable) and linear algebra lesson 01 (vectors). You need the dot product u⊤v=∑iuiviu^\top v = \sum_i u_i v_i, the length ∥v∥=v⊤v\|v\| = \sqrt{v^\top v}, and the angle θ\theta between two vectors: u⊤v=∥u∥ ∥v∥cos⁡θu^\top v = \|u\|\,\|v\|\cos\theta. Time: about 60 minutes, plus the notebook.


    Why this matters #

    • Training. A network with nn weights has a loss L:Rn→RL:\R^n \to \R. Gradient descent and all its variants (momentum, Adam) need the vector of nn partial derivatives ∇L\nabla L. 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 ∇x\nabla_x 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: F=−∇RE(R)F = -\nabla_R E(R). Machine-learned interatomic potentials predict EE and get the forces by differentiation.

    1. Predict first #

    2. The picture #

    Two ways to draw f(x,y)f(x, y). The graph is the surface z=f(x,y)z = f(x, y) over the (x,y)(x, y)-plane. The contour plot (level-set plot) draws, in the plane, the curves where ff has a fixed value: the level sets {(x,y):f(x,y)=c}\{(x, y) : f(x, y) = c\} for a few values of cc. A hiking map shows a mountain this way. Where the contour lines (for equally spaced cc) are close together, the function is steep. In ML, think of ff as a loss and of (x,y)(x, y) as two weights.

    Slices. Fix y=y0y = y_0. Then x↦f(x,y0)x \mapsto f(x, y_0) is a function of one variable: the curve where the plane y=y0y = y_0 cuts the surface. Its slope at x0x_0 is the partial derivative ∂f/∂x\partial f/\partial x. Fixing x=x0x = x_0 instead gives the other slice and ∂f/∂y\partial f/\partial y.

    Interactive figure: loading…

    Move x0x_0 and y0y_0, and rotate the figure. The orange slice keeps y=y0y = y_0 fixed; the slope of its dashed tangent is ∂f/∂x\partial f/\partial x. The yellow slice keeps x=x0x = x_0 fixed; its slope is ∂f/∂y\partial f/\partial y. The gradient combines both numbers into one arrow. Notice that it lies in the flat input plane z=0z = 0, under the point, not on the surface.

    The gradient on the contour map. Draw the arrow ∇f=(∂f/∂x,∂f/∂y)\nabla f = (\partial f/\partial x, \partial f/\partial y) 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.

    Interactive figure: loading…

    Drag the point. The contour lines are computed from ff 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 −∇f-\nabla f is the direction that gradient descent takes.

    Quick check

    On a contour plot with equally spaced levels, the contour lines are close together near point AA and far apart near point BB. What do you know about the gradients?

    3. Definitions and main results #

    From now on, f:Rn→Rf:\R^n \to \R and x=(x1,…,xn)x = (x_1, \dots, x_n). The pictures use n=2n = 2 and the names x,yx, y.

    Partial derivatives #

    Definition. The partial derivative of ff with respect to xix_i at xx is

    ∂f∂xi(x)=lim⁡t→0f(x+tei)−f(x)t,\frac{\partial f}{\partial x_i}(x) = \lim_{t \to 0} \frac{f(x + t e_i) - f(x)}{t},

    where eie_i is the ii-th standard basis vector. In words: change only xix_i, keep all other variables fixed, and take the ordinary derivative. Other notations: ∂if\partial_i f, ∂xif\partial_{x_i} f, fxif_{x_i}.

    To compute it, treat the other variables as constants. Examples:

    f(x,y)f(x, y) ∂f/∂x\partial f/\partial x ∂f/∂y\partial f/\partial y
    x2+10y2x^2 + 10y^2 2x2x 20y20y
    x2yx^2 y 2xy2xy x2x^2
    exye^{xy} y exyy\,e^{xy} x exyx\,e^{xy}

    For x2yx^2 y with respect to xx, the factor yy is a constant, so the derivative is y⋅2xy \cdot 2x. With respect to yy, the factor x2x^2 is the constant, so the derivative is x2x^2.

    An ML example. Logistic regression with two weights w=(w1,w2)w = (w_1, w_2), one input a=(a1,a2)a = (a_1, a_2) and a label y∈{−1,+1}y \in \{-1, +1\} has the loss L(w)=log⁡(1+e−y w⊤a)L(w) = \log\big(1 + e^{-y\,w^\top a}\big). Write m=y w⊤am = y\,w^\top a (the margin). The chain rule of lesson 01, with ddmlog⁡(1+e−m)=−σ(−m)\frac{d}{dm}\log(1 + e^{-m}) = -\sigma(-m) and ∂m/∂wj=y aj\partial m/\partial w_j = y\,a_j, gives

    ∂L∂wj=−σ(−m) y aj.\frac{\partial L}{\partial w_j} = -\sigma(-m)\, y\, a_j .

    For a=(1,2)a = (1, 2), y=+1y = +1 and w=(0,0)w = (0, 0): m=0m = 0 and σ(0)=1/2\sigma(0) = 1/2, so the partial derivatives are −1/2-1/2 and −1-1.

    The gradient #

    Definition. The gradient of ff at xx is the column vector of all partial derivatives:

    ∇f(x)=(∂f/∂x1(x)⋮∂f/∂xn(x))∈Rn.\nabla f(x) = \begin{pmatrix} \partial f/\partial x_1 (x) \\ \vdots \\ \partial f/\partial x_n (x) \end{pmatrix} \in \R^n .

    It has the same shape as xx: it is a vector in the input space, not a point on the surface. In the logistic example, ∇L(0,0)=(−1/2,−1)⊤\nabla L(0, 0) = (-1/2, -1)^\top, 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, f(x+h)=f(x)+f′(x)h+o(h)f(x + h) = f(x) + f'(x)h + o(h). In nn variables the step hh is a vector, and the number f′(x)f'(x) becomes a dot product with the gradient.

    Definition. ff is differentiable at xx if there is a vector g∈Rng \in \R^n with

    f(x+h)=f(x)+g⊤h+r(h),r(h)∥h∥→0  as h→0.f(x + h) = f(x) + g^\top h + r(h), \qquad \frac{r(h)}{\|h\|} \to 0 \ \text{ as } h \to 0 .

    Then g=∇f(x)g = \nabla f(x): put h=teih = t e_i, divide by tt and let t→0t \to 0; the left side becomes ∂f/∂xi\partial f/\partial x_i and the right side becomes gig_i. So the gradient is the only possible gg. Lesson 03 extends this definition to functions with vector outputs.

    Example. f(x,y)=x2+10y2f(x, y) = x^2 + 10y^2 at (1,1)(1, 1), with ∇f=(2,20)\nabla f = (2, 20) and the step h=(0.1,−0.05)h = (0.1, -0.05):

    • exact: f(1.1,0.95)=1.21+9.025=10.235f(1.1, 0.95) = 1.21 + 9.025 = 10.235;
    • linear approximation: f(1,1)+∇f⊤h=11+2⋅0.1+20⋅(−0.05)f(1, 1) + \nabla f^\top h = 11 + 2 \cdot 0.1 + 20 \cdot (-0.05), that is, 11+0.2−1=10.211 + 0.2 - 1 = 10.2;
    • error: 0.035=h12+10h220.035 = h_1^2 + 10h_2^2, of order ∥h∥2\|h\|^2.

    Directional derivatives #

    The partial derivatives measure the slope along the axes. Along any other direction v∈Rnv \in \R^n:

    Definition. The directional derivative of ff at xx along vv is

    Dvf(x)=lim⁡t→0f(x+tv)−f(x)t.D_v f(x) = \lim_{t \to 0} \frac{f(x + t v) - f(x)}{t}.

    For a unit vector vv (∥v∥=1\|v\| = 1) it is the slope of ff when you walk in the direction vv. The partial derivatives are the special cases v=eiv = e_i.

    Theorem 1. If ff is differentiable at xx, then Dvf(x)=∇f(x)⊤vD_v f(x) = \nabla f(x)^\top v for every vv.

    Proof.

    1. Put h=tvh = tv in the definition of differentiability: f(x+tv)−f(x)=t ∇f(x)⊤v+r(tv)f(x + tv) - f(x) = t\,\nabla f(x)^\top v + r(tv).
    2. Divide by t≠0t \ne 0: f(x+tv)−f(x)t=∇f(x)⊤v+r(tv)t\dfrac{f(x + tv) - f(x)}{t} = \nabla f(x)^\top v + \dfrac{r(tv)}{t}.
    3. For v≠0v \ne 0, ∣r(tv)t∣=∣r(tv)∣∥tv∥ ∥v∥→0\left|\dfrac{r(tv)}{t}\right| = \dfrac{|r(tv)|}{\|tv\|}\,\|v\| \to 0, because tv→0tv \to 0. (For v=0v = 0 both sides are 0.) ■\blacksquare

    So one vector, ∇f\nabla f, gives the slope in every direction, by a dot product. Note that DvfD_v f scales with vv: D2vf=2DvfD_{2v} f = 2 D_v f. To compare directions, use unit vectors.

    Steepest ascent and steepest descent #

    With θ\theta the angle between ∇f(x)\nabla f(x) and a unit vector vv, Theorem 1 gives

    Dvf(x)=∇f(x)⊤v=∥∇f(x)∥cos⁡θ.D_v f(x) = \nabla f(x)^\top v = \|\nabla f(x)\| \cos\theta .

    The slope is largest when cos⁡θ=1\cos\theta = 1, zero when θ=90°\theta = 90°, and smallest when cos⁡θ=−1\cos\theta = -1.

    Interactive figure: loading…

    Predict first: at which angle of vv does the curve on the right have its peak? Then drag the tip of vv around the circle. The slope DvfD_v f follows a cosine. Its peak ∥∇f∥\|\nabla f\| is at the direction of the gradient (blue line), its lowest value −∥∇f∥-\|\nabla f\| at the opposite direction (orange line), and it is 0 along the contour. The limit check computes (f(x+tv)−f(x))/t\big(f(x + tv) - f(x)\big)/t with a small tt and agrees with ∇f⊤v\nabla f^\top v. The dashed segment drops from the gradient tip onto the line of vv: the part of ∇f\nabla f along vv is ∥∇f∥cos⁡θ\|\nabla f\|\cos\theta.

    Theorem 2 (steepest ascent). Let ff be differentiable at xx with g=∇f(x)≠0g = \nabla f(x) \ne 0. Among all unit vectors vv, the directional derivative Dvf(x)D_v f(x) is largest for v=g/∥g∥v = g/\|g\|, with value ∥g∥\|g\|, and smallest for v=−g/∥g∥v = -g/\|g\|, with value −∥g∥-\|g\|.

    Proof.

    1. By Theorem 1, Dvf(x)=g⊤vD_v f(x) = g^\top v.
    2. The Cauchy–Schwarz inequality says ∣g⊤v∣≤∥g∥ ∥v∥|g^\top v| \le \|g\|\,\|v\|, with equality exactly when vv is a multiple of gg. With ∥v∥=1\|v\| = 1: −∥g∥≤g⊤v≤∥g∥-\|g\| \le g^\top v \le \|g\|.
    3. Equality on the right needs v=cgv = c g with c>0c > 0; the length 1 forces v=g/∥g∥v = g/\|g\|. Then g⊤v=∥g∥g^\top v = \|g\|. In the same way the left equality needs v=−g/∥g∥v = -g/\|g\|. ■\blacksquare

    So −∇f-\nabla f is the direction of steepest descent (measured with the usual length ∥v∥\|v\|), and gradient descent xk+1=xk−η ∇f(xk)x_{k+1} = x_k - \eta\,\nabla f(x_k) takes a step in this direction.

    The gradient is perpendicular to the level set #

    Let xx lie on the level set {f=c}\{f = c\}, and let γ(t)\gamma(t) be a smooth curve that stays in the level set, with γ(0)=x\gamma(0) = x. Its velocity γ′(0)\gamma'(0) is a tangent direction of the level set.

    Theorem 3. If ff is differentiable at xx, then ∇f(x)⊤γ′(0)=0\nabla f(x)^\top \gamma'(0) = 0: the gradient is perpendicular to every tangent direction of the level set.

    Proof. f(γ(t))=cf(\gamma(t)) = c for all tt, so its derivative is 0. By the chain rule for a function along a curve, ddtf(γ(t))=∇f(γ(t))⊤γ′(t)\frac{d}{dt} f(\gamma(t)) = \nabla f(\gamma(t))^\top \gamma'(t) (lesson 04 proves the general chain rule). At t=0t = 0 this gives ∇f(x)⊤γ′(0)=0\nabla f(x)^\top \gamma'(0) = 0. ■\blacksquare

    In words: walking along a contour line, ff does not change, so the slope in that direction is 0. By Dvf=∥∇f∥cos⁡θD_v f = \|\nabla f\|\cos\theta, a zero slope with ∇f≠0\nabla f \ne 0 means θ=90°\theta = 90°. In 2-D, if ∇f=(a,b)≠0\nabla f = (a, b) \ne 0, the tangent direction is (−b,a)(-b, a).

    Quick check

    f(x,y)=x2+10y2f(x, y) = x^2 + 10y^2. What is the directional derivative at (1,1)(1, 1) in the direction of v=(1,1)/2v = (1, 1)/\sqrt2?

    Steepest descent zig-zags in a stretched bowl #

    Take f(x,y)=x2+10y2f(x, y) = x^2 + 10y^2 at the point (1,1)(1, 1). The minimum is at (0,0)(0, 0), in the direction (−1,−1)(-1, -1). But −∇f(1,1)=(−2,−20)-\nabla f(1, 1) = (-2, -20) points almost straight down. The angle between them is

    cos⁡ϕ=(−2,−20)⊤(−1,−1)∥(−2,−20)∥ ∥(−1,−1)∥=22404 2≈0.774,ϕ≈39.3°.\cos\phi = \frac{(-2, -20)^\top(-1, -1)}{\|(-2, -20)\|\,\|(-1, -1)\|} = \frac{22}{\sqrt{404}\,\sqrt2} \approx 0.774, \qquad \phi \approx 39.3° .

    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: x←(1−2η) xx \leftarrow (1 - 2\eta)\,x and y←(1−20η) yy \leftarrow (1 - 20\eta)\,y (the one-variable rule of lesson 01, twice).

    • Stability needs ∣1−20η∣<1|1 - 20\eta| < 1, so η<0.1\eta < 0.1. The steep direction yy limits the step size.
    • With such a small η\eta, the factor for xx is at least 1−0.2=0.81 - 0.2 = 0.8: the flat direction converges slowly.
    • The best fixed step, η=1/11\eta = 1/11, makes both factors ±9/11≈0.818\pm 9/11 \approx 0.818. From (1,1)(1, 1) it needs 71 steps to reach ∥x∥<10−6\|x\| < 10^{-6}. On the round bowl x2+y2x^2 + y^2 with η=0.5\eta = 0.5, one step is enough.

    For a stretch κ\kappa (the function x2+κy2x^2 + \kappa y^2) the best factor is (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1). The number κ\kappa is the condition number of the problem. Lesson 03 shows how the Hessian measures it, and how Newton's method removes the zig-zag.

    Interactive figure: loading…

    Use the presets, then the sliders. The path of gradient descent starts at the violet point. Its first step follows the blue arrow −∇f-\nabla f, 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 yy-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

    f(x,y)=xyx2+y2  for (x,y)≠(0,0),f(0,0)=0.f(x, y) = \frac{xy}{x^2 + y^2} \ \text{ for } (x, y) \ne (0, 0), \qquad f(0, 0) = 0 .
    1. On the xx-axis, f(x,0)=0f(x, 0) = 0; on the yy-axis, f(0,y)=0f(0, y) = 0. So ∂f/∂x(0,0)=∂f/∂y(0,0)=0\partial f/\partial x(0, 0) = \partial f/\partial y(0, 0) = 0.
    2. If ff were differentiable at 0, its gradient would be (0,0)(0, 0), and f(h)=o(∥h∥)f(h) = o(\|h\|); in particular f(h)→0f(h) \to 0 as h→0h \to 0.
    3. But on the diagonal y=x≠0y = x \ne 0: f(x,x)=x2/(2x2)=1/2f(x, x) = x^2/(2x^2) = 1/2. Points on the diagonal come arbitrarily close to 0, so ff is not even continuous at 0. It is not differentiable there.

    On the line y=mxy = mx, f=m/(1+m2)f = m/(1 + m^2): every line through 0 sees a different constant. The directional derivative along (1,1)/2(1, 1)/\sqrt2 does not exist either: f(tv)=1/2f(tv) = 1/2 for t≠0t \ne 0, so (f(tv)−f(0))/t=1/(2t)\big(f(tv) - f(0)\big)/t = 1/(2t) 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 ff exist near xx and are continuous at xx, then ff is differentiable at xx. Such a function is called C1C^1 (continuously differentiable).

    Proof for two variables

    Let h=(h1,h2)h = (h_1, h_2) be small. Go from (x,y)(x, y) to (x+h1,y+h2)(x + h_1, y + h_2) in two moves, one variable at a time:

    f(x+h1,y+h2)−f(x,y)=[f(x+h1,y+h2)−f(x,y+h2)]+[f(x,y+h2)−f(x,y)].f(x + h_1, y + h_2) - f(x, y) = \big[f(x + h_1, y + h_2) - f(x, y + h_2)\big] + \big[f(x, y + h_2) - f(x, y)\big].
    1. Each bracket is a change of a one-variable function. By the mean value theorem, the first is ∂xf(ξ,y+h2) h1\partial_x f(\xi, y + h_2)\, h_1 for some ξ\xi between xx and x+h1x + h_1, and the second is ∂yf(x,ζ) h2\partial_y f(x, \zeta)\, h_2 for some ζ\zeta between yy and y+h2y + h_2.
    2. Subtract ∇f(x,y)⊤h\nabla f(x, y)^\top h. The rest is r(h)=[∂xf(ξ,y+h2)−∂xf(x,y)]h1+[∂yf(x,ζ)−∂yf(x,y)]h2r(h) = \big[\partial_x f(\xi, y + h_2) - \partial_x f(x, y)\big]h_1 + \big[\partial_y f(x, \zeta) - \partial_y f(x, y)\big]h_2.
    3. ∣h1∣,∣h2∣≤∥h∥|h_1|, |h_2| \le \|h\|, so ∣r(h)∣/∥h∥|r(h)|/\|h\| is at most the sum of the two brackets in absolute value.
    4. As h→0h \to 0, the points (ξ,y+h2)(\xi, y + h_2) and (x,ζ)(x, \zeta) go to (x,y)(x, y). The partial derivatives are continuous there, so both brackets go to 0. Hence r(h)/∥h∥→0r(h)/\|h\| \to 0. ■\blacksquare

    For nn variables, change one coordinate at a time in the same way.

    In ML practice, losses built from smooth pieces (linear maps, exp⁡\exp, log⁡\log, sigmoid, softmax) are C1C^1, so their gradients behave as in this lesson. ReLU networks are differentiable everywhere except on a set of kinks of measure zero.

    Quick check

    A function f:R2→Rf:\R^2 \to \R has ∂f/∂x(0)=∂f/∂y(0)=0\partial f/\partial x(0) = \partial f/\partial y(0) = 0. Which statement is true?

    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 ∥v∥A=v⊤Av\|v\|_A = \sqrt{v^\top A v} with AA symmetric positive definite: substitute u=A1/2vu = A^{1/2}v, so that ∥u∥=1\|u\| = 1 and g⊤v=(A−1/2g)⊤ug^\top v = (A^{-1/2}g)^\top u. Cauchy–Schwarz gives the minimizer u=−A−1/2g/∥A−1/2g∥u = -A^{-1/2}g/\|A^{-1/2}g\|, that is, v=−A−1g/g⊤A−1gv = -A^{-1}g/\sqrt{g^\top A^{-1} g}. The steepest direction is −A−1∇f-A^{-1}\nabla f: a preconditioned gradient. For x2+10y2x^2 + 10y^2 with A=diag⁡(2,20)A = \operatorname{diag}(2, 20) (the Hessian, lesson 03), at (1,1)(1, 1): −A−1(2,20)=(−1,−1)-A^{-1}(2, 20) = (-1, -1), exactly towards the minimum. This is Newton's direction.
    • The ℓ∞\ell_\infty norm (∣vi∣≤1|v_i| \le 1 for all ii): the most decrease comes from v=−sign⁡(g)v = -\operatorname{sign}(g), entry by entry. The fast gradient sign method (FGSM) for adversarial examples uses +εsign⁡(∇xL)+\varepsilon\operatorname{sign}(\nabla_x L) to increase the loss, and signSGD uses −sign⁡-\operatorname{sign} of the gradient.
    • The ℓ1\ell_1 norm (∑i∣vi∣≤1\sum_i |v_i| \le 1): the best vv moves only the coordinate with the largest ∣gi∣|g_i|. This is greedy coordinate descent.

    Answers to section 1. (1) No. −∇f(1,1)=(−2,−20)-\nabla f(1, 1) = (-2, -20) is 39.3°39.3° away from the direction (−1,−1)(-1, -1) to the minimum, which is why gradient descent zig-zags here. (2) At a right angle (Theorem 3), whenever ∇f≠0\nabla f \ne 0. (3) No. xy/(x2+y2)xy/(x^2 + y^2) has both partial derivatives 0 at the origin but equals 1/21/2 on the diagonal arbitrarily close to it.

    4. Worked example #

    Take f(x,y)=x2yf(x, y) = x^2 y at the point p=(1,2)p = (1, 2), where f(p)=2f(p) = 2.

    (a) Partial derivatives and gradient. With yy fixed, ∂f/∂x=2xy\partial f/\partial x = 2xy; with xx fixed, ∂f/∂y=x2\partial f/\partial y = x^2. At pp:

    ∇f(1,2)=(2⋅1⋅212)=(41),∥∇f∥=17≈4.123.\nabla f(1, 2) = \begin{pmatrix} 2 \cdot 1 \cdot 2 \\ 1^2 \end{pmatrix} = \begin{pmatrix} 4 \\ 1 \end{pmatrix}, \qquad \|\nabla f\| = \sqrt{17} \approx 4.123 .

    (b) Linear approximation. For the step h=(0.1,−0.1)h = (0.1, -0.1): f(p+h)≈2+4⋅0.1+1⋅(−0.1)=2.3f(p + h) \approx 2 + 4 \cdot 0.1 + 1 \cdot (-0.1) = 2.3. Exact: f(1.1,1.9)=1.21⋅1.9=2.299f(1.1, 1.9) = 1.21 \cdot 1.9 = 2.299. The error is −0.001-0.001.

    (c) A directional derivative. For the unit vector v=(3,4)/5v = (3, 4)/5 (check: 9+16/5=1\sqrt{9 + 16}/5 = 1): Dvf=(4⋅3+1⋅4)/5=16/5=3.2D_v f = (4 \cdot 3 + 1 \cdot 4)/5 = 16/5 = 3.2. The angle to the gradient has cos⁡θ=3.2/17≈0.776\cos\theta = 3.2/\sqrt{17} \approx 0.776, so θ≈39.1°\theta \approx 39.1°.

    (d) Steepest ascent and descent. Steepest ascent: v=(4,1)/17v = (4, 1)/\sqrt{17}, slope 17≈4.123\sqrt{17} \approx 4.123. Steepest descent: v=−(4,1)/17v = -(4, 1)/\sqrt{17}, slope −4.123-4.123. No unit direction has a slope outside [−4.123,4.123][-4.123, 4.123]; the value 3.23.2 of part (c) is inside, as it must be.

    (e) The tangent of the level set. The level set through pp is x2y=2x^2 y = 2, the curve y=2/x2y = 2/x^2. Its slope at x=1x = 1 is dy/dx=−4/x3=−4dy/dx = -4/x^3 = -4, so its tangent direction is (1,−4)(1, -4). Check: (4,1)⊤(1,−4)=4−4=0(4, 1)^\top(1, -4) = 4 - 4 = 0. The gradient is perpendicular to the level set. ✓ (The 2-D rule gives the tangent (−b,a)=(−1,4)(-b, a) = (-1, 4), 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 10−310^{-3} along the tangent changes ff by about 10−710^{-7}, not 10−310^{-3}, because the first-order change ∇f⊤τ\nabla f^\top \tau is 0.

    6. Where it shows up #

    • Gradient descent and its variants. Every update in deep learning, w←w−η ∇L(w)w \leftarrow w - \eta\,\nabla L(w) 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, f(α,β)=L(w∗+α δ+β η)f(\alpha, \beta) = L(w^* + \alpha\,\delta + \beta\,\eta) along two random directions δ,η\delta, \eta, and draw its contour plot: the same kind of picture as in this lesson.
    • Saliency maps and adversarial examples. ∇x\nabla_x 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 εsign⁡(∇xL)\varepsilon\operatorname{sign}(\nabla_x L) to an image: the steepest-ascent step in the ℓ∞\ell_\infty norm (see the folded block in section 3).
    • Forces from energies. Machine-learned interatomic potentials predict an energy E(R)E(R) from the atom positions RR and compute the forces as F=−∇REF = -\nabla_R E. This guarantees a conservative force field (energy is conserved in simulations).
    • Physics-informed losses. A neural field uθ(x,t)u_\theta(x, t) enters a PDE residual through its partial derivatives ∂u/∂t\partial u/\partial t and ∂u/∂x\partial u/\partial x, computed by automatic differentiation (lesson 05).

    7. Common mistakes #

    • Holding the wrong variable fixed. ∂(x2y)/∂x=2xy\partial(x^2 y)/\partial x = 2xy, not 2x2x (the factor yy stays) and not x2x^2 (that is ∂/∂y\partial/\partial y).
    • Drawing the gradient on the surface. ∇f(x)\nabla f(x) lives in the input space Rn\R^n, under the surface. For f:R2→Rf:\R^2 \to \R it has 2 entries, not 3.
    • Forgetting to normalize the direction. Dvf=∇f⊤vD_v f = \nabla f^\top v is the slope per unit step only when ∥v∥=1\|v\| = 1. For v=(1,1)v = (1, 1) you get 2\sqrt2 times the slope.
    • "−∇f-\nabla f 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 (39.3°39.3° 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 ff is differentiable." False: xy/(x2+y2)xy/(x^2 + y^2) at 0. You need, for example, continuous partial derivatives.

    8. Check yourself #

    1. Compute ∇f\nabla f for f(x,y)=exy+x3f(x, y) = e^{xy} + x^3 at (1,0)(1, 0).
      Answer∂xf=y exy+3x2=0+3=3\partial_x f = y\,e^{xy} + 3x^2 = 0 + 3 = 3, and ∂yf=x exy=1\partial_y f = x\,e^{xy} = 1. So ∇f(1,0)=(3,1)⊤\nabla f(1, 0) = (3, 1)^\top.
    2. For f(x,y)=x2+y2f(x, y) = x^2 + y^2 at (3,4)(3, 4): what is the largest slope over all unit directions, and in which direction?
      Answer∇f=(6,8)\nabla f = (6, 8), so the largest slope is ∥∇f∥=10\|\nabla f\| = 10, in the direction (6,8)/10=(0.6,0.8)(6, 8)/10 = (0.6, 0.8): straight away from the origin.
    3. At a point, ∇f=(2,−1)\nabla f = (2, -1). Give a unit vector along which ff does not change to first order.
      AnswerAny unit vv with 2v1−v2=02v_1 - v_2 = 0: v=(1,2)/5v = (1, 2)/\sqrt5 (or its negative). This is the tangent direction of the level set.
    4. Gradient descent on f=x2+4y2f = x^2 + 4y^2: for which step sizes η\eta does it converge, and which η\eta gives the fastest worst-case rate?
      AnswerThe factors are 1−2η1 - 2\eta and 1−8η1 - 8\eta. Both have absolute value below 1 when 0<η<1/40 < \eta < 1/4. The best η\eta balances ∣1−2η∣=∣1−8η∣|1 - 2\eta| = |1 - 8\eta|: 1−2η=8η−11 - 2\eta = 8\eta - 1, so η=0.2\eta = 0.2, with factor 0.6=(κ−1)/(κ+1)0.6 = (\kappa - 1)/(\kappa + 1) for κ=4\kappa = 4.
    5. Show that f(x,y)=xy/(x2+y2)f(x, y) = xy/(x^2 + y^2), f(0,0)=0f(0, 0) = 0, takes the value m/(1+m2)m/(1 + m^2) on the line y=mxy = mx (x≠0x \ne 0). What does this say about continuity at 0?
      Answerf(x,mx)=mx2/(x2+m2x2)=m/(1+m2)f(x, mx) = m x^2/(x^2 + m^2x^2) = m/(1 + m^2), independent of xx. Different lines give different values (00 for m=0m = 0, 1/21/2 for m=1m = 1), all arbitrarily close to 0. So ff has no limit at 0 and is not continuous there.
    6. For a differentiable ff, why is Dvf(x)D_v f(x) linear in vv? Give a test that can show a function is not differentiable at a point.
      AnswerDvf=∇f⊤vD_v f = \nabla f^\top v, a dot product with a fixed vector, so it is linear in vv. Test: if some directional derivative does not exist, or if Du+vf≠Duf+DvfD_{u+v} f \ne D_u f + D_v f for some u,vu, v, then ff is not differentiable there.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Define the partial derivative ∂f/∂xi\partial f/\partial x_i at xx.

    2. What is the gradient of f:Rn→Rf:\R^n \to \R, and what shape does it have?

    3. Write the directional derivative in terms of the gradient.

    4. Which unit direction gives the steepest descent, and what is the slope there?

    5. Why is the gradient perpendicular to the level set?

    6. Compute ∇(x2y)\nabla(x^2 y) at (1,2)(1, 2).

    7. Give a function with both partial derivatives at 0 that is not differentiable there.

    8. What condition on the partial derivatives guarantees differentiability?

    9. Why does gradient descent zig-zag on x2+10y2x^2 + 10y^2?

    Open the review →

    9. Interview angle #

    • "Why does the gradient point in the direction of steepest ascent?" — Dvf=∇f⊤vD_v f = \nabla f^\top v, then Cauchy–Schwarz: ∇f⊤v≤∥∇f∥\nabla f^\top v \le \|\nabla f\| for unit vv, with equality only at v=∇f/∥∇f∥v = \nabla f/\|\nabla f\|.
    • "Why is the gradient perpendicular to the contour lines?" — Along a contour line ff is constant, so the directional derivative along it is 0, so ∇f⊤v=0\nabla f^\top v = 0.
    • "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 (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1) per step. Momentum, preconditioning (Adam's diagonal scaling) or Newton-type methods help.
    • "If all partial derivatives exist, is the function differentiable?" — No; give xy/(x2+y2)xy/(x^2 + y^2). Continuous partials are enough.
    • "What is the gradient of L(w)=log⁡(1+e−y w⊤a)L(w) = \log(1 + e^{-y\,w^\top a})?" — −σ(−y w⊤a) y a-\sigma(-y\,w^\top a)\,y\,a.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five short exercises, each with a check cell and a folded solution:

    1. Write the gradients of x2+10y2x^2 + 10y^2, x2yx^2 y and exye^{xy} by hand, and check them with central differences.
    2. Compute a directional derivative two ways: with ∇f⊤v\nabla f^\top v and with the limit.
    3. Draw contours and a gradient field with quiver, and verify numerically that the gradient is perpendicular to the level set.
    4. Run gradient descent on x2+κy2x^2 + \kappa y^2 and count the steps to 10−610^{-6} as κ\kappa grows.
    5. Show numerically that xy/(x2+y2)xy/(x^2 + y^2) has different limits along different lines through 0.

    11. Watch and read #

    Partial derivatives as slopes of slices; compare with the surface figure.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Why the gradient is perpendicular to contour lines and long where they are close.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The directional derivative as a dot product with the gradient.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The same argument as Theorem 2, told with pictures.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A full lecture: the gradient, its perpendicularity to level sets, and directional derivatives.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play