Calculus for Machine Learning: Derivatives, Gradients, and the Chain Rule
How derivatives, partials, gradients, Jacobians, and the chain rule turn a loss into parameter updates — the calculus behind backpropagation.
Calculus gives machine learning a language for change. A model changes its prediction when an input changes, a loss changes when a prediction changes, and training changes parameters so that the loss becomes smaller. Derivatives quantify each of these effects. Gradients organize many derivatives into a direction, the chain rule connects changes through a sequence of operations, and curvature helps explain why some updates are stable while others overshoot. This chapter develops those ideas with the notation and examples needed to understand modern learning algorithms without treating differentiation as a collection of unexplained rules.
Why Training Is a Calculus Problem
A machine learning model is a parameterized function. Given an input and parameters , it produces a prediction
A loss function compares that prediction with a target :
For a dataset, the training objective usually averages losses across examples and may add a regularization term:
Training asks how changes when each parameter changes. If increasing one weight slightly increases the loss, that weight should usually move in the opposite direction. If changing a parameter has almost no effect, a large adjustment may be unnecessary or unsafe without more information. The derivative formalizes this local sensitivity.
For a scalar parameter , the derivative is defined by a limit:
The numerator measures a change in the objective and the denominator measures the parameter change that produced it. Their ratio is an average rate of change over a small interval. Taking the limit gives the instantaneous rate at .
The derivative is local information. It says what happens for an infinitesimal movement near the current point, not what must happen after an arbitrary jump. If , a sufficiently small increase in raises , while a sufficiently small decrease lowers it. This observation motivates the update
where is the learning rate. Real models contain many parameters, so the scalar derivative becomes a gradient. Deep models also contain long compositions of functions, so the chain rule becomes indispensable.
Calculus appears beyond training as well. Derivatives measure sensitivity to inputs, support feature-attribution methods, characterize probability-density transformations, and help analyze robustness. Integrals define expectations, marginal probabilities, and continuous normalization. Yet the central training loop is fundamentally differential: evaluate an objective, calculate how it responds to parameter changes, and use those sensitivities to choose an update.
Derivatives of Functions Commonly Used in Machine Learning
Successful differentiation depends less on memorizing hundreds of formulas than on recognizing a small set of recurring functions and combining a few rules correctly.
Powers and polynomials
For a real exponent , where the expression is defined,
Constants differentiate to zero, and differentiation distributes across sums. Therefore, for
the derivative is
Squared error is a particularly important polynomial. If
then
The factor is included because it cancels the produced by differentiation. It does not change the location of the minimum. The derivative also has an intuitive sign: an overprediction gives a positive derivative, while an underprediction gives a negative derivative.
Exponential functions
The natural exponential has the special property
For a scaled exponent, the chain rule gives
Exponentials appear in softmax probabilities, likelihoods, density functions, attention mechanisms, and smooth activation functions. They grow rapidly for positive inputs and approach zero for large negative inputs. Implementations must therefore consider numerical stability. Softmax, for example, is evaluated after subtracting the largest logit because multiplying numerator and denominator by the same exponential factor leaves the probabilities unchanged.
Logarithms
For ,
The natural logarithm converts products into sums and appears throughout maximum likelihood. If independent observations have likelihoods , maximizing
is equivalent to maximizing
The sum is easier to differentiate and more stable numerically. The derivative also explains why assigning a very small probability to an observed event receives a strong penalty: the log changes sharply near zero.
For a composition such as ,
The condition matters. Taking the logarithm of zero or a negative value is invalid over the real numbers. Machine learning libraries commonly combine logarithms with softmax or sigmoid operations in stable loss functions rather than asking users to compute probabilities and logs separately.
The sigmoid function
The logistic sigmoid maps a real number to the interval :
Its derivative can be written entirely in terms of its output:
To derive this result, write and apply the power and chain rules:
The derivative reaches its maximum value at and approaches zero as becomes strongly positive or negative. This saturation makes sigmoid useful for probability-like outputs but problematic across many hidden layers: multiplying many derivatives smaller than one can produce a vanishing gradient.
The most frequently used derivative facts can be summarized as follows.
| Function | Derivative | Typical machine learning role |
|---|---|---|
| Polynomial models, squared penalties | ||
| Softmax, densities, smooth transforms | ||
| Log-likelihood and cross-entropy | ||
| Binary outputs and gates | ||
| Regression loss |
These entries are building blocks, not isolated recipes. The argument of a function often depends on parameters, in which case its outer derivative must be multiplied by the derivative of that argument.
Partial Derivatives and Multivariable Models
Machine learning objectives rarely depend on only one number. Suppose
The partial derivative with respect to treats as fixed:
The partial derivative with respect to treats as fixed:
At , these values are and . They answer two different local questions. If only increases slightly, the function initially changes at about eight units per unit of . If only increases, it initially changes at about eleven units per unit of .
For a linear model
the prediction derivatives are
These expressions have an immediate interpretation. A weight connected to a large input has a larger effect on the prediction. The bias always changes the prediction one-for-one. Once a loss is placed around , the chain rule combines prediction sensitivity with loss sensitivity.
The notation must reveal what is held fixed. A partial derivative does not say that variables are unrelated; it describes a coordinate-wise change. During actual training, all parameters may be updated together. Partials are assembled into a gradient to represent the complete first-order behavior.
Gradients and the Direction of Steepest Change
For a scalar function , the gradient is the vector
The gradient points in the direction of steepest local ascent under Euclidean distance. To understand this statement, take a unit direction . The rate of change along that direction is the directional derivative
Because has length one, the Cauchy-Schwarz inequality gives
Equality occurs when points in the same direction as . The smallest directional derivative occurs in the opposite direction. Consequently, is the direction of steepest local descent, which leads to
Consider
Its gradient is
At , the gradient is . Moving a small distance along increases the objective most rapidly, while moving along decreases it most rapidly. The larger second component reflects sharper change along .
“Steepest” depends on the geometry used to measure step length. Ordinary gradient descent assumes Euclidean geometry. Feature scaling, preconditioning, natural gradients, and adaptive optimizers effectively modify the geometry or coordinate-wise step sizes. The raw gradient remains a local derivative vector, but the update need not be a simple scalar multiple of it.
Jacobians and Hessians: Derivative Structure Beyond a Gradient
A gradient applies when a function has a scalar output. A neural-network layer usually maps a vector to another vector. If
its Jacobian is the matrix
Each row describes how one output responds to all inputs; each column describes how all outputs respond to one input. Locally, the Jacobian acts as the best linear approximation:
For an affine layer , the Jacobian with respect to is simply . For an elementwise activation, the Jacobian is diagonal because each output activation depends only on its corresponding input. Backpropagation composes these local linear maps without usually constructing every full Jacobian.
The Hessian applies to a scalar function and collects second partial derivatives:
The diagonal entries measure coordinate-wise curvature. Off-diagonal entries measure interactions: they indicate how the derivative with respect to one parameter changes as another parameter changes. Near a point , the Hessian appears in a second-order approximation:
Hessian eigenvectors identify principal curvature directions, and eigenvalues quantify curvature along them. Large positive eigenvalues indicate steep upward curvature. Negative eigenvalues reveal directions of downward curvature. A mixture of positive and negative eigenvalues indicates a saddle. Computing and storing a full Hessian is generally impractical for large networks, but Hessian-vector products and approximations can still provide useful curvature information.
The Chain Rule: The Engine of Backpropagation
The chain rule differentiates composed functions. If and , then
The notation expresses a path of influence. A small change in changes ; the change in changes . Multiplying the two local rates gives the total local effect.
Suppose
for fixed . Introduce intermediate variables
Then
The final fraction is , so . Breaking a complicated expression into local operations makes the derivative easier to reason about and easier to implement.
For vectors, the same principle becomes multiplication by Jacobians. If and , then the Jacobian of the composition is
The order matters because matrix multiplication is not commutative. Deep learning frameworks typically evaluate vector-Jacobian products in reverse order, beginning with the scalar loss and moving backward through the computation graph. This reverse-mode strategy is efficient when one scalar loss depends on many parameters.
Backpropagation is therefore not a separate derivative rule. It is an organized, computationally efficient application of the chain rule. Intermediate forward values are stored or recomputed, local derivatives are evaluated, and an upstream sensitivity is passed backward through each operation.
Worked Example: A Two-Layer Scalar Network
Consider a small scalar network with one input , one hidden activation , one output , and squared loss:
This is a two-layer network if layers are counted by their parameterized transformations. The hidden layer is nonlinear, and the output layer is linear.
Choose
The forward pass begins with
The hidden activation is
The prediction is
The residual and loss are
Now move backward. The loss derivative with respect to the prediction is
Because ,
Therefore,
and
To continue toward the first layer, calculate the hidden sensitivity:
The sigmoid derivative at is
Thus
Finally,
The first-layer gradients are
Every factor has a meaning. The residual says whether the output is too high or low. The output weight transfers that signal to the hidden unit. The sigmoid derivative measures how responsive the hidden unit is at its current pre-activation. The input scales the effect on . If the sigmoid were saturated, its derivative would be tiny and the first-layer gradient would shrink even if the output error remained substantial.
With learning rate , one gradient-descent update gives approximately
All four derivatives are negative, so subtracting them increases all four parameters. For this example, that raises the underpredicted output toward the target. The following code reproduces the forward values, analytical gradients, and a finite-difference check:
import math
def sigmoid(z):
return 1.0 / (1.0 + math.exp(-z))
def loss(params, x=2.0, y=1.0):
w1, b1, w2, b2 = params
h = sigmoid(w1 * x + b1)
prediction = w2 * h + b2
return 0.5 * (prediction - y) ** 2
params = [0.5, -0.2, 1.2, 0.1]
w1, b1, w2, b2 = params
x, y = 2.0, 1.0
z1 = w1 * x + b1
h = sigmoid(z1)
prediction = w2 * h + b2
d_prediction = prediction - y
dw2 = d_prediction * h
db2 = d_prediction
dz1 = d_prediction * w2 * h * (1.0 - h)
dw1 = dz1 * x
db1 = dz1
analytical = [dw1, db1, dw2, db2]
epsilon = 1e-6
numerical = []
for index in range(len(params)):
plus = params.copy()
minus = params.copy()
plus[index] += epsilon
minus[index] -= epsilon
numerical.append((loss(plus) - loss(minus)) / (2.0 * epsilon))
print("prediction:", prediction)
print("loss:", loss(params))
print("analytical:", analytical)
print("numerical:", numerical)
The numerical derivative uses a centered finite difference. It is useful for checking a hand-derived gradient on a small problem, although automatic differentiation is faster and more accurate for ordinary training.
Critical Points, Curvature, and Convexity
A critical point of a differentiable scalar function occurs where the derivative or gradient is zero. In one dimension, the second derivative helps classify it:
- If and , the point is a strict local minimum.
- If and , the point is a strict local maximum.
- If , the test is inconclusive.
For example, has a minimum at zero, while has a maximum there. The function also has zero first and second derivatives at zero, but zero is neither a minimum nor a maximum.
In multiple dimensions, the Hessian replaces the second derivative. A positive definite Hessian at a stationary point indicates a strict local minimum. A negative definite Hessian indicates a strict local maximum. If the Hessian has both positive and negative eigenvalues, the point is a saddle. The function
has gradient zero at the origin but curves upward along the -axis and downward along the -axis.
A function is convex when every chord lies on or above its graph:
For a differentiable convex function, every local minimum is global. If the function is twice differentiable, a positive semidefinite Hessian everywhere is sufficient for convexity. Linear regression with mean squared error is convex in its coefficients. Logistic regression with the standard cross-entropy objective is also convex in its linear parameters.
Neural-network training is generally nonconvex. Parameters in different layers multiply through compositions, hidden units can be permuted without changing the represented function, and nonlinear activations create complex interactions. The objective may contain many saddle points, flat directions, and basins. A zero gradient therefore does not prove that training found a global minimum—or even a local minimum.
Nonconvexity does not imply that learning is hopeless. Large networks often contain many parameter settings with similarly low loss. Stochastic mini-batches, initialization, normalization, residual connections, and overparameterization can make useful regions accessible. In practice, held-out performance matters more than proving that one particular parameter vector is globally optimal.
Taylor Expansion and Learning-Rate Intuition
Taylor expansion connects derivatives to local prediction. In one dimension,
The first-order term predicts change from slope. The second-order term corrects for curvature. Gradient descent chooses , so
The negative first-order term favors a loss decrease. The curvature term grows with and can overcome that decrease if the step is too large. This is the mathematical reason a correct descent direction can still produce a worse objective after an excessive step.
For the quadratic
the derivative is , and gradient descent gives
Convergence requires
or
Curvature limits the stable learning rate. In multiple dimensions, the largest Hessian eigenvalue plays an analogous role for a quadratic objective. A narrow valley with one very large eigenvalue and one small eigenvalue forces a global learning rate to respect the steep direction, which can make progress painfully slow along the shallow direction.
Taylor reasoning is local, especially for nonquadratic objectives whose curvature changes across the landscape. Still, it provides a durable mental model: the gradient predicts the best infinitesimal direction, the learning rate chooses how far to trust that prediction, and curvature determines how quickly the prediction becomes inaccurate.
Automatic Differentiation at a High Level
Automatic differentiation, often shortened to autodiff, computes derivatives by decomposing a program into elementary operations with known local derivatives. It is neither symbolic algebra nor ordinary numerical differentiation.
Symbolic differentiation manipulates formulas to produce new formulas. It can create large redundant expressions and does not naturally fit arbitrary programs containing reused intermediates or control flow. Numerical differentiation perturbs inputs and estimates slopes from function values. It is simple but suffers from truncation and floating-point error, and it requires separate evaluations for many parameters.
Autodiff records or traces a computational graph. If a program calculates , , and , the graph stores those operations and their dependencies. During a reverse pass, the system begins with
and repeatedly multiplies an upstream sensitivity by each operation's local derivative. When a value influences the loss through several paths, contributions from those paths are added.
Reverse-mode autodiff is well suited to machine learning because a scalar loss depends on a large number of parameters. One reverse traversal calculates derivatives with respect to all of them at a cost comparable to a small multiple of the forward computation. Frameworks may save forward intermediates, recompute some values to reduce memory, fuse operations, and generate efficient kernels, but the mathematical foundation remains the chain rule.
Autodiff does not guarantee that the modeled objective is correct. It will faithfully differentiate a mistaken loss, an unintended broadcast, leaked data, or a disconnected computation. Gradient checks, shape assertions, small test cases, and domain reasoning remain important.
Common Calculus Mistakes in Machine Learning
Forgetting the inner derivative
For
the derivative is not merely . The derivative of the inner function is , so
Missing this factor is the most common chain-rule error. In a deep network, every operation on the path from a parameter to the loss contributes a local factor.
Confusing scalar, vector, and matrix derivatives
A scalar loss differentiated with respect to a vector produces a gradient vector. A vector output differentiated with respect to a vector input produces a Jacobian matrix. A scalar differentiated twice with respect to a vector produces a Hessian matrix. Treating all of these as an undifferentiated “derivative” causes shape errors and reversed matrix products.
Write dimensions beside quantities. If , , and , then contains local sensitivities, while contains .
Treating a partial derivative as a total derivative
A partial derivative changes one explicit argument while holding others fixed. If those “other” quantities also depend on the same underlying variable, a total derivative must include their indirect paths. Computational graphs make this distinction concrete: every route from a variable to the output contributes.
Using the wrong update sign
The gradient points toward ascent. Minimizing a loss normally requires subtraction:
Adding the gradient performs ascent. Sign conventions can become confusing when maximizing log-likelihood or reward, so define the objective explicitly before implementing the update.
Assuming zero gradient means global optimum
A zero gradient can indicate a minimum, maximum, saddle, or flat inflection point. Classification requires curvature and context. In nonconvex learning, even a local minimum does not carry a global guarantee.
Ignoring nondifferentiable points
Functions such as absolute value and ReLU are not differentiable at isolated points. Frameworks choose a subgradient or conventional value there. This is usually practical, but one should not claim an ordinary derivative exists where it does not. Piecewise functions must also be differentiated on the correct branch.
Confusing finite differences with exact derivatives
The approximation
depends on . A large value creates truncation error; an extremely small value creates cancellation and floating-point error. Finite differences are valuable for checks, not usually for training a large model.
Ignoring numerical domains
Expressions such as , , and have numerical hazards. A mathematically correct derivative cannot rescue an implementation that evaluates or overflows an exponential. Stable combined operations, clipping used with care, appropriate data types, and finite-value checks are part of correct applied calculus.
Practice with Solver360
Calculus becomes durable when symbolic work is connected to numerical behavior. Use the Scientific Calculator to evaluate function values, compare analytical derivatives with nearby difference quotients, and check the numerical steps in the two-layer example. Begin with , , and . At several values of , compare the predicted local change with the actual change . Reduce and observe how the first-order prediction improves.
Then use the Gradient Descent Calculator to connect derivatives with optimization paths. A useful sequence is:
- Select a one-dimensional quadratic and identify its derivative and critical point by hand.
- Start on each side of the minimum and predict the sign of the gradient before running an update.
- Increase the learning rate until the path begins to alternate across the minimum.
- Increase it further until the iterates diverge, then relate the threshold to curvature.
- Compare a circular two-dimensional bowl with an elongated bowl and inspect the direction of the gradient against the contour lines.
- Start near a saddle and explain why a small gradient does not certify a minimum.
- Rescale one coordinate and observe how the same nominal learning rate behaves under the new geometry.
For a hand-calculation exercise, return to the scalar network and replace with . Predict which gradient factors change sign. Next, change so that is very large and positive. The sigmoid output will approach one, but its derivative will approach zero. Trace how that small local derivative weakens the gradient reaching .
Finally, compare analytical and finite-difference gradients. Perturb one parameter at a time, calculate the centered difference, and compare at several values of . The two methods should agree over a reasonable range but eventually differ when becomes too small. This experiment separates calculus error from floating-point behavior.
Frequently Asked Questions
Is calculus required to use machine learning libraries?
One can fit models with high-level libraries without manually differentiating every expression. However, calculus is necessary for understanding why optimization behaves as it does, diagnosing vanishing or exploding gradients, choosing losses and activations coherently, and implementing unfamiliar models. Libraries remove repetitive derivative calculation; they do not remove the underlying relationships.
A practical learner does not need every theorem before training a model. A strong foundation consists of scalar derivatives, partial derivatives, gradients, the chain rule, basic matrix shapes, and curvature intuition. These concepts explain a large portion of everyday deep-learning behavior.
What is the difference between a derivative and a gradient?
A derivative usually describes the rate of change of a scalar function with respect to one scalar variable. A gradient collects partial derivatives of a scalar output with respect to multiple inputs into a vector. If , then has components.
The gradient is more than convenient storage. Under Euclidean geometry, it identifies the steepest local ascent direction, and its negative identifies steepest local descent.
Is the gradient always perpendicular to a contour line?
At a regular point where the gradient is nonzero, yes. A contour or level set contains points where is constant. Motion tangent to that contour has directional derivative zero. Since the directional derivative is , tangent directions are orthogonal to the gradient.
This geometric fact explains why gradient arrows cross loss contours rather than following them. At critical points where the gradient is zero, no unique gradient direction exists.
Why does backpropagation work backward?
The final loss is scalar while the model may contain millions of parameters. Reverse-mode differentiation starts with the loss sensitivity and reuses shared downstream calculations while moving toward all parameters. This is efficient for many inputs and one output.
Forward-mode differentiation propagates the effect of one input direction toward outputs. It can be preferable when there are few inputs and many outputs. Neural-network training has the opposite shape, so reverse mode is the natural choice.
Are backpropagation and gradient descent the same algorithm?
No. Backpropagation computes gradients through a composed model. Gradient descent uses those gradients to update parameters. The same backpropagated gradient can be supplied to SGD, momentum, Adam, or a second-order method. Conversely, finite differences could estimate a gradient for descent, although that would be inefficient for a large network.
Keeping the distinction clear helps debugging. A model may have correct gradients but an unstable learning rate, or an appropriate optimizer may receive incorrect gradients because the computational graph is wrong.
Why do gradients vanish in deep networks?
The chain rule multiplies local derivatives along a path. If many factors have magnitudes smaller than one, their product can become extremely small. Saturated sigmoid and tanh activations are common contributors. Small weight singular values can shrink signals as well.
Initialization schemes, ReLU-like activations, normalization, and residual connections help preserve gradient flow. Vanishing is not merely “a small learning rate”; it is a weak derivative signal before the optimizer chooses a step.
Why do gradients explode?
Repeated multiplication by large local derivatives or weight matrices can make an upstream sensitivity grow rapidly. Exploding gradients produce unstable updates, very large parameter values, infinities, or NaNs. Recurrent networks are especially vulnerable because the same transition is composed across many time steps.
Appropriate initialization, normalization, stable architectures, lower learning rates, and gradient clipping can help. Clipping controls the update consequence but should not replace investigation of persistently unstable dynamics.
Does a positive second derivative guarantee a minimum?
In one dimension, if and , then is a strict local minimum under standard smoothness conditions. A positive second derivative without a zero first derivative does not indicate a critical point. In multiple dimensions, the corresponding condition is a zero gradient and a positive definite Hessian.
The guarantee is local. A nonconvex function can have several local minima with different objective values. Convexity is what turns local minimality into global minimality.
Why not compute the full Hessian for every update?
With parameters, a full Hessian has entries. A model with one million parameters would require a trillion entries, far beyond practical storage and computation. Solving a Newton update can also be expensive and numerically delicate.
Second-order information is still useful through Hessian-vector products, diagonal or block approximations, quasi-Newton methods, and curvature-aware optimizers. First-order methods remain dominant because gradients scale much better and stochastic mini-batches provide inexpensive update estimates.
How can I tell whether my analytical gradient is correct?
Test a tiny deterministic problem using centered finite differences, compare relative rather than only absolute error, and avoid points where the function is nondifferentiable. Use double precision for the check and try several perturbation sizes. Also verify dimensions and isolate each parameter.
A successful gradient check only validates the tested computation near the tested values. It does not prove that the chosen loss represents the intended task, that batching is correct, or that every branch of a program behaves properly.
From Calculus to Loss Functions and Gradient Descent
The main structure of machine learning calculus is now visible. Derivatives measure local change. Partial derivatives isolate coordinate-wise sensitivity. A gradient assembles those sensitivities and points toward steepest local ascent, making its negative the fundamental descent direction. Jacobians describe vector transformations, Hessians describe curvature, and the chain rule links every operation between a parameter and the loss. Backpropagation and automatic differentiation turn that linkage into an efficient computation.
The next step is to study loss functions as mathematical models of error. Mean squared error, cross-entropy, margin losses, and regularization terms create different gradients and encode different assumptions. After that, study gradient descent in depth: learning rates, stochastic and mini-batch estimates, momentum, adaptive methods, conditioning, and stopping criteria. Calculus explains what local information is available; optimization explains how to use it repeatedly to learn.
Return to the Gradient Descent Calculator as those topics become more detailed. The visible path of an optimizer is a sequence of calculus decisions: evaluate a local slope, choose how far to trust it, encounter new curvature, and repeat. That perspective connects elementary derivatives directly to the training of modern machine learning systems.
Continue reading
Gradient Descent Complete Guide: Learning Rates, Variants, and Convergence
Understand why gradient descent works, how learning rate and batch size change the path, and when to use SGD, momentum, RMSProp, or Adam on real loss surfaces.
Loss Functions in Machine Learning: MSE, MAE, Likelihood, and Cross-Entropy
What a loss actually optimizes: MSE and MAE for regression, log loss and cross-entropy for classification, and how regularization adds extra terms.