Chapter 10 of 25
Calculus for Neural Networks
Derivatives, gradients, and the chain rule that makes learning possible
Motivation
Linear algebra, from the last chapter, tells you what a neural network computes — a chain of matrix multiplications and activations. Calculus is what tells the network how to get better. Every single weight update that ever happens during training is, underneath the surface, the result of a derivative calculation. If linear algebra is the network's anatomy, calculus is its learning mechanism.
This chapter builds the calculus toolkit — derivatives, partial derivatives, gradients, and above all the chain rule — that you need to fully understand backpropagation, coming up soon. Take the chain rule section seriously: it is, without much exaggeration, the single most important piece of math in this entire course.
A Real-Life Scenario
Imagine you're adjusting the temperature dial on an oven while baking bread, trying to hit a perfect golden crust. You don't know the exact function relating dial position to crust color, but you can experiment: nudge the dial up slightly, see if the crust darkens faster or slower than before. That nudge-and-observe process — how much does the output change when I change this one input by a tiny amount? — is exactly what a derivative measures.
Now imagine that instead of one dial, you have a million dials (the weights of a neural network), and instead of eyeballing crust color, you have a single number telling you how wrong the whole network's prediction was (the loss). You can't nudge a million dials one at a time and see what happens — that would take forever. What you need is a way to instantly know, for every dial simultaneously, which direction to turn it to make the loss smaller. That's exactly what gradients and the chain rule deliver, and it's exactly what makes training feasible at all.
Building the Intuition
Here's the picture to hold before any formulas:
- A derivative tells you the instantaneous rate of change of a function — nudge the input a tiny bit, and the derivative tells you how much and in which direction the output moves.
- A partial derivative does the same thing, but for a function of many variables at once, treating every variable except one as temporarily frozen.
- The gradient collects every partial derivative into a single vector that points in the direction of steepest increase — its negative points toward the fastest way to decrease the function, which is exactly what we want when trying to shrink a loss.
- The chain rule is how you compute a derivative through a chain of nested functions — and a neural network, layer stacked on layer, is nothing but a very long chain of nested functions.
The Math Behind It
The Derivative
Intuition: nudge by a tiny amount and see how much changes, then shrink that nudge toward zero. If , increasing increases ; if , increasing decreases . This is precisely the information used to decide which direction to move a weight during training: we want to know which way to nudge it to decrease the loss.
| Function | Derivative |
|---|---|
| f(x) = c (constant) | f'(x) = 0 |
| f(x) = xⁿ | f'(x) = nxⁿ⁻¹ |
| f(x) = eˣ | f'(x) = eˣ |
| f(x) = ln(x) | f'(x) = 1/x |
| f(x) = σ(x) = 1/(1+e⁻ˣ) | f'(x) = σ(x)(1−σ(x)) |
| f(x) = tanh(x) | f'(x) = 1 − tanh²(x) |
The sigmoid and tanh derivatives above get used constantly once we reach activation functions and backpropagation. It's worth being able to re-derive from the quotient rule at least once, so it isn't just a memorized fact.
Partial Derivatives
A neural network's loss doesn't depend on one variable — it depends on every weight and bias simultaneously, which can number in the millions. To handle functions of many variables, we need partial derivatives.
For a function , the partial derivative with respect to , written , measures 's rate of change with respect to while holding every other variable constant.
Worked example: let .
At : , and .
The Gradient
Intuition: the gradient collects every partial derivative into one vector that points in the direction of steepest increase of at that point. Its negative, , points toward steepest decrease. This single fact is the entire foundation of gradient descent: to shrink a loss function, move the parameters in the direction of .
When a function outputs a vector rather than a scalar (as many layers of a network do), the full collection of partial derivatives forms a matrix called the Jacobian. When you take second-order partial derivatives of a scalar function, you get a matrix called the Hessian, describing local curvature. This course's derivations rely primarily on first-order gradients, but both terms are worth recognizing — the Jacobian shows up naturally when reasoning about backpropagation through an entire layer at once, and the Hessian underlies second-order optimization methods and the idea of how "sharp" a loss minimum is.
The Chain Rule
This is the one piece of math this entire course is quietly building toward. It is the mathematical fact that makes backpropagation possible.
If and , so depends on only through , then:
Intuition: if changes times as fast as , and changes times as fast as , then changes times as fast as . Rates of change simply multiply along a chain of dependencies.
A simple numeric worked example: let . Set , so .
Check by direct expansion: , so — the two methods agree, exactly as they must. Concretely, at : , so , and direct expansion gives too.
Now suppose a neural network has many variables feeding into the final loss through many paths at once — this is the situation in every real layer.
If depends on , and each depends on , then:
Why this matters: in an MLP, the loss depends on a weight in an early layer only indirectly, through every neuron in every later layer that weight's output eventually influences. The multivariate chain rule is exactly what lets us sum up the contribution of every one of those paths to compute — this is, quite literally, what backpropagation implements.
Picture a neural network as a computational graph: a directed graph where each node is an operation (a matrix multiply, an addition, an activation function) and edges represent data flowing between operations. The chain rule says: to compute the derivative of the final loss with respect to any node, multiply the local derivatives along every path from that node to the loss, and sum over all such paths. Backpropagation is simply an efficient algorithm for doing this for every parameter in the network at once, by traversing the graph backward exactly one time.
Gradient Descent: A First Look
Where: is every trainable parameter (weights and biases), is the loss, is its gradient with respect to the parameters, and is the learning rate.
Intuition: since points toward steepest increase in loss, stepping in the opposite direction, , decreases it. The learning rate controls the size of that step — this same update rule is exactly what a later chapter on optimization builds on in full detail.
Implementing It
import numpy as np
def f(x):
return (3*x + 1)**2
def numerical_derivative(f, x, h=1e-6):
return (f(x + h) - f(x - h)) / (2*h)
x0 = 2.0
analytical = 18*x0 + 6 # derived by hand above
numerical = numerical_derivative(f, x0)
print(f"Analytical derivative at x={x0}: {analytical}")
print(f"Numerical derivative at x={x0}: {numerical:.6f}")This compares a hand-derived ("analytical") derivative against a numerical approximation using tiny finite differences — nudging by a small in both directions and measuring the resulting change in . The two should agree almost exactly (both give 42 here). This technique is called gradient checking, and it's an invaluable debugging tool once you implement backpropagation from scratch: it catches subtle sign errors or incorrect chain-rule applications that would otherwise silently make a network train incorrectly.
If your hand-derived gradients don't match a numerical finite-difference check to several decimal places, trust the numerical check — there's a bug somewhere in your analytical derivation or its implementation, almost always a misapplied chain rule step or a sign flip.
Key Takeaways
- The derivative measures a function's instantaneous rate of change; partial derivatives extend this to functions of many variables, holding all others fixed.
- The gradient collects every partial derivative into a vector pointing toward steepest increase; its negative points toward steepest decrease.
- The chain rule, , lets you differentiate through nested (composed) functions — exactly the structure of a layered neural network.
- The multivariate chain rule sums contributions over every path of dependency, and is the precise mathematical basis of backpropagation.
- Gradient descent updates parameters by moving them in the direction of , scaled by a learning rate .
- Gradient checking (comparing analytical derivatives against numerical finite-difference estimates) is a standard way to catch bugs in a from-scratch backpropagation implementation.
Common Mistakes
When computing for a multivariable function, every other variable must be treated as a fixed constant during that differentiation — mixing this up (differentiating with respect to the wrong variable, or forgetting a term that depends on x hidden inside a 'constant') is one of the most common early mistakes with partial derivatives.
When a dependency chain has three or more nested functions ( depends on , depends on , depends on ), it's easy to skip a link and multiply only two of the three derivatives together. Every link in the chain must be included: .
Interview Corner
Where This Shows Up in Practice
Every single training step of every neural network in existence is the chain rule, applied automatically and efficiently across every layer, computing exactly how much each weight should move to reduce the loss. Combined with the matrix and vector operations from the previous chapter, you now have both halves of the toolkit needed to derive backpropagation completely, layer by layer, symbol by symbol — which is exactly where this course goes next, right after one more chapter on probability and statistics that explains why we use the loss functions we use in the first place.