Machine Learning · 19 of 20

Backpropagation tutorial

Computes how much every network weight contributed to an error, then updates it. Learn the concept, implement it from scratch, and apply it with PyTorch autograd.

Category
Neural network training
Core idea
∂L/∂W⁽ˡ⁾ = δ⁽ˡ⁾(a⁽ˡ⁻¹⁾)ᵀ
Typical use
Training neural networks for vision, language, audio, and forecasting.
Practical tool
PyTorch autograd

What is Backpropagation?

Backpropagation is a neural network training technique. Computes how much every network weight contributed to an error, then updates it. Its central idea is summarized by ∂L/∂W⁽ˡ⁾ = δ⁽ˡ⁾(a⁽ˡ⁻¹⁾)ᵀ.

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with PyTorch autograd and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when Backpropagation is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with PyTorch autograd and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python functions, NumPy arrays, and basic descriptive statistics.
  • A clear distinction between training data, validation data, and untouched test data.
  • Familiarity with features, targets, preprocessing, and task-appropriate evaluation metrics.
LanguagePython 3
Primary libraryPyTorch autograd
Learning modeFrom scratch + library

How Backpropagation works

  1. 1

    Input

    A forward-pass prediction, its target, and the network’s intermediate activations.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Propagate loss gradients backward through each layer with the chain rule.

  4. 4

    Output

    Updated weights that make the next prediction slightly more accurate.

  5. 5

    Validate

    Track gradient norms by layer to detect vanishing, exploding, or disconnected gradients.

Formula and intuition

∂L/∂W⁽ˡ⁾ = δ⁽ˡ⁾(a⁽ˡ⁻¹⁾)ᵀ

L is the loss; δ⁽ˡ⁾ is the error signal at layer l, and a⁽ˡ⁻¹⁾ contains the preceding layer’s activations.

The notation captures the main operation or complexity statement behind Backpropagation. Read it together with the symbol key above and the step-by-step process in this guide.

When to use Backpropagation

Training neural networks for vision, language, audio, and forecasting.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

Backpropagation from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(size=(128, 2))
y = (X[:, 0] * X[:, 1] > 0).astype(float)[:, None]
W1 = rng.normal(0, .3, (2, 4))
W2 = rng.normal(0, .3, (4, 1))
learning_rate = .25

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

for _ in range(600):
    hidden = sigmoid(X @ W1)          # forward pass
    prediction = sigmoid(hidden @ W2)
    output_gradient = (prediction - y) * prediction * (1 - prediction)
    hidden_gradient = (output_gradient @ W2.T) * hidden * (1 - hidden)
    W2 -= learning_rate * hidden.T @ output_gradient / len(X)
    W1 -= learning_rate * X.T @ hidden_gradient / len(X)
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build Backpropagation with PyTorch autograd

PyTorch autograd records tensor operations and applies the chain rule to populate every parameter gradient.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install torch
  1. Prepare the data.A forward-pass prediction, its target, and the network’s intermediate activations. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Propagate loss gradients backward through each layer with the chain rule.
  4. Inspect the result.Updated weights that make the next prediction slightly more accurate. Then apply the evaluation checks in the next section.
PythonPyTorch autograd workflow
import torch
from torch import nn

torch.manual_seed(7)
X = torch.randn(64, 4)
y = torch.randn(64, 1)
model = nn.Sequential(nn.Linear(4, 8), nn.Tanh(), nn.Linear(8, 1))
optimizer = torch.optim.SGD(model.parameters(), lr=0.05)

optimizer.zero_grad()
prediction = model(X)
loss = nn.functional.mse_loss(prediction, y)
loss.backward()
for name, parameter in model.named_parameters():
    print(name, "gradient norm:", parameter.grad.norm().item())
optimizer.step()
print("loss before update:", loss.item())

API details and version-specific options: official PyTorch autograd reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Track gradient norms by layer to detect vanishing, exploding, or disconnected gradients.
  • Use a numerical gradient check for custom operations on small test inputs.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • Forgetting optimizer.zero_grad accumulates gradients across steps.
  • In-place operations can invalidate values needed for backward computation.
  • Calling detach or converting tensors to NumPy breaks the computation graph.

Before using Backpropagation in a project

  • Define the prediction or discovery objective before selecting the algorithm.
  • Split data before fitting preprocessing and tune only inside cross-validation.
  • Record data versions, random seeds, features, hyperparameters, and evaluation metrics.
  • Compare against a simple baseline and inspect errors by meaningful subgroups.
  • Monitor input drift and real-world performance after deployment.

Official documentation and next steps

Primary software reference PyTorch autograd

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See Backpropagation in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →