Suppose a model predicts three delivery times and its average squared error is too high. You can change either of its two weights. Which change should you try, and how much improvement should you expect? A derivative gives a local prediction of what happens when an input moves. The gradient collects that information for a scalar loss, while a Jacobian keeps a separate record for each model output. Learning to distinguish those objects makes tensor shapes easier to read and helps you debug training code when the loss behaves unexpectedly.
You will derive a slope from a limit, compute a gradient and a directional derivative, read a Jacobian as a local linear map, and check a batch loss gradient with finite differences. You need the dot products and matrix shapes from Vectors, Matrices, and Operations and the residual definition from Linear Systems and Least Squares. The PCA lesson supplies another example of an objective measured by squared reconstruction error.
A derivative is the limiting slope between nearby evaluations#
Let f map a real input x to a real output. At a nonzero step h, the finite slope between x and x+h is
The numerator is an output difference. The denominator is an input difference, so the slope has units of output per unit of input. If f measures a predicted duration in minutes and x is distance in kilometers, the derivative is measured in minutes per kilometer. The sign tells you which way the output initially moves when you increase the input.
Take f(x)=x² at x=3. Expanding gives f(3+h)=9+6h+h². Subtract f(3)=9 and divide by a nonzero h to get 6+h. For h=0.1 this gives 6.1, and for h=−0.1 it gives 5.9. Both sides tend toward 6, so the derivative f′(3) equals 6. The denominator never has to be zero. The limit asks whether every sufficiently small step, from either side, leads to a slope arbitrarily close to the same number.
You can read the result as a local prediction. Increasing x by 0.01 predicts an output increase of 6×0.01=0.06. The exact increase is 0.0601. The leftover h² shrinks faster than h as h tends to zero. At a much larger h, it can matter. Checking a derivative and predicting a large change therefore require different evidence. For a scalar function differentiable at x, the precise local statement is that f(x+h) equals f(x)+f′(x)h plus a remainder whose ratio to |h| tends to zero.
If the two slopes disagree in the limit, the two-sided derivative does not exist. At x=0 the absolute-value function yields −1 for negative h and +1 for positive h. Its centered finite difference is zero for every h because the two function values coincide. A finite numerical result can hide a kink. Use one-sided probes at a branch boundary and inspect the operation’s specified derivative convention if a framework is involved.
A gradient combines partial derivatives of one scalar#
Suppose a scalar loss L depends on a vector w of D trainable parameters. A partial derivative with respect to coordinate j changes only wⱼ. Write eⱼ for the coordinate vector with a one in position j and zeros elsewhere. The partial derivative ∂L/∂wⱼ is the limit of [L(w+h·eⱼ)−L(w)]/h as h tends to zero. Collect all D partials in the column gradient g=∇L(w). In NumPy the same coordinates are stored in a one-dimensional array of shape [D]. The scalar loss itself has shape [].
If L is differentiable at w, you can predict the change from a small vector displacement Δw by the dot product gᵀΔw. The approximation error shrinks faster than the length of Δw near zero. Near a smooth point this combines all coordinate effects at once. The existence of coordinate partials at a point by itself does not establish that a single linear approximation works along every direction. The functions used in the main examples are polynomials and satisfy that differentiability assumption.
When you compute partial derivatives by hand, reuse scalar rules. The derivative of a sum is the sum of derivatives. The derivative of a product ab is a′b+ab′. An outer square contributes a factor of twice its input, and a change to the square's input scales that contribution. The next lesson develops the composition rule systematically. Keep the differentiation target explicit even in a short derivation. With L(a,b)=a²b+3b, holding b fixed gives ∂L/∂a=2ab, while holding a fixed gives ∂L/∂b=a²+3. At a=2 and b=−1 the gradient entries are −4 and 7. A small positive increment to a alone decreases loss to first order, while a positive increment to b alone increases it.
Translate a direction into a loss slope
Let u be a Euclidean unit vector and t a signed distance traveled along it. The points w+tu form a one-dimensional path. Substitute Δw=tu into the local approximation. The slope of loss along the path at t=0 is gᵀu. For a nonunit vector v the same product gᵀv is the derivative per unit of the path's parameter t, so changing v's length changes the slope per unit t. Normalize a proposed direction before comparing per-distance rates.
In the example g=(−4,7). For u=(1,0), the slope equals −4. For u=(0,1), it equals 7. A direction proportional to (7,4) gives slope zero because −4×7+7×4=0. That means the linear term vanishes. Higher-order terms can still change the result. The direction of steepest local increase per unit Euclidean length is g/‖g‖₂ when g is nonzero, and the reverse direction gives steepest decrease. This follows from the dot product bound |gᵀu|≤‖g‖₂ when ‖u‖₂=1, with equality for aligned directions. How you measure input distance matters. Changing parameter units rescales the coordinate representation and can change which unit move qualifies as steepest.
A Jacobian predicts change in multiple outputs#
When F takes D inputs and returns M outputs, take one gradient per scalar output. Put the transpose of each gradient into the corresponding row of J, the Jacobian. Its entry J[i,j] is ∂Fᵢ/∂wⱼ. The array shape is [M,D], with output coordinates on rows and input coordinates on columns. A whole column answers what happens to all outputs when you perturb one input. A row answers how one output responds to every input. The scalar-output Jacobian would contain a single row gᵀ. Some references use row notation for the scalar gradient, so use shapes and the intended multiplication to disambiguate it.
Take F(a,b)=(a+2b, ab, a²−b)ᵀ. At (2,3), the first row is (1,2). The second is (b,a)=(3,2). The third is (2a,−1)=(4,−1). Now increase a by 0.01 and decrease b by 0.02. Multiply J by the displacement column (0.01,−0.02)ᵀ to obtain the predicted output change (−0.03,−0.01,0.06)ᵀ. The true changes are (−0.03,−0.0102,0.0601)ᵀ. The first output is affine and its first-order prediction is exact for every step. The remaining differences come from the products of increments that the linear approximation drops.
This is the same shape rule as the matrix transformation in the eigenvalues lesson. A matrix A maps a column of D inputs to an output column of M coordinates. For F(w)=Aw+b, the Jacobian equals A everywhere, and the bias b does not affect output changes. A nonlinear function has a different local matrix as you move through input space. A dense Jacobian can also be costly. A map from 4,096 real inputs to 32,000 outputs requires 131,072,000 entries, or 500 MiB for the entries alone in float32. If your question concerns a single perturbation, the product JΔw is what you need. The next lesson will explain how automatic differentiation can compute products without allocating that matrix.
Work through a batch loss by hand#
Use three normalized targets with two numeric features per observation and no bias parameter. The batch input X has shape [B,D] with B=3 rows and D=2 features. Predictions p=Xw and labels y both have shape [B]. Let r=p−y be the signed prediction residual. The training objective L(w)=rᵀr/(2B) is half the mean squared error. Its factor of one half makes the derivative of each squared residual contribute a residual without an extra factor of two. The loss units are the square of the target units, or dimensionless for these normalized values.
The first prediction is 1×1+2×(−1)=−1. The next is 3×1+(−1)×(−1)=4. The third is 2×1+0×(−1)=2. Subtract the labels to get r=(−1,1,1)ᵀ and compute L=(1+1+1)/6=0.5.
Diagram key and text version
- Entry
- Process
- Outcome
- Weights [2] → Predictions [3]
- Predictions [3] → Residuals [3]
- Residuals [3] → Gradient [2]
Perturb only the first weight by h. The three residuals change by h, 3h, and 2h because those are the entries in the first column of X multiplied by h. Expanding one squared residual gives (rᵢ+hX[i,1])² = rᵢ²+2hrᵢX[i,1]+h²X[i,1]². Subtract the original loss, divide by h, and let h tend to zero. The term proportional to h vanishes. The remaining first partial is the average of the residuals weighted by the first column, giving [−1×1+1×3+1×2]/3=4/3. Repeat with the second column to get [−1×2+1×(−1)+1×0]/3=−1. For arbitrary B and D, the same derivation gives
Check the shape. Xᵀ has D rows and B columns, so multiplying by a B-coordinate residual returns one entry per weight. The Jacobian of the unaggregated predictions with respect to w is X. The gradient of the scalar batch loss instead combines those output sensitivities using the signed residuals. Switching from mean to sum reduction multiplies this gradient by B. Switching from half mean squared error to ordinary mean squared error multiplies it by two. Both changes matter to update magnitude.
At the initial weights, g=(4/3,−1)ᵀ, so a small move opposite the gradient decreases loss. With step coefficient η=0.1 in w_new=w−ηg, the updated weights are (13/15,−9/10). The residuals become (−14/15,1/2,11/15)ᵀ. Their squared sum divided by six yields 1493/5400, about 0.2765. The first-order prediction would have been 0.5−0.1×25/9≈0.2222. The difference is the positive quadratic contribution from the finite move. Trying η=1 on the same batch increases the loss even though the step points in the same direction. A derivative describes the neighborhood of its evaluation point. An update must also pick a suitable step size.
Verify the derivative using independent evaluations#
For a scalar loss, a centered difference along direction u evaluates the loss twice.
For each coordinate, set u=eⱼ. Repeating this for D parameters costs 2D evaluations, so start with a small fixture. If F returns multiple outputs, the operation returns a vector approximation to Ju. Coordinate probes recover the Jacobian column by column. In a large model, checking several fixed directions costs two evaluations per direction. A single direction can miss an erroneous gradient component perpendicular to it.
import numpy as np
X = np.array([[1., 2.], [3., -1.], [2., 0.]])
y = np.array([0., 3., 1.])
w = np.array([1., -1.])
def loss(weights):
r = X @ weights - y
return (r @ r) / (2 * len(y))
analytic = X.T @ (X @ w - y) / len(y)
h = 1e-5
numeric = np.array([
(loss(w + h * e) - loss(w - h * e)) / (2 * h)
for e in np.eye(w.size)
])
np.testing.assert_allclose(numeric, analytic, rtol=1e-7, atol=1e-8)
The downloadable Python lab runs these checks, verifies the nonlinear Jacobian, and prints a step sweep for a nonquadratic function. Run python3 08-derivatives-gradients.py with NumPy installed. Its optional --torch comparison computes the same loss gradient with torch.func.grad and the same vector-valued Jacobian with torch.func.jacrev. The NumPy path implements the checks from forward evaluations. PyTorch's gradcheck notes explain how it compares numerical and automatic derivatives.
A central difference cancels the first-order step error found in a forward difference when the function is sufficiently smooth. Its approximation error still competes with floating-point rounding. For f(x)=x³ at x=2, expanding f(2+h)−f(2−h) gives 24h+2h³, so the exact centered quotient is 12+h². On a computer, reducing h eventually makes the two function values nearly indistinguishable. A wider step can also cross a discontinuity, a kink, or a mask boundary. Compare a range of sensible steps. For a smooth float64 fixture with coordinates near one, try 10⁻³, 10⁻⁵, and 10⁻⁷ and look for agreement across adjacent choices. Scale the step to the coordinates you perturb when their magnitudes differ.
Use shape and scale checks before debugging an optimizer#
| Symptom | First check | What the result tells you |
|---|---|---|
| Every derivative is much larger than expected | Compare the loss reduction and the exact denominator | A mean versus sum mismatch rescales all entries |
| Numerical and analytic values disagree at one branch boundary | Compare one-sided probes | The smooth derivative may fail to exist there |
| A finite difference is zero for tiny steps | Inspect dtype and test a larger h | The perturbed values may round to the same number |
| One sample’s perturbation changes another sample’s prediction | Inspect operations that aggregate across the batch | A batch-coupled operation invalidates independent per-example Jacobians |
| The checked gradient passes but the update raises loss | Evaluate the loss at multiple step sizes on the same batch | Step size or curvature can explain the increase |
Keep the exact data, labels, model mode, and random draws fixed across perturbations. Otherwise a dropout mask or a new batch can change the loss more than the parameter perturbation does. Check with a small float64 example first and use tolerances with both absolute and relative terms. Near zero, an absolute tolerance is especially important. Match the analytic and numerical objectives exactly. A broadcast mismatch such as predictions with shape [B,1] against labels with shape [B] can produce a residual array of shape [B,B], which compares each prediction with every label. Assert intended shapes before interpreting a gradient check.
In a model with a shared parameter tensor, the gradient of a scalar loss has the same logical dimensions as the parameters. If you want every output score's sensitivity to every input entry, the full derivative must account for both sets of axes. For a batch of independent examples, the blocks connecting different examples are zero. Mean subtraction across examples couples those entries, so the blocks can become nonzero. This distinction is why a gradient of a batch loss and a batch of individual Jacobians describe different calculations.
A zero gradient does not certify that you found a minimum. For instance L(a,b)=a²−b² has zero gradient at the origin. Moving along a increases its value and moving along b decreases it. A zero gradient can also arise from saturation or a clipped objective. Monitor the objective, parameter-update magnitudes, and held-out behavior before drawing a conclusion from one gradient norm.
Try it yourself
Add a shared intercept
Add a scalar bias c to all three batch predictions while leaving the weights unchanged. At c=0, what is the derivative of the half mean squared error with respect to c?
Reveal solution
Every prediction changes by the same increment h. Repeat the expansion with a feature column of ones. The derivative is mean(r)=(−1+1+1)/3=1/3. The common bias aggregates effects from all three samples.
Try it yourself
Check a direction through the nonlinear map
For F(a,b)=(a+2b, ab, a²−b)ᵀ at (2,3), estimate the change if only b rises by 0.05. Compute one exact change and explain why it agrees.
Reveal solution
The b column is (2,2,−1)ᵀ. Multiply by 0.05 to get (0.10,0.10,−0.05)ᵀ. The middle output changes from 2×3=6 to 2×3.05=6.10. With a fixed, all three outputs are affine in b, so every prediction is exact along this particular path.
Memory chart#
- Derivative measures the limiting slope with respect to one scalar input.
- Partial derivative changes one coordinate while holding the other coordinates fixed.
- Gradient collects sensitivities of one scalar outcome and predicts change by a dot product.
- Jacobian puts outputs on rows and inputs on columns, mapping a small input displacement to an estimated output change.
- Finite differences verify analytic derivatives on reproducible small fixtures. The step, arithmetic precision, and branch boundaries affect the check.
Next, Chain Rule, Backpropagation, and Autodiff follows these local derivatives through a sequence of operations, including parameters that influence the result along multiple paths.
References#
- Mathematics for Machine Learning, Chapter 5, Sections 5.1–5.3 develops scalar derivatives, partial derivatives, and the output-by-input Jacobian convention.
- Deep Learning, Chapter 4, Sections 4.3 and 4.3.1 connects gradients to directional change and explains the local nature of descent steps.
- PyTorch gradcheck mechanics explains central differences and numerical Jacobian reconstruction for real inputs.
- PyTorch torch.func.jacrev documents argument selection and batched Jacobian evaluation.