Artificial Intelligence • Mathematical Foundations • 15 min read

Derivatives, Gradients, and the Chain Rule

A machine-learning model produces predictions from numerical inputs and adjustable parameters. During training, the model needs a way to determine how a small change in a parameter would affect its prediction error. Derivatives, gradients, and the chain rule provide the mathematical foundation for answering that question.

These concepts come from calculus, the branch of mathematics concerned with change and accumulation. They connect the numerical operations in Vector and Matrix Operations to the parameter updates used in Optimization and Gradient Descent. They also explain an essential part of neural-network backpropagation.

Begin with a model that makes an error

Suppose a tiny prediction model multiplies a single input x=2x=2 by a tunable weight ww:

y^=wx\hat y=wx

The correct target is y=10y=10. If the current weight is w=3w=3, the prediction is y^=6\hat y=6. We can measure the error with squared loss:

L(w)=(wx−y)2=(2w−10)2L(w)=(wx-y)^2=(2w-10)^2

At w=3w=3, the loss is (6−10)2=16(6-10)^2=16. How do we know whether to increase or decrease ww?

A derivative answers how quickly a quantity changes when one input changes slightly. For this loss function:

dLdw=2(2w−10)⋅2=4(2w−10)\frac{dL}{dw}=2(2w-10)\cdot2=4(2w-10)

At w=3w=3, the derivative is −16-16. Its negative sign tells us that a small increase in ww will initially decrease the loss. For example, changing ww from 3 to 3.1 changes the loss from 16 to 3.82=14.443.8^2=14.44.

That calculation uses the chain rule, because the loss is formed by composing two calculations: first 2w−102w-10, then squaring the result. When a model has many weights, we compute a partial derivative with respect to each one and collect those derivatives into a gradient.

Think of these ideas as answers to three questions: How does one output change? (derivative), how does it change with each of several inputs? (partial derivatives and gradient), and how do changes travel through a chain of calculations? (chain rule). These are the mathematical ingredients used by gradient-based training.

Functions: the starting point

A function is a rule that associates each input in its domain with exactly one output. In mathematics, the notation y=f(x)y=f(x) indicates that the output yy depends on the input xx.

Consider a simple prediction rule:

y^=f(x)=2x+1\hat{y}=f(x)=2x+1

If x=3x=3, the predicted value is y^=7\hat{y}=7. Changing xx to 44 changes the prediction to 99.

Different functions respond differently to changes in their inputs. For example:

  • A linear function such as f(x)=2x+1f(x)=2x+1 changes at a constant rate.
  • A quadratic function such as f(x)=x2f(x)=x^2 changes at a rate that depends on the input.
  • A function with several inputs, such as f(w,b)=2w+bf(w,b)=2w+b, can respond differently to each input.

Calculus makes these relationships precise.

What is a derivative?

The derivative of a function at a point is the limit, when it exists, of the ratio of a change in the function’s output to a change in its input. It measures the function’s instantaneous rate of change at that point.

For a single-variable function ff, its derivative is written f′(x)f'(x) or dfdx\frac{df}{dx} and defined as:

f′(x)=lim⁡h→0f(x+h)−f(x)hf'(x)=\lim_{h\to0}\frac{f(x+h)-f(x)}{h}

The expression inside the limit is the difference quotient: the average change in output per unit of input over a small interval of length hh. Taking the limit describes what happens as that interval approaches zero.

Worked example: differentiating a square

Let f(x)=x2f(x)=x^2. Substitute it into the definition:

f′(x)=lim⁡h→0(x+h)2−x2h=lim⁡h→02xh+h2h=lim⁡h→0(2x+h)=2x\begin{aligned} f'(x) &=\lim_{h\to0}\frac{(x+h)^2-x^2}{h}\\ &=\lim_{h\to0}\frac{2xh+h^2}{h}\\ &=\lim_{h\to0}(2x+h)\\ &=2x \end{aligned}

Therefore:

ddx(x2)=2x\boxed{\frac{d}{dx}(x^2)=2x}

At x=2x=2, the derivative is f′(2)=4f'(2)=4. Around that point, a small increase Δx\Delta x in the input changes the output by approximately 4Δx4\Delta x:

f(2+Δx)≈f(2)+4Δxf(2+\Delta x)\approx f(2)+4\Delta x

For Δx=0.01\Delta x=0.01, the approximation gives 4.044.04; the exact value is 2.012=4.04012.01^2=4.0401. The difference is small because the change in input is small.

The derivative as a tangent slope

For a differentiable real-valued function of one real variable, the derivative at a point equals the slope of the graph’s tangent line there. The tangent line provides a local linear approximation to a curved function.

Graph of y equals x squared with a tangent line at x equals two, where the tangent slope is four.
At $x=2$, the curve $f(x)=x^2$ has a tangent slope of $4$, even though its slope differs at other inputs.

Interpreting the sign and size

Derivative at a pointLocal interpretation
PositiveThe function increases as the input increases slightly.
NegativeThe function decreases as the input increases slightly.
ZeroThe tangent is horizontal; the point might be a minimum, maximum, or neither.
Large absolute valueThe output is relatively sensitive to a small change in input.
Small absolute valueThe output changes relatively slowly with the input.

The interpretation applies locally. A derivative of 44 at one point does not mean the function increases by exactly 44 over every interval of length 11.

Important: Not every function is differentiable everywhere. For instance, f(x)=∣x∣f(x)=|x| has a sharp corner at x=0x=0, so its usual derivative does not exist at that point. Some machine-learning functions also have nondifferentiable points; optimization methods may still work using suitable conventions or generalized derivatives.

Basic differentiation rules

Once a derivative is defined, a few rules make it possible to calculate derivatives of many functions without repeating the limit calculation each time.

RuleFormulaExample
Constantddxc=0\frac{d}{dx}c=0ddx7=0\frac{d}{dx}7=0
Powerddxxn=nxn−1\frac{d}{dx}x^n=nx^{n-1}ddxx3=3x2\frac{d}{dx}x^3=3x^2
Constant multipleddx[cf(x)]=cf′(x)\frac{d}{dx}[cf(x)]=cf'(x)ddx(3x2)=6x\frac{d}{dx}(3x^2)=6x
Sumddx[f+g]=f′+g′\frac{d}{dx}[f+g]=f'+g'ddx(x2+x)=2x+1\frac{d}{dx}(x^2+x)=2x+1
Product(fg)′=f′g+fg′(fg)'=f'g+fg'ddx(xex)=ex+xex\frac{d}{dx}(xe^x)=e^x+xe^x
Exponentialddxex=ex\frac{d}{dx}e^x=e^xddx(2ex)=2ex\frac{d}{dx}(2e^x)=2e^x
Natural logarithmddxln⁡x=1x\frac{d}{dx}\ln x=\frac{1}{x} for x>0x>0ddx(3ln⁡x)=3x\frac{d}{dx}(3\ln x)=\frac{3}{x}

The chain rule handles compositions of functions and will be developed below. Derivatives of the exponential and logarithm are particularly useful in probability models, activation functions, and loss functions.

Partial derivatives: when a function has multiple inputs

A prediction or loss usually depends on more than one value. Consider:

L(w,b)=(2w+b−5)2L(w,b)=(2w+b-5)^2

Here, LL is a loss (error) function, while ww and bb are two model parameters. We want to know how LL changes when one parameter changes while the other is held fixed.

A partial derivative measures exactly this local sensitivity. The notation ∂L∂w\frac{\partial L}{\partial w} means the partial derivative of LL with respect to ww; similarly for bb.

For example, with the chain rule:

∂L∂w=2(2w+b−5)⋅2\frac{\partial L}{\partial w}=2(2w+b-5)\cdot 2 ∂L∂b=2(2w+b−5)⋅1\frac{\partial L}{\partial b}=2(2w+b-5)\cdot 1

At w=1w=1 and b=0b=0:

∂L∂w=−12,∂L∂b=−6\frac{\partial L}{\partial w}=-12,\qquad \frac{\partial L}{\partial b}=-6

Both values are negative. At this point, increasing either parameter slightly would decrease the loss to first order; the loss is more sensitive per unit of change in ww than in bb.

The partial derivatives describe local effects, not globally optimal parameter choices.

Gradients: combining partial derivatives

For a differentiable scalar-valued function of several variables, the gradient is the vector of its first-order partial derivatives.

For f(x1,x2,…,xn)f(x_1,x_2,\ldots,x_n):

∇f=[∂f∂x1∂f∂x2⋮∂f∂xn]\nabla f=\begin{bmatrix} \frac{\partial f}{\partial x_1}\\ \frac{\partial f}{\partial x_2}\\ \vdots\\ \frac{\partial f}{\partial x_n} \end{bmatrix}

The symbol ∇\nabla is pronounced nabla or del. In introductory optimization, the gradient is commonly represented as a column vector.

Worked example: a function of two variables

Let:

f(x,y)=x2+3y2f(x,y)=x^2+3y^2

Differentiate with respect to each input:

∂f∂x=2x,∂f∂y=6y\frac{\partial f}{\partial x}=2x,\qquad \frac{\partial f}{\partial y}=6y

The gradient is therefore:

∇f(x,y)=[2x6y]\nabla f(x,y)=\begin{bmatrix}2x\\6y\end{bmatrix}

At (x,y)=(1,2)(x,y)=(1,2):

∇f(1,2)=[212]\boxed{\nabla f(1,2)=\begin{bmatrix}2\\12\end{bmatrix}}

This tells us that, at this point, the function is more sensitive to a unit change in yy than to an equal-size change in xx.

Geometric meaning of a gradient

For a differentiable scalar function, the gradient points in the direction of steepest local increase when direction is measured using the ordinary Euclidean notion of distance. Its negative points toward steepest local decrease.

For a small displacement Δx\Delta\mathbf{x}, the first-order approximation is:

f(x+Δx)≈f(x)+∇f(x)TΔxf(\mathbf{x}+\Delta\mathbf{x})\approx f(\mathbf{x})+\nabla f(\mathbf{x})^{\mathsf T}\Delta\mathbf{x}

This expression connects gradients to the dot product. The gradient and the displacement must have compatible dimensions.

Important: A gradient of zero does not guarantee a minimum. It can also occur at a local maximum or a saddle point. Moreover, the direction of steepest decrease depends on the scale and geometry used to measure parameter changes.

The chain rule: derivatives through connected calculations

Many AI models compute their outputs in stages. A value is transformed by one function and then passed through another. The chain rule determines how the final output changes with an earlier input.

Suppose:

u=g(x),y=f(u)u=g(x),\qquad y=f(u)

Then y=f(g(x))y=f(g(x)), and, wherever the necessary derivatives exist:

dydx=dydu⋅dudx\boxed{\frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}}

In words: multiply the sensitivity of the output to the intermediate value by the sensitivity of the intermediate value to the input.

Worked example: a composition of two functions

Let:

y=(3x+1)2y=(3x+1)^2

Define the intermediate value u=3x+1u=3x+1, so that y=u2y=u^2.

  1. Differentiate the outer function: dydu=2u\frac{dy}{du}=2u.
  2. Differentiate the inner function: dudx=3\frac{du}{dx}=3.
  3. Multiply: dydx=2u⋅3=6(3x+1)\frac{dy}{dx}=2u\cdot3=6(3x+1).

So:

dydx=18x+6\boxed{\frac{dy}{dx}=18x+6}

This procedure is more general than the specific polynomial: it applies whenever differentiable operations are composed.

The multivariable chain rule

When an intermediate quantity depends on several inputs, the chain rule extends to partial derivatives. If L=L(z)L=L(z) and z=z(w,b)z=z(w,b), then:

∂L∂w=dLdz∂z∂w,∂L∂b=dLdz∂z∂b\frac{\partial L}{\partial w}=\frac{dL}{dz}\frac{\partial z}{\partial w},\qquad \frac{\partial L}{\partial b}=\frac{dL}{dz}\frac{\partial z}{\partial b}

If an earlier variable affects the result through multiple computational paths, the contributions from those paths must be added. That sum is important in neural networks with branching or reused values.

For vector-valued intermediate functions, the more general chain rule uses Jacobians: matrices of first-order partial derivatives. The gradient examples here use the simpler scalar-output case needed for an initial understanding of model training.

Complete AI example: differentiating a prediction loss

Consider one training example with input x=2x=2 and target y=5y=5. Our model uses a weight ww and bias bb:

y^=wx+b\hat{y}=wx+b

Define a squared-error loss:

L=(y^−y)2L=(\hat{y}-y)^2

The loss measures the squared difference between the model’s prediction and the target. A single-example squared error is used here for clarity; training datasets usually contain many examples.

Step 1: express the computations as a sequence

The model evaluates four connected quantities:

z=wx+b,e=z−y,L=e2z=wx+b,\qquad e=z-y,\qquad L=e^2
Computation graph from weight, bias and input through prediction, error and squared loss, showing the reverse direction used to calculate gradients.
The forward pass calculates a prediction and loss. The backward pass computes how the loss depends on earlier values.

Step 2: compute the loss

Start with w=1w=1 and b=0b=0:

z=(1)(2)+0=2z=(1)(2)+0=2 e=2−5=−3,L=(−3)2=9e=2-5=-3,\qquad L=(-3)^2=9

Step 3: calculate the derivatives backward

Apply the chain rule from the loss to the parameters:

dLde=2e,∂e∂z=1\frac{dL}{de}=2e,\qquad \frac{\partial e}{\partial z}=1

Also:

∂z∂w=x,∂z∂b=1\frac{\partial z}{\partial w}=x,\qquad \frac{\partial z}{\partial b}=1

Combining the pieces gives:

∂L∂w=2(y^−y)x\boxed{\frac{\partial L}{\partial w}=2(\hat{y}-y)x} ∂L∂b=2(y^−y)\boxed{\frac{\partial L}{\partial b}=2(\hat{y}-y)}

At our starting values, y^−y=−3\hat{y}-y=-3 and x=2x=2, so:

∂L∂w=2(−3)(2)=−12\frac{\partial L}{\partial w}=2(-3)(2)=-12 ∂L∂b=2(−3)=−6\frac{\partial L}{\partial b}=2(-3)=-6

The gradient with respect to the parameter vector θ=[w,b]T\boldsymbol\theta=[w,b]^{\mathsf T} is:

∇θL=[−12−6]\nabla_{\boldsymbol\theta}L= \begin{bmatrix}-12\\-6\end{bmatrix}

Step 4: connect the derivatives to a parameter update

A gradient tells us the local direction of increasing loss. One common optimization method, gradient descent, uses its negative to update parameters:

θnew=θold−η∇θL\boldsymbol\theta_{\text{new}} =\boldsymbol\theta_{\text{old}}-\eta\nabla_{\boldsymbol\theta}L

Here, η>0\eta>0 is the learning rate. Taking η=0.05\eta=0.05:

wnew=1−0.05(−12)=1.6w_{\text{new}}=1-0.05(-12)=1.6 bnew=0−0.05(−6)=0.3b_{\text{new}}=0-0.05(-6)=0.3

The updated prediction is (1.6)(2)+0.3=3.5(1.6)(2)+0.3=3.5, and the squared error decreases from 99 to 2.252.25.

This is an illustrative single-example update, not proof that the updated parameters will perform better on new data. Gradient descent and its limitations are covered in Optimization and Gradient Descent.

Derivatives in Python

You can check derivatives numerically, calculate them analytically, or use automatic differentiation in a machine-learning framework. These approaches serve different purposes.

Numerical differentiation with finite differences

A central difference approximates the derivative using nearby function values:

f′(x)≈f(x+h)−f(x−h)2hf'(x)\approx\frac{f(x+h)-f(x-h)}{2h}
import numpy as np


def f(x):
    return x**2 + 3*x


def central_difference(func, x, h=1e-5):
    return (func(x + h) - func(x - h)) / (2 * h)


x = 2.0
numerical = central_difference(f, x)
analytical = 2*x + 3

print(f"Numerical derivative: {numerical:.6f}")  # 7.000000
print(f"Analytical derivative: {analytical:.6f}")  # 7.000000

assert np.isclose(numerical, analytical, atol=1e-7)

Numerical differences are useful for checking calculations. However, a very large hh gives a poor local approximation, while an extremely small hh can cause floating-point cancellation errors. They are generally not the main method used to train large neural networks.

Manually calculating a gradient and updating parameters

The next example reproduces the worked model-training calculation without relying on an automatic differentiation library:

def squared_error(w, b, x, target):
    prediction = w*x + b
    return (prediction - target)**2


x, target = 2.0, 5.0
w, b = 1.0, 0.0
learning_rate = 0.05

prediction = w*x + b
error = prediction - target

# Derivatives obtained by applying the chain rule.
dloss_dw = 2 * error * x
dloss_db = 2 * error

before = squared_error(w, b, x, target)
w -= learning_rate * dloss_dw
b -= learning_rate * dloss_db
after = squared_error(w, b, x, target)

print("Gradients:", dloss_dw, dloss_db)  # -12.0 -6.0
print("Updated parameters:", w, b)       # 1.6 0.3
print("Loss:", before, "->", after)       # 9.0 -> 2.25

assert abs(after - 2.25) < 1e-10

Automatic differentiation in PyTorch

In practice, neural-network frameworks calculate derivatives through automatic differentiation. They record or construct the necessary computation relationships and apply differentiation rules, rather than approximating every derivative with finite differences.

import torch

w = torch.tensor(1.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)

x = torch.tensor(2.0)
target = torch.tensor(5.0)

prediction = w*x + b
loss = (prediction - target)**2

loss.backward()

print("dL/dw:", w.grad.item())  # -12.0
print("dL/db:", b.grad.item())  # -6.0

The backward() call uses the chain rule to compute gradients for the tracked parameters. It does not update them. An optimizer or an explicit parameter-update step is needed for training. These ideas continue in Neural Network Fundamentals.

Where these concepts appear in AI

ConceptWhat it contributesExample
DerivativeSensitivity to one inputHow a loss changes with a particular model parameter
Partial derivativeSensitivity to one variable while other variables are fixedEffect of changing a neural-network bias
GradientSensitivities to all parameters as a vectorDirection used to update a parameter vector
Chain ruleDerivatives through a sequence of operationsGradients through multiple neural-network layers
Automatic differentiationEfficient derivative computation from program operationsPyTorch backward() and similar systems

Beyond neural-network training, derivatives appear in optimization, sensitivity analysis, scientific computing, and models that describe changing systems. They can also be used to assess how an output responds to variations in its input features, although such sensitivities are not automatically causal explanations.

Common misunderstandings

MisunderstandingMore accurate explanation
A derivative gives the exact change over any interval.It describes instantaneous or local change; linear approximations become less reliable over large intervals.
A partial derivative changes every variable at once.It varies one input while holding the others fixed.
A gradient is a single number.For a multivariable scalar function, it is a vector of partial derivatives.
A zero gradient always indicates a minimum.It may indicate a minimum, maximum, saddle point, or other stationary behavior.
The chain rule is only for neural networks.It is a general calculus rule for composed functions.
Backpropagation and gradient descent are the same operation.Backpropagation computes gradients; gradient descent uses gradients to update parameters.
Automatic differentiation is just finite differences.Automatic differentiation applies differentiation rules to the computation and is distinct from finite-difference approximations.
A negative derivative means a parameter must always increase.It describes the local direction of change; actual updates depend on the objective, learning rate, and optimization method.

Check your understanding

  1. For f(x)=x3+2xf(x)=x^3+2x, calculate f′(x)f'(x) and f′(2)f'(2).
  2. For g(x,y)=x2+xy+y2g(x,y)=x^2+xy+y^2, calculate both partial derivatives and the gradient at (1,2)(1,2).
  3. Use the chain rule to differentiate h(x)=(4x−1)3h(x)=(4x-1)^3.
  4. A loss has gradient ∇L=[3,−2]T\nabla L=[3,-2]^{\mathsf T}. In which local direction does ordinary gradient descent move the parameters?
  5. For a model y^=wx+b\hat{y}=wx+b with x=3x=3, y=4y=4, w=1w=1, and b=0b=0, find the squared-error loss and its derivatives with respect to ww and bb.
  6. Why does calling loss.backward() not, by itself, finish a training step?
Show the worked answers
  1. f′(x)=3x2+2f'(x)=3x^2+2, so f′(2)=3(4)+2=14f'(2)=3(4)+2=14.
  2. ∂g∂x=2x+y\frac{\partial g}{\partial x}=2x+y and ∂g∂y=x+2y\frac{\partial g}{\partial y}=x+2y. At (1,2)(1,2), ∇g=[4,5]T\nabla g=[4,5]^{\mathsf T}.
  3. h′(x)=3(4x−1)2⋅4=12(4x−1)2h'(x)=3(4x-1)^2\cdot4=12(4x-1)^2.
  4. The negative-gradient direction is [−3,2]T[-3,2]^{\mathsf T}. The size of the step depends on the learning rate.
  5. The prediction is 33, the error is −1-1, and the loss is 11. Thus, ∂L∂w=2(−1)(3)=−6\frac{\partial L}{\partial w}=2(-1)(3)=-6 and ∂L∂b=2(−1)=−2\frac{\partial L}{\partial b}=2(-1)=-2.
  6. backward() computes and stores gradients. Updating parameters requires an additional optimizer step or explicit update.

References

  1. OpenStax — Calculus Volume 1. An open textbook covering limits, derivatives, differentiation rules, and the chain rule.
  2. MIT OpenCourseWare — Single Variable Calculus. Lectures and worked problems on derivative concepts and calculations.
  3. MIT OpenCourseWare — Multivariable Calculus. Study materials on partial derivatives, gradients, and the multivariable chain rule.
  4. PyTorch documentation — Autograd mechanics. Technical explanation of automatic differentiation and gradient computation.

Related articles in

Image preview

Fit