Module 2 · Beginner · Before you start: the Python and maths you need

Calculus for machine learning, made easy

Calculus for machine learning without the fear: slopes, derivatives, the chain rule, partial derivatives and gradients, and how they train models, with Python.

By theprogrammers team · · 7 min read

How does a model "learn"? It starts with random guesses for its weights, measures how wrong it is, and then nudges every weight in the direction that makes it less wrong. Repeat thousands of times, and the model gets good.

The only question is: which direction is "less wrong"? Calculus answers that. Specifically, one idea: the derivative, which tells you how much an output changes when you change an input a tiny bit.

You won't need to solve pages of equations. Libraries like PyTorch calculate derivatives automatically. But understanding what they mean is what turns "the model trained" from magic into something you can reason about and debug.

The idea: slope

Imagine driving. Your speed is how fast your distance changes over time. If you travel 60 km in one hour, your average speed is 60 km/h. Speed is a rate of change, and that's all a derivative is.

On a graph, the rate of change is the slope: how steep the line is.

  • A positive slope means going up: increase the input and the output increases.
  • A negative slope means going down.
  • A slope of zero means flat: you're at a peak or the bottom of a valley.

For a straight line, the slope is the same everywhere. For a curve, the slope changes from point to point, and the derivative gives the slope at one exact point.

The derivative

Take the curve f(x) = x². What's its slope at x = 3? Move a tiny step h and see how much f changes:

def f(x):
    return x ** 2

h = 0.000001
slope = (f(3 + h) - f(3)) / h
print(round(slope, 4))    # 6.0

The slope at x = 3 is 6. That calculation, change in output divided by a tiny change in input, is the derivative. It's called a numerical derivative, and it's a great way to check your understanding.

Calculus gives shortcuts so you don't have to compute it numerically. The derivative of x² is 2x, and at x = 3 that's 6, matching our code.

The few rules you need

FunctionDerivativeExample
A constant, c0The derivative of 5 is 0
x1
xⁿ (power rule)n·xⁿ⁻¹x² → 2x, x³ → 3x²
c · f(x)c · f′(x)3x² → 6x
f(x) + g(x)f′(x) + g′(x)x² + 3x → 2x + 3

f′(x), read "f prime of x", means the derivative of f. You'll also see it written as df/dx.

The chain rule: functions inside functions

Models are built from functions nested inside other functions. A neural network is layer inside layer inside layer. The chain rule says how to take the derivative of nested functions: multiply the derivatives of each layer together.

For f(x) = (3x + 1)², the outer function is "square it" and the inner is 3x + 1:

  • Derivative of the outer, evaluated at the inner: 2(3x + 1)
  • Derivative of the inner: 3
  • Multiply: f′(x) = 2(3x + 1) × 3 = 6(3x + 1)

Intuitively: if the inner part changes 3 times as fast as x, and the outer part changes 2(3x + 1) times as fast as the inner part, the total rate is their product. Like gears: if gear A turns gear B three times as fast, and B turns C twice as fast, then C turns six times as fast as A.

This is backpropagation. Training a neural network applies the chain rule backwards through every layer, from the error at the output to every weight in the network. That's the whole algorithm in one sentence.

Partial derivatives and the gradient

Real models have many weights, not one input. A partial derivative asks: how does the output change if I nudge just one input, keeping all the others fixed?

For f(w, b) = w² + 3b:

  • The partial derivative with respect to w is 2w (treat b as a constant).
  • The partial derivative with respect to b is 3.

Collect all the partial derivatives into a vector and you have the gradient. The gradient points in the direction of steepest increase. So to decrease something, you step in the opposite direction. Hold that thought.

Putting it together: the slope of a model's error

Here's a tiny model, prediction = w × x, with three training examples where the true rule is y = 2x:

import numpy as np

x = np.array([1, 2, 3])
y = np.array([2, 4, 6])

def loss(w):
    return np.mean((w * x - y) ** 2)    # mean squared error

def gradient(w):
    return np.mean(2 * (w * x - y) * x)  # derivative of the loss with respect to w

print(loss(1.0), gradient(1.0))    # 4.67  -9.33
print(loss(2.0), gradient(2.0))    # 0.0  0.0

The loss measures how wrong the model is. At w = 1, the loss is 4.67, and the gradient is −9.33: negative, meaning "increasing w will reduce the loss". At w = 2, the right answer, the loss is 0 and the gradient is 0: we're at the bottom of the valley.

The loss plotted against the weight w is a U-shaped curve with its lowest point at w = 2. Tangent lines show a slope of −9.33 at w = 1, meaning increase w, and +9.33 at w = 3, meaning decrease w.

The sign of the slope tells you which way to move w, and its size tells you how far you are from the bottom.

The gradient was found with the chain rule: the loss squares the error (outer, derivative 2 × error), and the error depends on w (inner, derivative x). You can confirm it numerically:

h = 0.000001
print(round((loss(1 + h) - loss(1)) / h, 3))    # -9.333

This is how every model learns: compute the loss, compute its gradient with respect to each weight, step each weight a little in the downhill direction, repeat. That algorithm is called gradient descent, and it's the next lesson.

What you can skip

Integrals, limits proofs, trigonometric derivatives and most of a calculus textbook aren't needed for applied machine learning. Frameworks such as PyTorch compute gradients automatically ("autograd"), so in practice you rarely differentiate by hand. Understanding what a gradient tells you is what matters.

Key takeaways

  • A derivative is a rate of change: the slope of a function at a point.
  • You can approximate it numerically: (f(x + h) − f(x)) / h for a tiny h.
  • The chain rule multiplies derivatives through nested functions; backpropagation is the chain rule applied to a network.
  • The gradient is the vector of partial derivatives and points uphill; models learn by stepping downhill.
  • At the minimum of the loss, the gradient is zero.

Practice

  1. Using the power rule, find the derivative of f(x) = 4x³ + 2x − 7.
Show the answer

f′(x) = 12x² + 2. The 4x³ becomes 4 × 3x² = 12x², 2x becomes 2, and the constant −7 becomes 0.

  1. Check your answer numerically at x = 2. The formula gives 12 × 4 + 2 = 50.
Show the answer
f = lambda x: 4 * x**3 + 2 * x - 7
h = 0.000001
print(round((f(2 + h) - f(2)) / h, 3))    # 50.0
  1. Use the chain rule to find the derivative of f(x) = (2x − 5)².
Show the answer

Outer: 2(2x − 5). Inner: 2. Multiply: f′(x) = 4(2x − 5) = 8x − 20.

  1. In the example above, the gradient at w = 3 is positive. What does that tell you, and which way should w move?
Show the answer
print(gradient(3.0))    # 9.33...

A positive gradient means the loss increases as w increases, so w should move down, towards 2. Gradient descent always moves against the gradient.

Interview questions

Why is calculus needed in machine learning?

Training means minimising a loss function. Derivatives, and gradients for many parameters, show how the loss changes as each parameter changes, which tells optimisation algorithms like gradient descent which direction to update the parameters.

What is a gradient?

The vector of partial derivatives of a function with respect to each of its inputs. It points in the direction of steepest increase, and its size shows how steep that increase is. Its negative points in the direction of steepest decrease.

How does the chain rule relate to backpropagation?

A neural network is a composition of functions (layers). Backpropagation uses the chain rule to compute the gradient of the loss with respect to every weight efficiently, by propagating derivatives backwards from the output layer and reusing intermediate results.

What does a gradient of zero mean?

The function is flat at that point: a minimum, a maximum or a saddle point. In training, a gradient near zero means updates become tiny; ideally the model has reached a minimum of the loss, but it may also be stuck on a plateau.

Go deeper

This lesson is an overview. The calculus course builds each idea step by step, starting from what is calculus?. For the ideas used most in this course, see what is a derivative?, derivative rules, the chain rule, the derivative of the sigmoid and numerical derivatives with Python. For optimising under a rule, the maths behind support vector machines, see Lagrange multipliers explained.

What to learn next

  1. Watch a model learn in gradient descent explained, with Python code.
  2. Review vectors and dot products in linear algebra for machine learning.