Skip to main content
LearnMLAcademy
Advanced10 min read

Backpropagation and Automatic Differentiation

Derive backpropagation step by step using the calculus chain rule in Python, with tensor walkthroughs, gradient calculations, and PyTorch practice.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Beginner Lesson

Backpropagation: How a Neural Network Learns From One Mistake

A neural network may contain millions of adjustable weights. After it makes a wrong prediction, backpropagation calculates how much each weight contributed to that mistake. An optimizer then uses those calculations to make a small correction. This lesson follows both journeys—forward to the prediction and backward to the weights—using one complete numerical example.

The Learning Problem

Suppose a network predicts 2, but the correct answer is 4. Knowing the final error is not enough. The network must answer three more questions:

1

Which weights?

Which connections helped produce the wrong answer?

2

Which direction?

Should each weight become larger or smaller?

3

How sensitive?

Would a tiny change have a large or small effect on the loss?

Backpropagation answers those questions efficiently. It starts at the final loss and works backward through the calculations. At every step it uses a derivative—a number that describes how sensitive one value is to a small change in another.

First Journey: The Forward Pass

The forward pass is simply the calculation that makes a prediction. Input values enter the network, each layer performs its weighted calculations and activations, and the output layer produces the final answer. The loss function then compares that answer with the target.

FORWARD PASS: values move rightx1x2x3h1h2h3ŷLOSSLInput valuesHidden calculationsPrediction → Loss
Figure 1: Input values travel through weighted calculations to create a prediction and a loss.

input → weighted sums → activations → prediction → loss

Second Journey: The Backward Pass

The backward pass begins only after the loss is known. It asks how the loss would change if each earlier value changed slightly. This sensitivity is called a gradient. The information moves from the loss toward the output layer, hidden layers and earlier weights.

BACKWARD PASS: error responsibility moves leftx1x2x3h1h2h3ŷLOSSLInput valuesHidden calculationsPrediction → Loss
Figure 2: Starting from the loss, the chain rule calculates how much each earlier weight affected the mistake.

loss → output gradients → hidden gradients → weight gradients

The arrows do not mean that the training examples themselves run backward. Only derivative information moves backward. The actual weight change happens later, when the optimizer applies the learning rate.

Important Terms Before the Calculation

Weight (w)

An adjustable number that controls how strongly an input affects the next calculation.

Bias (b)

An adjustable offset added after the weighted input.

Loss (L)

The numerical penalty for the current prediction.

Derivative

The sensitivity of one value to a tiny change in another value.

Gradient

The set of derivatives for all trainable weights and biases.

Learning rate (η)

A small multiplier that controls the size of an optimizer update.

One Complete Numerical Example

We will train the smallest useful model: one input, one weight and one bias. It predicts with ŷ = wx + b. To make differentiation simple, we use the squared loss L = ½(ŷ − y)². The ½ is a teaching convenience: differentiating the square introduces a factor of 2, and ½×2 becomes 1.

SymbolValueWhere it comes fromCan training change it?
Input x2A manually chosen training-example inputNo
Target y4The known answer paired with this exampleNo
Weight w0.5A manually chosen starting parameter for the demonstrationYes
Bias b1A manually chosen starting parameter for the demonstrationYes
Learning rate η0.1A developer-chosen update-size hyperparameterNo; the optimizer uses it
x = 2known inputw = 0.5trainableb = 1trainablew × x0.5 × 2 = 1+ b1 + 1 = 2ŷ = 2predictiony = 4targetL = 2½(ŷ−y)²backward calculation follows these dependencies in reverse
Figure 3: A computation graph stores small operations and their dependencies; automatic differentiation applies derivative rules to this graph.

2D Computation Graph: Forward Activations vs. Backward Chain-Rule Gradients

Forward values compute the prediction and loss; backward partial derivatives compute each parameter’s exact responsibility.

Forward Pass (→)Backward Gradients (←)
Inputs & Weightsx = 2, w = 0.5Linear Productz = w·x = 1.0Prediction (b=1)ŷ = z + b = 2.0Loss (Target y=4)L = ½(ŷ−y)² = 2.0∂L/∂L = 11. Output Gradient∂L/∂ŷ = ŷ − y= 2 − 4 = −2.02. Chain Rule at (+)∂L/∂z = (∂L/∂ŷ)·(∂ŷ/∂z)= −2.0 × 1 = −2.03. Weight Gradient∂L/∂w = (∂L/∂z)·x= −2.0 × 2 = −4.04. SGD Updatew ← w − η·(∂L/∂w)0.5 − 0.1(−4) = 0.9
Notice how backpropagation never recomputes values from scratch: each step reuses the forward activation (x=2) and the downstream gradient (-2) using local multiplication.
1

Calculate the prediction

Multiply the input by the current weight, then add the bias. The model predicts 2.

ŷ = wx + b = (0.5 × 2) + 1 = 2

2

Calculate the loss

The target is 4, so the prediction is too small. The current loss is 2.

L = ½(ŷ − y)² = ½(2 − 4)² = ½ × 4 = 2

3

Find how loss changes with the prediction

The symbol ∂ means “change in.” This derivative is negative, telling us that increasing the prediction would reduce the loss.

∂L/∂ŷ = ŷ − y = 2 − 4 = −2

4

Follow the chain back to the weight

Because ŷ = wx + b, the prediction changes by x when w changes, so ∂ŷ/∂w = x = 2. Multiplying the connected derivatives is the chain rule.

∂L/∂w = (∂L/∂ŷ)(∂ŷ/∂w) = (−2)(x) = (−2)(2) = −4

5

Find the bias gradient

Adding one unit to the bias adds one unit to the prediction, so ∂ŷ/∂b = 1.

∂L/∂b = (∂L/∂ŷ)(∂ŷ/∂b) = (−2)(1) = −2

6

Let the optimizer update the parameters

Gradient descent subtracts the learning rate multiplied by each gradient. Subtracting a negative number makes both parameters larger.

w_new = 0.5 − 0.1(−4) = 0.9 b_new = 1 − 0.1(−2) = 1.2

7

Check the next prediction

The loss fell from 2 to 0.5. One update did not finish training, but it moved the model in the correct direction.

ŷ_new = (0.9 × 2) + 1.2 = 3 L_new = ½(3 − 4)² = 0.5

How the Chain Rule Connects the Steps

The loss does not use w directly. It depends on the prediction ŷ, and ŷ depends on w. The chain rule connects those dependencies:

∂L/∂w = ∂L/∂ŷ × ∂ŷ/∂w

How loss reacts to prediction
× How prediction reacts to weight
= How loss reacts to weight

Why multiply? Imagine a tiny increase of 0.01 in w. Because ∂ŷ/∂w=2, the prediction changes by approximately 2×0.01=0.02. Because ∂L/∂ŷ=−2, that prediction change alters loss by approximately −2×0.02=−0.04. Combining the two effects gives −2×2×0.01=−0.04, so the sensitivity per one unit of w is −4.

A real network repeats this idea through many connected operations. Backpropagation reuses intermediate results, making it far more efficient than perturbing and recalculating every parameter separately.

Do Not Confuse Backpropagation, Autodiff, Gradient Descent and the Optimizer

These ideas cooperate, but each has a different responsibility.

TermWhat it meansIts job during training
Computation graphA record of operations and dependenciesRemembers how the loss was produced
Automatic differentiationA framework mechanism that applies derivative rules to recorded operationsEvaluates derivatives without hand-coding each one
BackpropagationAn efficient reverse pass that sends sensitivity through the networkComputes a gradient for each trainable parameter
Gradient descentThe basic principle of moving parameters opposite the gradientExplains the direction used to reduce a local objective
OptimizerThe actual update algorithm, such as SGD or AdamCombines gradients, learning rates and possible state to change parameters

What the Framework Does for You

PyTorch and TensorFlow record the forward operations and compute the gradients automatically. The mathematics is still the same as the hand calculation.

one_step.py
import torch

x = torch.tensor(2.0)
y = torch.tensor(4.0)
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)

y_hat = w * x + b          # forward pass
loss = 0.5 * (y_hat - y)**2
loss.backward()             # backward pass

print(w.grad.item())        # -4.0
print(b.grad.item())        # -2.0

with torch.no_grad():
    w -= 0.1 * w.grad
    b -= 0.1 * b.grad

new_y_hat = w * x + b
new_loss = 0.5 * (new_y_hat - y)**2
print(w.item(), b.item())   # about 0.9, 1.2
print(new_y_hat.item())     # about 3.0
print(new_loss.item())      # about 0.5

# PyTorch adds future backward results to .grad, so clear them before
# another independent training step.
w.grad.zero_()
b.grad.zero_()

Read the PyTorch Example Line by Line

requires_grad=True

Marks w and b as trainable values whose gradients should be stored.

y_hat = w * x + b

Runs the same forward prediction calculated by hand.

loss = 0.5 * ...

Creates one scalar objective from prediction and target.

loss.backward()

Traverses the recorded operations backward and accumulates gradients in w.grad and b.grad.

with torch.no_grad()

Changes parameters without recording the update itself as part of the next gradient graph.

w -= 0.1 * w.grad

Performs the explicit gradient-descent update using the chosen learning rate 0.1.

new_loss

Runs a second forward calculation and verifies that loss fell from 2 to about 0.5.

grad.zero_()

Clears accumulated gradients before another independent step; optimizers commonly provide zero_grad() for all parameters.

Common Mistakes and How to Diagnose Them

Forgetting to clear gradients

Many frameworks accumulate gradients. Clear them before the next backward pass unless accumulation is intentional.

Updating during validation

Validation measures the model; it must not call backward or change parameters.

Detached computation

Converting a needed tensor to a plain number or detaching it can break the path from loss to weight.

Exploding or vanishing gradients

Repeated large derivatives can explode; repeated small derivatives can vanish. Inspect gradient norms.

Wrong loss-output pairing

A mathematically valid gradient can still train the wrong objective. Verify targets, logits and activation expectations.

Confusing backprop with the update

Backprop calculates gradients. SGD, Adam or another optimizer performs the update.

When Backpropagation Is—and Is Not—the Right Tool

SituationGuidanceWhy
Differentiable neural networkUse backpropagationIt efficiently supplies gradients for millions of parameters
Sequence modelUse backpropagation through time or an equivalent graphThe repeated operations are unrolled through sequence positions
Non-differentiable decision or simulatorConsider a smooth surrogate, policy gradient, search or gradient-free optimizationOrdinary derivatives may not exist or may not reach the parameters
Need only inferenceDo not run backwardPrediction needs the forward pass only, saving memory and time

The complete idea in five lines

  1. A forward pass creates a prediction and a loss.
  2. The computation graph records which operations produced that loss.
  3. Backpropagation follows the graph backward and applies the chain rule.
  4. The result is one gradient for every trainable parameter.
  5. An optimizer uses those gradients and a learning rate to update the parameters.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Backpropagation and Automatic Differentiation"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • The forward pass records how inputs and parameters produce loss.
  • Backpropagation applies the chain rule in reverse.
  • Automatic differentiation evaluates derivative rules on the computation graph.
  • Gradients measure sensitivity; the optimizer decides the update.
  • Framework gradients can accumulate and must be cleared deliberately.
  • Gradient checks and tiny examples expose broken backward paths.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What does backpropagation compute?
Question 2 of 5numerical/formula
If y=wx, L=(y-t)², what is dL/dw?
Question 3 of 5interpretation
A positive gradient means what for a small increase in that parameter?
Question 4 of 5conceptual
How is an optimizer different from backpropagation?
Question 5 of 5debugging/diagnostic
Why clear gradients before the next ordinary batch?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What does backpropagation compute?▼

Correct Answer: Gradients of loss with respect to trainable parameters

It applies the chain rule in reverse through recorded operations to obtain parameter sensitivities.

2If y=wx, L=(y-t)², what is dL/dw?▼

Correct Answer: 2(y-t)x

dL/dy=2(y-t) and dy/dw=x, so the chain rule gives 2(y-t)x.

3A positive gradient means what for a small increase in that parameter?▼

Correct Answer: Loss locally tends to increase

A positive local derivative says increasing the parameter increases loss nearby; gradient descent therefore moves it downward.

4How is an optimizer different from backpropagation?▼

Correct Answer: The optimizer converts gradients into parameter updates

Backpropagation supplies gradients; SGD, Adam, and other optimizers decide the actual update.

5Why clear gradients before the next ordinary batch?▼

Correct Answer: Frameworks commonly accumulate them

Without clearing, the new backward pass adds to stored gradients and updates from unintended accumulated information.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next