Derivatives And Gradient Descent
On this page
Calculus is the branch of mathematics that studies continuous change. It has two main branches: differential calculus, which studies rates of change, and integral calculus, which studies accumulation and area. This note covers the first branch and its most important application in computer science, gradient descent, the optimization algorithm behind almost all of modern machine learning. Integrals are in "Integrals."
What A Derivative Is
The derivative of a function measures how quickly the function changes. If , the derivative is written (Lagrange notation, "f prime") or (Leibniz notation, "a small change in per small change in ").
Geometrically, the derivative at a point is the slope of the tangent line to the graph at that point. The tangent is the straight line that just touches the curve there and points in the direction the curve is heading.
Reading The Sign
The sign of the derivative tells you the direction of the function, and its size tells you how steep it is.
| Derivative | Function is | Picture |
|---|---|---|
| Increasing | Walking uphill | |
| Decreasing | Walking downhill | |
| Momentarily flat | Top of a hill, bottom of a valley, or a plateau |
A speedometer is a good analogy. Your position on the road is , and the speedometer shows : not where you are, but how fast where you are is changing.
Differentiation Rules
You rarely compute derivatives from the formal limit definition. Instead you apply a small set of rules, term by term.
The Power Rule
The most important rule, used for every polynomial (an expression built from powers of , like ):
Bring the exponent down in front, then lower the exponent by one.
Constants And Constant Multiples
A constant does not change, so its rate of change is zero: . A constant multiple just comes along for the ride:
A term like is , so its derivative is .
Sums Term By Term
The derivative of a sum is the sum of the derivatives, so you differentiate each term separately:
Exponential Functions
An exponential function has the variable in the exponent, such as , or . The most important one uses Euler's number , because has a remarkable property: it is its own derivative.
The last rule is a special case of the chain rule: the constant in the exponent comes out in front. So and . The meaning of is that the growth rate is always equal to the current size, which is exactly the behaviour of compound interest, viral spread and unchecked population growth.
Rules Summary
| Function | Derivative |
|---|---|
| (constant) | |
Higher Derivatives
A derivative is itself a function, so you can differentiate it again. For :
The second derivative measures how the rate of change itself changes. In physics, if is position, is velocity and is acceleration. In optimisation, tells you whether a flat point is a valley () or a hilltop ().
Applications In Computer Science
Whenever you want to understand how one quantity responds to another, derivatives show up.
Machine Learning
A model with a parameter is judged by a loss function that measures how wrong its predictions are. The derivative says how the loss changes when you nudge . Training a model means repeatedly moving in the direction that lowers the loss, which is gradient descent, covered in detail below:
Algorithm Analysis
If an algorithm's running time is approximately , then describes how quickly the running time grows as the input grows. Big O notation such as captures the long-term growth class, while the derivative gives the instantaneous growth rate. For , : adding one element to a big input costs roughly extra steps.
Computer Graphics
The derivative of a curve gives its slope at every point, and that slope determines the surface normal, the direction perpendicular to the surface. Normals are what lighting, reflections and shading calculations are built on.
Network Traffic And User Growth
If is the number of packets transmitted at time , then is the rate of change of traffic. A large positive spike may signal a sudden surge, a large negative one may signal congestion or a failure.
For a website whose users grow as , the growth rate is . Notice that the rate is times the current number of users: the more users you have, the faster you gain new ones. Even when libraries compute derivatives for you (PyTorch's autograd, for example), knowing what they mean is what lets you reason about why a model trains or fails to train.
Gradient Descent
Gradient descent is an iterative optimisation algorithm: it searches for the input that minimises a function, using only the derivative. Take . You can see that the minimum is at where , but for a loss function with millions of parameters you cannot see anything, so you need an algorithm.
The Blindfolded Hiker
Imagine standing on a mountain, blindfolded, trying to reach the bottom of the valley. A reasonable strategy is:
- Feel the slope of the ground under your feet.
- Take a small step downhill.
- Repeat until the ground is flat.
The derivative is the slope you feel. A positive derivative means uphill is to the right, so you step left. A negative derivative means uphill is to the left, so you step right. In both cases you move in the direction opposite to the derivative.
The Update Rule
From the current position , the next position is
where is the slope at the current point and is the learning rate, the step size multiplier. The minus sign is the "opposite direction" from the hiker strategy.
Worked Example
Minimise , with , starting at with . The update rule becomes .
Look at the step sizes: , then , then . At the tangent is steep () so the step is big. Closer to the bottom the slope flattens and the steps shrink automatically. You do not need to tell the algorithm to slow down near the minimum, the derivative does it for you.
The same thing in code takes only a few lines:
def gradient_descent(df, x0, alpha=0.1, steps=50, tol=1e-8):
x = x0
for n in range(steps):
step = alpha * df(x)
x = x - step
if abs(step) < tol: # slope is (almost) zero: converged
break
return x
df = lambda x: 2 * x # derivative of f(x) = x**2
print(gradient_descent(df, x0=4)) # very close to 0Choosing The Learning Rate
The learning rate is the most important setting of the algorithm, and it is a trade-off.
| Learning rate | Behaviour |
|---|---|
| Too small | Converges, but painfully slowly: many tiny steps |
| About right | Converges quickly to the minimum |
| Too large | Jumps over the minimum, oscillates, and can even diverge |
With on the update becomes . Each step flips the sign and multiplies the distance by : . The algorithm overshoots further every time and never settles. For specifically, the update is , so it converges exactly when , meaning .
Critical Points
When , the update rule gives : the algorithm stops moving. Such a point is a critical point, and it is not necessarily a minimum.
| Type | Example | Second derivative test |
|---|---|---|
| Minimum | at | , curves upward |
| Maximum | at | , curves downward |
| Saddle point | at | , test is inconclusive |
For , the function is negative just left of and positive just right of it, so is neither a minimum nor a maximum, even though the tangent is horizontal there. So is necessary for a minimum but not sufficient. Gradient descent on can grind to a halt at the saddle point without ever finding a minimum (there is none, the function goes to ).
Local And Global Minima
A function can have several valleys. The lowest one is the global minimum, the others are local minima. Gradient descent only ever feels the local slope, so it settles in whichever valley it starts above.
For , the derivative has three zeros (found numerically): (global minimum, ), (local maximum) and (local minimum, ). Start at and the algorithm happily stops at , unaware that a much deeper valley exists. In practice this is handled with tricks like random restarts, momentum, or stochastic noise in the gradient.
Gradient Descent In Machine Learning
Real models have many parameters, the weights , and a loss that depends on all of them, . For regression, a common loss is the Mean Squared Error:
where is the true value and the model's prediction. With several variables, the ordinary derivative is replaced by partial derivatives : the slope in the direction of one weight while the others are held fixed. Together they form the gradient, which gives the algorithm its name. Every weight gets the same update rule:
This is repeated until the loss is small enough. The same loop trains linear and logistic regression, neural networks, deep learning models and reinforcement learning agents.
Worked Exercises
These cover rules, critical points and gradient descent.
Rules
. . . . For : and .
Applied Derivatives
Users after months: , so users per month. Height of a simulated object , so the velocity is .
Critical Points
For : , and , so it is a minimum.
For : gives and . With : (local maximum) and (both local minima, ). Gradient descent started at negative ends at , started at positive ends at .
One Gradient Descent Step
, , : , so .
Quick Recap
- The derivative is the slope of the tangent: positive means increasing, negative means decreasing, zero means flat.
- Power rule , constants vanish, constant multiples stay, sums go term by term.
- and : exponential growth rate is proportional to the current size.
- Higher derivatives: is the rate of change of the rate of change (acceleration, curvature).
- Gradient descent: , step opposite to the slope. Steps shrink automatically near the minimum.
- Learning rate: too small is slow, too large overshoots or diverges.
- marks a critical point: minimum, maximum or saddle. Use to classify.
- Gradient descent can get stuck in a local minimum; the start point matters.
- In ML, the loss (e.g. MSE) is minimised with partial derivatives for every weight.