What is backpropagation?
Backpropagation is the reverse-mode automatic differentiation algorithm used to compute exact gradients of a loss function with respect to every weight and bias in a neural network. After a forward pass caches intermediate activations, backpropagation applies the chain rule from output to input in time proportional to a single forward pass. Optimization algorithms such as SGD or Adam then use these gradients to update parameters and minimize the loss.
Study Card: What is Backpropagation?
Direct Answer
Backpropagation (short for backward propagation of errors) is an algorithm that computes the gradient of a scalar loss function with respect to all trainable parameters in a neural network. It is a specific application of reverse-mode automatic differentiation using the chain rule of calculus.
For layer with pre-activation and activation , define the local error signal . Backpropagation propagates this signal backward from layer down to layer :
Computing gradients for all parameters takes roughly the same asymptotic compute as one forward pass (), while storing intermediate activations requires memory unless activation checkpointing is used. Optimizers (SGD, Adam) then use these gradients to update weights.
Key Terms
- Loss Function: Scalar objective quantifying the mismatch between predictions and targets.
- Gradient: Vector of partial derivatives indicating the direction and magnitude of steepest increase of the loss.
- Chain Rule: Calculus rule for differentiating composite functions, allowing local derivatives at each operation to be reused efficiently across all upstream parameters.
- Forward Pass: Evaluating the network from input to loss while caching intermediate tensors needed for the backward pass.
- Optimization Algorithm: Update rule (such as SGD or Adam) that steps parameters opposite the gradient to minimize .
Example
Consider a two-layer network predicting house prices from features like square footage and location. During the forward pass, inputs travel through hidden activations to produce a predicted price, and MSE compares it to the true price. If the prediction is too high, backpropagation computes , propagates that error signal backward across the output weights and hidden-layer activation derivatives, and produces parameter gradients and . Gradient descent then adjusts each weight proportionally to reduce the error on the next step.
Code Implementation
import numpy as np
import tensorflow as tf
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
# 1. Automatic differentiation with TensorFlow GradientTape
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(3,)),
tf.keras.layers.Dense(2, activation="sigmoid"),
tf.keras.layers.Dense(1),
])
loss_fn = tf.keras.losses.MeanSquaredError()
X = tf.constant([[1.0, 2.0, 3.0]])
y_true = tf.constant([[4.0]])
with tf.GradientTape() as tape:
y_pred = model(X)
loss_value = loss_fn(y_true, y_pred)
gradients = tape.gradient(loss_value, model.trainable_variables)
print("TensorFlow autograd gradients:")
for var, grad in zip(model.trainable_variables, gradients):
print(f"{var.name}:\n{grad.numpy()}\n")
# 2. Manual backpropagation through both layers in NumPy
w1 = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) # shape (3, 2)
b1 = np.array([0.1, 0.2]) # shape (2,)
w2 = np.array([[0.7], [0.8]]) # shape (2, 1)
b2 = np.array([0.3]) # shape (1,)
x_np = np.array([1.0, 2.0, 3.0])
y_np = np.array([4.0])
# Forward pass
z1 = x_np @ w1 + b1
a1 = sigmoid(z1)
z2 = a1 @ w2 + b2
y_pred_np = z2
loss = np.mean((y_pred_np - y_np) ** 2)
# Backward pass (output layer -> hidden layer)
dL_dz2 = 2.0 * (y_pred_np - y_np) # shape (1,)
dL_dw2 = np.outer(a1, dL_dz2) # shape (2, 1)
dL_db2 = dL_dz2 # shape (1,)
dL_da1 = dL_dz2 @ w2.T # shape (2,)
dL_dz1 = dL_da1 * (a1 * (1.0 - a1)) # sigmoid derivative
dL_dw1 = np.outer(x_np, dL_dz1) # shape (3, 2)
dL_db1 = dL_dz1 # shape (2,)
print("Manual NumPy backpropagation:")
print("dL/dw2:\n", dL_dw2)
print("dL/db2:", dL_db2)
print("dL/dw1:\n", dL_dw1)
print("dL/db1:", dL_db1)
Related Concepts
- Gradient Descent: Uses backpropagated gradients to iteratively update network weights ().
- Computational Graphs: Directed acyclic graphs representing tensor operations so frameworks can traverse dependencies in reverse topological order.
- Reverse-Mode vs. Forward-Mode Autodiff: Reverse-mode is efficient when there are many parameters and one scalar loss; forward-mode is preferable when outputs outnumber inputs.
- Activation Checkpointing: Trades extra forward recomputation for reduced activation memory in very deep networks.
- Vanishing/Exploding Gradients: Numerical instability across long chains of layer Jacobians during backpropagation.