Partial derivatives, directional derivatives and the gradient
A first step into several variables: path-dependent limits, partial and directional derivatives, and the gradient as steepest ascent direction and normal to level sets. A specialist idea is emphasized: the gradient depends on the chosen inner product, and changing the norm changes steepest descent (the gradient sign with ℓ∞, one coordinate with ℓ1, and the preconditioned gradient with Mahalanobis).
After this lesson you can
Study limits and continuity in ℝⁿ and detect path-dependent limits.
Calculate partial and directional derivatives and relate them to the gradient.
Prove that the gradient is the steepest ascent direction and is orthogonal to level sets.
Derive steepest descent directions under ℓ1, ℓ∞ and Mahalanobis norms and relate them to signSGD, coordinate descent and preconditioning.
Implement a gradient checker with relative error and use it to catch errors in analytic derivatives.
Motivation: millions of parameters and one question
Training a model minimizes a function L:Rn→R with enormous n: about 1.2×108 parameters in GPT-1, 1.75×1011 in GPT-3. At each step the optimizer is at point w and must decide which way to move. It cannot see the whole surface; it can only ask how L changes if it moves slightly in a direction. This lesson answers three questions that seem naive but are not:
What do “near” and “continuous” mean in Rn? In one variable there are only two sides from which to approach a point. In the plane there are infinitely many paths, and a function may have a different limit along each.
How is slope measured in a direction? With partial derivatives (slopes along axes), directional derivatives (along any direction), and the gradient, summarizing them all when the function is sufficiently regular.
What is the steepest descent direction? The textbook answer is −∇L, the steepest descent direction. The specialist answer is “it depends on how step length is measured”: another norm gives the gradient sign (signSGD), a single coordinate (coordinate descent), or a preconditioned gradient. Half a dozen modern optimizers are this same idea with different norms.
A scalar function f:D⊆Rn→R assigns a number to each point x=(x1,…,xn) of its domain. A loss, energy, log likelihood and value function are all such functions. There are two ways to draw them when n=2.
The graph is the set {(x,f(x)):x∈D}⊆Rn+1. For n=2 it is a surface in space: the landscape with valleys and mountains.
Level sets live in the domain itself.
A topographic map is the standard example: each line joins points with the same altitude, and where lines crowd together the terrain is steep. Level sets are not always curves: level 0 of x2+y2 is a point, that of x2−y2 is two intersecting lines, and level 1 of a constant function equal to 1 is the whole plane. When Sc is truly a curve (or hypersurface) is specified by the regular level set theorem in lesson 10, and the condition will turn out to be ∇f=0, the object we are about to construct.
InteractiveSynchronized surface and contour map
Drag point p around the contour map. On the surface the two sections through p appear: y=p2 in orange and x=p1 in aqua, each with its tangent. Their slopes are the partial derivatives. On the map the blue arrow is the gradient, the sum of orange and aqua components. Notice three things: the gradient crosses the level curve of p at right angles (the readout measures that angle on the computed curve), is longer where contours crowd together, and distance to the next contour closely resembles Δc/∥∇f∥. Also try the curved Rosenbrock valley and logistic loss of a two-weight model on 12 synthetic points.
The figure previews almost everything this lesson proves. What follows is indispensable: doing it rigorously, knowing the assumptions behind each claim and the functions that break it when an assumption fails.
Limits and continuity in Rⁿ
The limit definition is the usual one, with Euclidean distance instead of absolute value. Rn with d(x,y)=∥x−y∥2 is a metric space, so everything seen there applies.
Does the choice of norm matter? No. In Rn all norms are equivalent: for any two norms there are constants 0<c≤C with c∥x∥a≤∥x∥b≤C∥x∥a for every x (for example, ∥x∥∞≤∥x∥2≤n∥x∥∞). The general proof uses compactness of the unit sphere. Thus a ball in one norm contains a ball in any other, and the definition gives the same limits. Norm choice will matter again, greatly, at the end of the lesson, but not here.
Calculation rules carry over unchanged (limits of sums, products and quotients with nonzero denominator; composition with continuous functions), and projections x↦xi are continuous because ∣xi−pi∣≤∥x−p∥. Thus polynomials in n variables are continuous throughout Rn and polynomial quotients are continuous where the denominator does not vanish. As always, problems lie where it does.
The path matters
Proof
Given ε>0, take δ from the definition. Since γ(t)→p, there is t0 with 0<∥γ(t)−p∥<δ for 0<t<t0 (positive because γ avoids p). For those t, ∣f(γ(t))−L∣<ε.
∎
The theorem only disproves existence of a limit. Every path you can think of giving the same value proves nothing, because there are too many paths. Two classic examples show this.
InteractivePath-dependent limits
Choose the function and path family, adjust slope m or coefficient k and press ‘Approach origin’. The upper graph is f along the path versus x, with the limit dashed; the lower graph shows the path limit versus the parameter. With xy/(x2+y2) the limit along lines spans all [−1/2,1/2]. With x2y/(x4+y2) the line curve is flat at 0: switch to parabolas and find the ridge on the surface. Notice the origin partial-derivative readout: they exist and are 0 for both functions, although neither is continuous there.
To prove a limit exists requires a bound depending only on distance to the point. A standard technique is to bound ∣f(x)−L∣ by a function of ∥x−p∥ tending to zero.
Two more traps. The iterated limitslimx→0limy→0f(x,y) decide nothing either: for xy/(x2+y2) they equal 0 in both orders and the limit does not exist. And separate continuity in each variable (x↦f(x,p2) and y↦f(p1,y) continuous) is much weaker than continuity: both functions in the figure have it at the origin.
Partial derivatives
The simplest way to differentiate a multivariable function is to freeze all but one variable and differentiate in one variable.
Geometrically, ∂x∂f(p) is the slope of the graph section by plane y=p2, the orange curve in the first figure, and ∂y∂f(p) that of the section by x=p1, aqua. To calculate them apply single-variable rules treating the other variables as constants.
The requirement that U be open guarantees p+tei is in the domain for small t on both sides. The important thing about the definition is how little it sees: only values of f on the n lines parallel to the axes passing through p. A function can do anything outside those lines without the partial derivatives noticing.
Directional derivative and gradient
Axes are not special. If a small step can be taken in any direction, we want the slope in any direction.
Partial derivatives are the case u=ei, and the definition gives D−uf(p)=−Duf(p) (replace t by −t). Unit u is required so the number is a slope per unit length; many texts define the same expression for any v, in which case Dcvf=cDvf.
We seek to describe infinitely many slopes with n numbers. The formula achieving this is Duf(p)=∇f(p)⋅u: slope in direction u is a combination of axis slopes with weights ui. But it cannot always hold because partials only see axes. An assumption is needed, and the most convenient is continuity of the partial derivatives.
Proof
We work in R2; in Rn the argument is the same with n terms. Write h=(h1,h2), with ∥h∥ small enough that the rectangle with vertices p and p+h lies in the neighborhood where partials exist. Go from p to p+h in two axis-parallel segments:
In the first bracket only the first variable changes. By the mean value theorem applied to s↦f(p1+s,p2+h2), differentiable on the interval because ∂1f exists there, it equals h1∂1f(a) for some a on the horizontal segment. Similarly, the second equals h2∂2f(b) with b on the vertical segment. Both points are at distance at most ∥h∥ from p (both segments are in the rectangle). Therefore
By Cauchy–Schwarz, the absolute value of the right side is at most ∥h∥(∣∂1f(a)−∂1f(p)∣2+∣∂2f(b)−∂2f(p)∣2)1/2. As h→0, a,b→p, and continuity of partials at p makes the parenthesis tend to 0. That is exactly o(∥h∥) in Landau notation.
For the second statement, take h=tu: (f(p+tu)−f(p))/t=∇f(p)⋅u+o(∣t∣)/t→∇f(p)⋅u.
∎
A function whose partial derivatives exist and are continuous throughout U is called class C1. The theorem’s first formula says f resembles, near p, affine function h↦f(p)+∇f(p)⋅h, with error becoming small faster than h. That property, taken as a definition, is differentiability, studied in the next lesson as the Fréchet derivative and extended to vector-valued functions. Here the case C1 suffices, covering all smooth losses in this course.
InteractiveThe directional derivative dial
unit direction u
0.55∇f
0.55(Duf)u as u rotates
tangent to level curve
Duf (magenta) and ∇f⋅u (blue dashed) versus angle of u
Function
f(x,y)=21(x2+3y2)+sin(x+y)
Duf (difference quotient)1.6277
∇f⋅u1.6277
∥∇f∥1.8857
Angle α between u and ∇f30.3°
Rotate unit direction u (red) around p. The magenta point is (Duf)u, calculated with a difference quotient without using the gradient. With the smooth function it traces a circle whose diameter is the segment from p to the tip of ∇f, because (∇f⋅u)u is the projection of ∇f onto the line of u and the angle at the projection is right (Thales). Below, Duf versus angle is a cosine wave of amplitude ∥∇f∥: maximum aligned with ∇f; zero tangent to the level curve; minimum at −∇f. Move p and switch to the nondifferentiable function: every directional derivative exists, but the curve is no longer a circle.
The theorem’s assumption is not a technicality. Function g(x,y)=x2y/(x2+y2), with g(0,0)=0, is continuous at the origin (∣g∣≤∣y∣) and homogeneous of degree 1, g(tu)=tg(u). Therefore Dug(0)=g(u)=u12u2 exists in every direction, and its partials are De1g=0 and De2g=0. If the formula held, every directional derivative would be ∇g(0)⋅u=0, and on the diagonal Dug=(1/2)3≈0.354. A function whose directional derivatives are not linear in u cannot be differentiable. This is what the dial shows: the magenta curve is not a circle.
Steepest ascent and level sets
With formula Duf=∇f⋅u, the motivating question is answered in one line.
Proof
By Cauchy–Schwarz, ∣∇f⋅u∣≤∥∇f∥∥u∥=∥∇f∥, with equality if and only if u is parallel to ∇f. The two parallel unit vectors are ±∇f/∥∇f∥ and give ±∥∇f∥. The last statement is the definition of orthogonality. Equivalently, if α is the angle between u and ∇f, Duf=∥∇f∥cosα, the dial’s cosine wave.
∎
This property names the gradient as steepest ascent direction: ∇f(p) points where f increases fastest, its length is that maximum rate and −∇f is the steepest descent direction. Gradient descent, wt+1=wt−η∇L(wt), follows it with steps proportional to slope.
The gradient is perpendicular to level sets
Proof
Let h(t)=γ(t)−p, which tends to 0 and satisfies h(t)/t→γ′(0). By the linear approximation theorem,
0=tf(γ(t))−f(p)=∇f(p)⋅th(t)+to(∥h(t)∥).
The last term tends to 0 because ∥h(t)∥/∣t∣ is bounded near t=0 (it converges to ∥γ′(0)∥). Taking limits, 0=∇f(p)⋅γ′(0).
∎
The proof is a special case of the chain rule, dtdf(γ(t))=∇f(γ(t))⋅γ′(t), seen in full in lesson 8. The result says ∇f(p) is perpendicular to every velocity of curves contained in Sc: it is a normal vector to the level set. In R2 this means the tangent line to the level curve at p is {x:∇f(p)⋅(x−p)=0}; in R3, the tangent plane to surface f=c is the plane with normal ∇f(p).
Contour density
The linear approximation theorem explains the first figure’s last observation. If ∇f(p)=0 and you advance distance s in direction ∇f, the value rises by s∥∇f(p)∥+o(s). To move from level c to c+Δc requires advancing
s≈∥∇f(p)∥Δc.
With contours equally spaced in value, their separation is inversely proportional to gradient length: crowded lines mean a large gradient. The figure’s “measured distance” readout solves f(p+s∇f)=csiguiente by bisection; the prediction is exact only in the limit Δc→0 and diverges when curvature of f at a contour’s scale is no longer negligible (try the Rosenbrock valley). This also explains why in a narrow valley the gradient points almost perpendicular to the valley floor, not toward the minimum: it is perpendicular to contours, and in a narrow valley contours are nearly parallel to the floor.
The gradient depends on the inner product
So far everything seemed absolute: the gradient is “the” steepest ascent direction. But there is a hidden choice. We measured step length with the Euclidean norm by requiring ∥u∥2=1, and wrote slope with the standard inner product, ∇f⋅u. Changing either changes the answer, and this is no curiosity: it is how to understand preconditioning, Adam, the natural gradient and recent optimizers.
What is intrinsic and what depends on the metric
What does not depend on a choice is the linear map v↦Dvf(p), assigning each displacement the first-order change of f. To write it as “inner product with a vector” one must choose an inner product. The standard one gives ∇f. With ⟨u,v⟩P=u⊤Pv, where P is positive definite, seek vector r with ⟨r,v⟩P=∇f⋅v for every v, that is, Pr=∇f:
gradPf=P−1∇f.
And the same Cauchy–Schwarz argument, now with ⟨⋅,⋅⟩P, says the steepest ascent direction among u with ∥u∥P=1 is normalized P−1∇f. Different inner product, different gradient, different direction.
Changing units changes gradient descent
This has a practical consequence. Suppose you optimize f(x,y) but the second variable is expressed in different units, y=sy′ (for example, meters versus kilometers, or a weight multiplied by an initialization constant). In new coordinates the function is f~(x,y′)=f(x,sy′) and, by the single-variable chain rule, ∂f~/∂y′=s∂f/∂y. A gradient descent step in (x,y′) moves y′ by −ηs∂yf, that is, moves y by
Δy=sΔy′=−ηs2∂y∂f.
The step in x does not change. Rescaling one coordinate by s multiplies its step by s2: this is gradient descent with P−1=diag(1,s2) in original coordinates. The “steepest descent direction” depends on units the problem does not fix, and a good optimizer should be as invariant to them as possible. This starts diagonal preconditioning.
Steepest descent under any norm
Now generalize in another direction: step length is measured with any norm ∥⋅∥, not necessarily from an inner product. The question “which unit-length direction decreases f most to first order?” becomes minimizing linear function d↦g⋅d, with g=∇f(p), over the unit ball.
By ball symmetry (d↦−d), min∥d∥≤1g⋅d=−∥g∥∗. A norm’s steepest descent direction is any minimizer d⋆, achieving slope −∥g∥∗. Geometrically, lines (hyperplanes) g⋅d=c are perpendicular to g in the Euclidean sense, and we seek the last one touching the ball: d⋆ is the contact point of the ball with half-plane g⋅d≤−∥g∥∗. For the four norms of interest the problem has a closed-form solution.
Proof
(1) This is the steepest ascent theorem. (2) You will prove it in a guided exercise. (3) For ∥d∥1≤1, ∣g⋅d∣≤∑j∣gj∣∣dj∣≤maxj∣gj∣∑j∣dj∣≤∥g∥∞, and d=−sign(gi)ei, which has norm 1, gives −∣gi∣=−∥g∥∞. (4) Write g⋅d=(P−1g)⊤Pd=⟨P−1g,d⟩P and apply Cauchy–Schwarz in inner product ⟨⋅,⋅⟩P: ∣g⋅d∣≤P−1gP∥d∥P, with P−1gP2=g⊤P−1PP−1g=g⊤P−1g. Equality is achieved with d proportional to −P−1g.
∎
The dual norms ℓ1↔ℓ∞ are the p=1, q=∞ case of Hölder duality between ℓp and ℓq with 1/p+1/q=1, seen with Lp spaces; the Mahalanobis norm is the multivariate Gaussian’s Mahalanobis distance.
InteractiveSteepest descent by norm
Unit ball and half-plane ∇f⋅d≤−∥∇f∥∗
unit ball ∥d∥≤1
steepest descent direction
line ∇f⋅d=−∥∇f∥∗
Steepest descent with exact line search on f=21x⊤Ax, κ(A)=12
selected norm
A=[3.75−4.76−4.769.25], eigenvalues 1 and 12.
Norm
d⋆=−∇f/∥∇f∥2,∥∇f∥∗=∥∇f∥2
∇f(1.30, 0.55)
d⋆(−0.921, −0.390)
Slope ∇f⋅d⋆=−∥∇f∥2−1.412
Angle between d⋆ and −∇f0.0°
Steps to f≤10−6f(x0)18
Drag the tip of ∇f and change norm. The shaded region is half-plane ∇f⋅d≤−∥∇f∥∗ and its boundary the lowest level line touching the unit ball; contact point is d⋆. With ℓ2 it is normalized −∇f; with ℓ∞ the ball is a square and contact is a corner, −sign(∇f); with ℓ1 it is a diamond and contact is a vertex on an axis (in ties, an entire side). With Mahalanobis edit P. In the second panel, steepest descent with exact line search on a quadratic with condition number 12: compare the zigzag of ℓ2 with the staircase of ℓ1 and with P=A, which arrives in one step.
From direction to step
An optimizer needs length as well as direction. The clean way to obtain both at once is to minimize the linear model plus a penalty for step length:
dpaso=dargmin[g⋅d+2λ∥d∥2]=λ∥g∥∗d⋆.
To see this, write d=cv with c=∥d∥≥0 and ∥v∥=1: the objective is c(g⋅v)+λc2/2≥−c∥g∥∗+λc2/2, with equality if v=d⋆, and the parabola in c has its minimum at c=∥g∥∗/λ. Since d⋆ already points downhill, the step is d⋆ stretched by ∥g∥∗/λ, without changing sign. With the four norms:
Norm
Step dpaso
Method
ℓ2
−λ1g
gradient descent with η=1/λ
ℓ∞
−λ∥g∥1sign(g)
sign descent (signSGD)
ℓ1
−λgiei, i∈argmaxj∣gj∣
coordinate descent with the Gauss–Southwell rule
∥⋅∥P
−λ1P−1g
preconditioned gradient; Newton if P is the Hessian
The figure’s second-panel trajectory shows why norm matters. With exact line search (optimal length along each direction), ℓ2 makes the classic zigzag between valley walls: each direction is perpendicular to a contour and does not point to the minimum. With P=A, the quadratic’s own matrix, P−1∇f(x)=A−1Ax=x points exactly to the minimum and arrives in one step: the metric that makes contours round makes the problem trivial. With P=diag(A), however, little is gained (or it loses, depending on the starting point), because valley axes are rotated 30° relative to coordinate axes and a diagonal matrix cannot capture that rotation.
Implementation from scratch: the gradient checker
Derivatives written by hand (or by a colleague, or an AI) have bugs. The standard way to catch them compares the analytic gradient with a numerical finite-difference approximation. For the comparison to be useful, understand two opposing error sources.
Truncation error. By single-variable Taylor along ei, the forward difference satisfies (f(x+hei)−f(x))/h=∂if(x)+2h∂i2f(x)+O(h2), while even terms cancel in the central difference:
Roundoff error. Each floating-point evaluation of f carries relative error of order machine epsilonεmaq (2.2×10−16 in float64, 1.2×10−7 in float32). Subtracting nearly equal values and dividing by h amplifies that error like εmaq∣f∣/h: catastrophic cancellation.
Adding them, central-difference error is of order E(h)=6h2∂i3f+εmaq∣f∣/h, minimized at h⋆∼εmaq1/3≈6×10−6 in float64 with error of order εmaq2/3≈10−11. The forward difference has h⋆∼εmaq1/2≈1.5×10−8 and error of order 10−8. Let us check.
[ ]Finite differences: error versus hBrowser
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.sin(x[0]) * np.exp(x[1]) + x[0] * x[1] ** 2
def grad_f(x):
return np.array([np.cos(x[0]) * np.exp(x[1]) + x[1] ** 2,
np.sin(x[0]) * np.exp(x[1]) + 2 * x[0] * x[1]])
def numerical_grad(f, x, h=1e-5):
"""Gradiente por diferencias centradas: 2n evaluaciones de f."""
x = np.asarray(x, dtype=float)
g = np.zeros_like(x)
for i in range(x.size):
e = np.zeros_like(x)
e.flat[i] = h
g.flat[i] = (f(x + e) - f(x - e)) / (2 * h)
return g
def forward_grad(f, x, h=1e-8):
"""Diferencias adelantadas: n + 1 evaluaciones, pero error O(h)."""
x = np.asarray(x, dtype=float)
fx = f(x)
g = np.zeros_like(x)
for i in range(x.size):
e = np.zeros_like(x)
e.flat[i] = h
g.flat[i] = (f(x + e) - fx) / h
return g
x0 = np.array([0.7, -0.3])
hs = np.logspace(-14, -1, 66)
err_c = np.array([np.linalg.norm(numerical_grad(f, x0, h) - grad_f(x0)) for h in hs])
err_f = np.array([np.linalg.norm(forward_grad(f, x0, h) - grad_f(x0)) for h in hs])
eps = np.finfo(float).eps
for nombre, err in (("adelantada", err_f), ("centrada", err_c)):
i = err.argmin()
print(f"{nombre:10s}: mejor h = {hs[i]:.1e}, error = {err[i]:.1e}")
print(f"predicción: sqrt(eps) = {np.sqrt(eps):.1e}, eps^(1/3) = {eps ** (1/3):.1e}")
for h in (1e-2, 1e-5, 1e-11):
print(f"h = {h:.0e}: error de la centrada = {np.linalg.norm(numerical_grad(f, x0, h) - grad_f(x0)):.1e}")
plt.loglog(hs, err_f, label="adelantada")
plt.loglog(hs, err_c, label="centrada")
plt.loglog(hs, hs ** 2 / 6, ":", color="gray", label="h²/6 (truncamiento)")
plt.loglog(hs, eps / hs, "--", color="gray", label="ε/h (redondeo)")
plt.xlabel("h"); plt.ylabel("‖error del gradiente‖"); plt.ylim(1e-13, 1e-1); plt.legend(); plt.show()
Both curves are V-shaped: truncation dominates on the right (slope 1 for forward and 2 for central on log-log axes) and roundoff on the left (slope −1). Minima fall where theory predicts, up to constants depending on f: h≈2.5×10−9 for forward (versus 1.5×10−8) and h≈6.3×10−6 for central (versus 6.1×10−6), with errors 1.3×10−8 and 3.3×10−12. Notice h=10−11, seemingly “more accurate,” gives central error 10−6: five orders of magnitude worse than h=10−5, giving 1.9×10−11. Smaller is not better.
Now the checker. Absolute error ∥ga−gn∥ cannot decide because it depends on gradient scale: 10−4 is enormous if the gradient is 10−5 and negligible if 103. Use the symmetric relative error
err(ga,gn)=∥ga∥+∥gn∥∥ga−gn∥∈[0,1],
which favors neither and equals 1 when one is zero and the other is not. We test it on logistic regression loss with λ∥w∥2 regularization, on seeded synthetic data, and with two deliberately wrong gradients: one omits regularization’s factor 2 and another flips one coordinate’s sign.
[ ]Gradient checker with relative errorBrowser
rng = np.random.default_rng(0)
n, d = 200, 5
X = rng.normal(size=(n, d)) # datos sintéticos
w_true = rng.normal(size=d)
y = np.where(X @ w_true + 0.5 * rng.normal(size=n) > 0, 1.0, -1.0)
lam = 0.1
def loss(w):
z = X @ w
return np.mean(np.logaddexp(0.0, -y * z)) + lam * w @ w # log(1 + e^{-y z}) sin desbordamiento
def sigmoid(t):
return 0.5 * (1 + np.tanh(0.5 * t)) # estable para |t| grande
def grad_loss(w):
z = X @ w
return -(X.T @ (y * sigmoid(-y * z))) / n + 2 * lam * w
def grad_bug_factor(w): # error plantado: falta el 2 de la regularización
z = X @ w
return -(X.T @ (y * sigmoid(-y * z))) / n + lam * w
def grad_bug_sign(w): # error plantado: signo cambiado en la última coordenada
g = grad_loss(w)
g[-1] = -g[-1]
return g
def grad_check(f, grad_f, x, h=1e-5):
ga = np.asarray(grad_f(x), dtype=float)
gn = numerical_grad(f, x, h)
den = np.linalg.norm(ga) + np.linalg.norm(gn)
return 0.0 if den == 0 else np.linalg.norm(ga - gn) / den
w0 = rng.normal(size=d)
for nombre, g in (("correcto", grad_loss), ("falta un 2", grad_bug_factor), ("signo", grad_bug_sign)):
print(f"{nombre:12s} error relativo = {grad_check(loss, g, w0):.1e}")
ga, gn = grad_bug_sign(w0), numerical_grad(loss, w0)
print("error relativo por coordenada (gradiente con el signo cambiado):")
print(np.round(np.abs(ga - gn) / (np.abs(ga) + np.abs(gn)), 8))
The correct gradient gives relative error 1.3×10−11, at the V’s minimum. The two planted bugs give 1.6×10−1 and 7.4×10−2: nine or ten orders of magnitude above, unambiguous. Coordinate breakdown locates the bug: all are 0 except the last, exactly 1 (if ga=−gn, the ratio is 2∣g∣/2∣g∣). As a guide, Stanford CS231n course notes suggest this scale for float64 relative error: above 10−2, probably a bug; between 10−4 and 10−2, cause for concern; below 10−4, acceptable if the function has nondifferentiable points (like ReLU), but high if smooth; below 10−7, good.
To finish the geometry, the familiar picture: contours of a two-weight logistic loss and their gradients. The cell also checks orthogonality numerically, measuring the angle between gradient and tangent to the level curve calculated by matplotlib.
[ ]Contours and gradient arrowsBrowser
X2 = np.array([[1.2, 0.8], [0.6, 1.5], [1.8, 0.2], [0.3, 0.4], [-0.4, 1.1], [-0.7, -0.5],
[-1.0, -0.6], [-0.5, -1.4], [-1.6, 0.1], [0.4, -0.9], [0.9, 0.7], [0.2, -0.3]])
y2 = np.array([1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1.0]) # los 12 puntos sintéticos de la primera figura
def L2(w1, w2):
Z = w1[..., None] * X2[:, 0] + w2[..., None] * X2[:, 1]
return np.mean(np.logaddexp(0.0, -y2 * Z), axis=-1)
def gradL2(w):
z = X2 @ w
return -(X2.T @ (y2 * sigmoid(-y2 * z))) / len(y2)
W1, W2 = np.meshgrid(np.linspace(-2.6, 3.4, 200), np.linspace(-1.2, 4.8, 200))
plt.contour(W1, W2, L2(W1, W2), levels=np.arange(0.5, 3.0, 0.1), colors="gray", linewidths=0.7)
Q1, Q2 = np.meshgrid(np.linspace(-2.2, 3.0, 12), np.linspace(-0.8, 4.4, 12))
G = np.array([gradL2(np.array([a, b])) for a, b in zip(Q1.ravel(), Q2.ravel())])
plt.quiver(Q1.ravel(), Q2.ravel(), -G[:, 0], -G[:, 1], color="C0", angles="xy")
plt.gca().set_aspect("equal"); plt.xlabel("w₁"); plt.ylabel("w₂"); plt.title("−∇L sobre los contornos")
plt.show()
# La curva de nivel L = 1, punto a punto: L es convexa y L(c) < 1, así que cada rayo desde c la corta una vez
from scipy.optimize import brentq
c = np.array([0.45, 1.75])
phis = np.linspace(0, 2 * np.pi, 720, endpoint=False)
dirs = np.stack([np.cos(phis), np.sin(phis)], axis=1)
radios = [brentq(lambda r: L2(*(c + r * u)) - 1.0, 0.0, 20.0, xtol=1e-12) for u in dirs]
curva = c + np.array(radios)[:, None] * dirs
tangentes = np.roll(curva, -1, axis=0) - np.roll(curva, 1, axis=0) # diferencias centradas a lo largo de la curva
gr = np.array([gradL2(p) for p in curva])
cosang = np.abs(np.sum(gr * tangentes, axis=1)) / (np.linalg.norm(gr, axis=1) * np.linalg.norm(tangentes, axis=1))
print(f"L = 1: ángulo entre ∇L y la tangente entre {np.degrees(np.arccos(cosang.max())):.4f}° y {np.degrees(np.arccos(cosang.min())):.4f}°")
The measured angle stays between 89.98° and 90°; the small deviation comes from approximating the tangent by the difference of two neighboring curve points, not from theory. Finally, a brute-force check of the dual norm table in R3: sample many directions, normalize them with each norm and find the one making g⋅d most negative.
[ ]Steepest descent by brute forceBrowser
g = np.array([3.0, -1.0, 2.0])
D = rng.normal(size=(400_000, 3))
for nombre, p, dual, d_cerrada in (
("l2 ", 2, np.linalg.norm(g, 2), -g / np.linalg.norm(g)),
("linf", np.inf, np.linalg.norm(g, 1), -np.sign(g)),
("l1 ", 1, np.linalg.norm(g, np.inf), -np.sign(g[0]) * np.eye(3)[0]),
):
Dn = D / np.linalg.norm(D, ord=p, axis=1, keepdims=True) # puntos de la esfera unidad de la norma
i = np.argmin(Dn @ g)
print(f"{nombre}: min g·d muestreado = {Dn[i] @ g:+.4f} -‖g‖_* = {-dual:+.4f} "
f"d* muestreada = {np.round(Dn[i], 2)} fórmula = {d_cerrada}")
P = np.array([[2.0, 0.5, 0.0], [0.5, 1.0, 0.0], [0.0, 0.0, 4.0]])
Lc = np.linalg.cholesky(P)
Dn = np.linalg.solve(Lc.T, (D / np.linalg.norm(D, axis=1, keepdims=True)).T).T # d con dᵀPd = 1
i = np.argmin(Dn @ g)
d_cerrada = -np.linalg.solve(P, g) / np.sqrt(g @ np.linalg.solve(P, g))
print(f"P : min g·d muestreado = {Dn[i] @ g:+.4f} -sqrt(gᵀP⁻¹g) = {-np.sqrt(g @ np.linalg.solve(P, g)):+.4f} "
f"ángulo entre la muestra y la fórmula = {np.degrees(np.arccos(np.clip(Dn[i] @ P @ d_cerrada, -1, 1))):.2f}°")
The sampled minimum remains slightly above the exact one, as expected (no sample lands exactly on the contact point), and directions match the closed formulas.
With libraries: SciPy
SciPy supplies both pieces: scipy.optimize.approx_fprime approximates the gradient and scipy.optimize.check_grad compares it with yours. Two documentation details matter. Both use forward differences with default step εmaq≈1.49×10−8, optimal for forward differences but giving error of order 10−8, not 10−11. And check_grad returns absolute error ∥ga−gn∥2, not relative error, so interpret the number against gradient size.
[ ]check_grad, approx_fprime and precisionBrowser
from scipy.optimize import check_grad, approx_fprime
print("check_grad (correcto): ", check_grad(loss, grad_loss, w0))
print("check_grad (falta un 2): ", check_grad(loss, grad_bug_factor, w0))
print("norma del gradiente: ", np.linalg.norm(grad_loss(w0)))
g_ap = approx_fprime(w0, loss)
print("approx_fprime, error relativo:", np.linalg.norm(g_ap - grad_loss(w0)) / np.linalg.norm(grad_loss(w0)))
# float32 frente a float64: la misma pérdida, el mismo gradiente analítico (en float64) y distintos h
X32, y32 = X.astype(np.float32), y.astype(np.float32)
def loss32(w):
w = np.asarray(w, dtype=np.float32)
z = X32 @ w
return np.mean(np.logaddexp(np.float32(0), -y32 * z)) + np.float32(lam) * (w @ w)
def numerical_grad32(f, x, h):
x = np.asarray(x, dtype=np.float32)
g = np.zeros_like(x)
for i in range(x.size):
e = np.zeros_like(x)
e[i] = h
g[i] = (f(x + e) - f(x - e)) / (2 * np.float32(h))
return g
ga = grad_loss(w0)
rel = lambda a, b: np.linalg.norm(a - b) / (np.linalg.norm(a) + np.linalg.norm(b))
print("\n h float64 float32")
for h in (1e-1, 1e-2, 1e-3, 1e-4, 1e-5):
print(f"{h:.0e} {rel(numerical_grad(loss, w0, h), ga):.1e} {rel(numerical_grad32(loss32, w0, h), ga):.1e}")
print("eps^(1/3) en float32:", np.finfo(np.float32).eps ** (1 / 3))
check_grad gives 1.8×10−8 with the correct gradient and 0.25 with the incorrect one, against a gradient norm of order 1: here absolute and relative error tell the same story, but not always. The final table is the one to remember. In float64, relative error falls with h like h2 until 10−11. In float32 the best result is order 10−5 near h=10−2 (the theoretical optimum is ε321/3≈5×10−3) and with h=10−5 error rises to about 6×10−3: the gradient is correct and yet the checker gives a number indicating an error in float64. Always gradient-check in float64.
Common mistakes
Exercises
NumericA directional derivative
Calculate the directional derivative of f(x,y)=x2y+exy at point (1,0) in direction (3,4).
NumericThe maximum slope
For f(x,y)=xey+y2, what is the largest value of Duf(2,0) among all unit vectors u?
QuizDoes the limit exist?
Let f(x,y)=x4+y2x2y for (x,y)=(0,0). Does lim(x,y)→(0,0)f(x,y) exist?
QuizWhat implies what
Let f:R2→R and p∈R2. Which statements hold for every f?
ProofThe steepest descent direction
Prove: Let f be class C1 near p with g=∇f(p)=0. Then u⋆=−g/∥g∥ is the unique unit vector minimizing Duf(p), and the minimum is −∥g∥.
0
By the linear approximation theorem, Duf(p)=g⋅u for every unit u.
Step 1 of 3. What lower bound on g⋅u do you obtain for ∥u∥=1?
ProofSteepest descent under ℓ∞
Prove: Let g∈Rn have all nonzero components. Among d with ∥d∥∞≤1, the minimum of g⋅d is −∥g∥1 and is attained only at d⋆=−sign(g).
0
Write g⋅d=∑igidi with ∣di∣≤1 for every i.
Step 1 of 3. What lower bound does each term gidi have?
NumericSlope with steps in a cube
At a point, ∇f=(3,−1,2). If steps are measured in norm ℓ∞, what is slope ∇f⋅d⋆ of the steepest descent direction?
NumericHow far does the direction turn?
With P=diag(1,4) and ∇f=(2,2), what angle in degrees does the steepest descent direction for norm ∥d∥P=d⊤Pd form with −∇f?
QuizChanging a parameter's units
You minimize f(x,y) by gradient descent with rate η. A colleague reparameterizes y=10y′ and performs gradient descent in variables (x,y′), with the same η. Translated back to the original variable, how much does y move in one step?
QuizReading a gradient check
The following situations use central differences and relative error ∥ga−gn∥/(∥ga∥+∥gn∥) on a smooth loss with gradient of size 1. Which readings are correct?
More than one answer may be correct.
CodeA coordinatewise checker
Implement grad_check(f, grad_f, x, h=1e-5), returning an array of the same shape as `x` with each coordinate's relative error, ∣ga−gn∣/(∣ga∣+∣gn∣), where ga is analytic gradient grad_f(x) and gn is the central-difference gradient with step h. If at a coordinate ∣ga∣+∣gn∣<10−12, its error is 0. x may be a vector or matrix (for example, layer weights), and the function must not modify the x it receives.
import numpy as np
def grad_check(f, grad_f, x, h=1e-5):
"""Error relativo por coordenada entre grad_f(x) y el gradiente por diferencias centradas."""
x = np.asarray(x, dtype=float)
ga = np.asarray(grad_f(x), dtype=float)
# tu código: gn, el gradiente numérico con la misma forma que x
err = np.zeros_like(x)
return err
Shift+Enter to run
Summary
Key idea
Directional derivative Duf is the slope of f in direction u; when f is C1 it equals ∇f⋅u, so the gradient is the steepest ascent direction and normal to level sets. But “steepest” depends on how steps are measured: with another norm, steepest descent points elsewhere.
A limit in Rn requires closeness in all directions at once. Two paths with different limits disprove existence; to prove it requires a bound in terms of ∥x−p∥. x2y/(x4+y2) gives 0 on every line and 1/2 on parabola y=x2.
Partial derivatives are derivatives of axis sections. They can exist without continuity because they see only n lines.
If partials exist near p and are continuous at p, f(p+h)=f(p)+∇f(p)⋅h+o(∥h∥) and Duf=∇f⋅u. Without that assumption the formula can fail, and even if it holds for every u, continuity does not follow.
By Cauchy–Schwarz, Duf=∥∇f∥cosα: maximum in direction ∇f, zero along level-set tangents, minimum at −∇f. Contour spacing is approximately Δc/∥∇f∥.
The gradient depends on the inner product (P−1∇f for ⟨⋅,⋅⟩P), and steepest descent depends on the norm: −g for ℓ2, −sign(g) for ℓ∞, one coordinate for ℓ1, −P−1g for Mahalanobis, with slope −∥g∥∗.
Gradient checking uses central differences, relative error and float64, with h≈10−5: optimal error is ∼ε2/3 and too small h spoils it with roundoff.