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 by a tunable weight :
The correct target is . If the current weight is , the prediction is . We can measure the error with squared loss:
At , the loss is . How do we know whether to increase or decrease ?
A derivative answers how quickly a quantity changes when one input changes slightly. For this loss function:
At , the derivative is . Its negative sign tells us that a small increase in will initially decrease the loss. For example, changing from 3 to 3.1 changes the loss from 16 to .
That calculation uses the chain rule, because the loss is formed by composing two calculations: first , 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 indicates that the output depends on the input .
Consider a simple prediction rule:
If , the predicted value is . Changing to changes the prediction to .
Different functions respond differently to changes in their inputs. For example:
- A linear function such as changes at a constant rate.
- A quadratic function such as changes at a rate that depends on the input.
- A function with several inputs, such as , 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 , its derivative is written or and defined as:
The expression inside the limit is the difference quotient: the average change in output per unit of input over a small interval of length . Taking the limit describes what happens as that interval approaches zero.
Worked example: differentiating a square
Let . Substitute it into the definition:
Therefore:
At , the derivative is . Around that point, a small increase in the input changes the output by approximately :
For , the approximation gives ; the exact value is . 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.
Interpreting the sign and size
| Derivative at a point | Local interpretation |
|---|---|
| Positive | The function increases as the input increases slightly. |
| Negative | The function decreases as the input increases slightly. |
| Zero | The tangent is horizontal; the point might be a minimum, maximum, or neither. |
| Large absolute value | The output is relatively sensitive to a small change in input. |
| Small absolute value | The output changes relatively slowly with the input. |
The interpretation applies locally. A derivative of at one point does not mean the function increases by exactly over every interval of length .
Important: Not every function is differentiable everywhere. For instance, has a sharp corner at , 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.
| Rule | Formula | Example |
|---|---|---|
| Constant | ||
| Power | ||
| Constant multiple | ||
| Sum | ||
| Product | ||
| Exponential | ||
| Natural logarithm | for |
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:
Here, is a loss (error) function, while and are two model parameters. We want to know how changes when one parameter changes while the other is held fixed.
A partial derivative measures exactly this local sensitivity. The notation means the partial derivative of with respect to ; similarly for .
For example, with the chain rule:
At and :
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 than in .
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 :
The symbol 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:
Differentiate with respect to each input:
The gradient is therefore:
At :
This tells us that, at this point, the function is more sensitive to a unit change in than to an equal-size change in .
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 , the first-order approximation is:
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:
Then , and, wherever the necessary derivatives exist:
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:
Define the intermediate value , so that .
- Differentiate the outer function: .
- Differentiate the inner function: .
- Multiply: .
So:
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 and , then:
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 and target . Our model uses a weight and bias :
Define a squared-error loss:
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:
Step 2: compute the loss
Start with and :
Step 3: calculate the derivatives backward
Apply the chain rule from the loss to the parameters:
Also:
Combining the pieces gives:
At our starting values, and , so:
The gradient with respect to the parameter vector is:
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:
Here, is the learning rate. Taking :
The updated prediction is , and the squared error decreases from to .
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:
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 gives a poor local approximation, while an extremely small 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
| Concept | What it contributes | Example |
|---|---|---|
| Derivative | Sensitivity to one input | How a loss changes with a particular model parameter |
| Partial derivative | Sensitivity to one variable while other variables are fixed | Effect of changing a neural-network bias |
| Gradient | Sensitivities to all parameters as a vector | Direction used to update a parameter vector |
| Chain rule | Derivatives through a sequence of operations | Gradients through multiple neural-network layers |
| Automatic differentiation | Efficient derivative computation from program operations | PyTorch 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
| Misunderstanding | More 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
- For , calculate and .
- For , calculate both partial derivatives and the gradient at .
- Use the chain rule to differentiate .
- A loss has gradient . In which local direction does ordinary gradient descent move the parameters?
- For a model with , , , and , find the squared-error loss and its derivatives with respect to and .
- Why does calling
loss.backward()not, by itself, finish a training step?
Show the worked answers
- , so .
- and . At , .
- .
- The negative-gradient direction is . The size of the step depends on the learning rate.
- The prediction is , the error is , and the loss is . Thus, and .
backward()computes and stores gradients. Updating parameters requires an additional optimizer step or explicit update.
Related concepts and next reading
- AI Knowledge Map — See where calculus fits into the complete AI learning path.
- Vectors and Matrices — Review parameter and feature representations.
- Vector and Matrix Operations — Review dot products and matrix computations used with gradients.
- Probability and Bayes’ Theorem — Continue through the mathematical foundations.
- Optimization and Gradient Descent — Study how gradients guide iterative parameter updates.
- Neural Network Fundamentals — Explore the components whose parameters are differentiated during learning.
- Forward Propagation and Backpropagation — Follow the chain rule through deeper neural networks.
References
- OpenStax — Calculus Volume 1. An open textbook covering limits, derivatives, differentiation rules, and the chain rule.
- MIT OpenCourseWare — Single Variable Calculus. Lectures and worked problems on derivative concepts and calculations.
- MIT OpenCourseWare — Multivariable Calculus. Study materials on partial derivatives, gradients, and the multivariable chain rule.
- PyTorch documentation — Autograd mechanics. Technical explanation of automatic differentiation and gradient computation.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.