Backpropagation in Neural Networks


Backpropagation in Neural Networks

Maria
Today we’re unpacking backpropagation: an algorithm for computing gradients automatically. It’s closely associated with neural networks, but the central idea is much more general. We’ll start with what gradients mean, build up the computation-graph view, and then see how backpropagation applies to both a simple loss and a neural network.

Michael
Let’s begin with the practical motivation. Suppose we have a neural network and a loss for one training example. To use stochastic gradient descent, we need the gradient of that loss with respect to every parameter—say, the matrices in several layers and the final weight vector. We could differentiate the whole expression by hand, but as the network grows, that becomes tedious.

Maria
The network’s computation can be described in stages. Start with a feature vector, multiply by a weight matrix, and apply an activation function. Repeat that process through the layers, then take a dot product with a final weight vector to get a prediction. Subtract the target and square the result to get the loss.

Michael
So instead of treating that entire formula as one giant object, we can break it into intermediate calculations. That’s the idea behind a computation graph: a directed acyclic graph whose final node represents the expression we care about, and whose other nodes represent intermediate subexpressions.

Maria
Exactly. A simple example is c equals a plus b. We draw a and b as inputs to a box that adds them, and label the output c. The graph makes the structure visible, and later it will let us calculate how changes in the inputs affect the final output.

Michael
If we increase a by a tiny amount, epsilon, then c increases by exactly epsilon. So the gradient of c with respect to a is one. The same reasoning applies to b: a small increase in b changes c by the same amount, so that gradient is also one.

Maria
Now change the operation to c equals a times b. If a increases by epsilon, the output becomes a times b plus b times epsilon. The amount of change is b times epsilon, so the gradient of c with respect to a is b. By symmetry, the gradient with respect to b is a.

Michael
Those are local derivatives written as little rules for graph edges. A few more rules give us useful building blocks: for a plus b, the derivatives are one and one; for a minus b, they’re one and minus one; and for a times b, they’re b and a.

Maria
For the square, if c equals a squared, the derivative with respect to a is two times a. For the maximum of a and b, the derivative with respect to a is one when a is the larger input and zero when b is larger. The derivative with respect to b works the same way in reverse.

Michael
There’s also the logistic, or sigmoid, function. If its output is sigma of a, its derivative can be written as sigma of a times one minus sigma of a. That expression has a useful sanity check: as the input becomes very large or very negative, the sigmoid approaches one or zero, and its derivative approaches zero.

Maria
The key is that these small rules can be composed. Consider b equals a squared, followed by c equals b squared. The derivative of b with respect to a is two a, and the derivative of c with respect to b is two b. By the chain rule, the derivative of c with respect to a is their product: two b times two a.

Michael
And since b equals a squared, that product becomes four a cubed. Because c is a to the fourth, this agrees with the ordinary power rule. In a computation graph, the chain rule becomes a simple instruction: multiply the local gradients along the path.

Maria
Let’s apply that to hinge loss for linear classification. First take the dot product of the weight vector w and the feature vector phi of x to get a score. Multiply that score by the label y to get the margin, subtract the margin from one, and take the maximum of that result and zero.

Michael
To find the gradient with respect to w, trace the graph backward from the loss. For the maximum, the derivative follows the first input when one minus the margin is greater than zero, which is the same as saying the margin is less than one. The subtraction contributes minus one, and multiplying the score by y contributes y.

Maria
At the dot product, the gradient with respect to w contributes the feature vector phi of x. Multiplying all those pieces gives the hinge-loss gradient: minus y times phi of x when the margin is less than one, and zero when the margin is greater than one. The graph lets us assemble the answer one local derivative at a time.

Michael
Now let’s use a two-layer neural network. Multiply the feature vector x by a weight matrix V, apply an activation function to get the hidden vector h, and take the dot product of h with the final weight vector w. That gives the score. Subtract the target y to get the residual, then square the residual for the loss.

Maria
One useful feature of the graph is that it separates the loss from the way we produce a score. The part that squares the residual is the squared-loss calculation. The part that produces the score could be a linear predictor, this two-layer network, or a deeper network.

Michael
For the gradient with respect to w, start at the squared loss. Its derivative contributes two times the residual. The residual changes one-for-one with the score, and the score’s derivative with respect to w is h. So the gradient is two times the residual times h.

Maria
That resembles the linear-regression gradient: two times the residual times the feature vector. Here, h plays the role of the features seen by the final weight vector. That’s a useful check that the network’s last layer behaves like a linear predictor on its hidden representation.

Michael
For the gradient with respect to V, we keep tracing backward. The squared-loss and residual parts are shared with the path we just used, so they contribute the same factor, two times the residual. Then the score contributes w, because the score is the dot product of w and h.

Maria
If the activation is the sigmoid applied element by element, its derivative for each hidden unit is h times one minus h. That’s an element-wise product with w. Finally, the matrix multiplication by V contributes the input x, giving an outer product.

Michael
Putting those pieces together, the gradient with respect to V is two times the residual, multiplied element-wise by w and by h times one minus h, and then multiplied by x transposed. The exact arrangement reflects the dimensions of the vectors and matrix, but the principle is the same: combine the local derivatives along the backward route.

Maria
So far, we’ve been using graphs to explain the calculation. Backpropagation turns that explanation into a general procedure. It has two phases: a forward pass that evaluates the graph, and a backward pass that computes how the final loss changes with respect to values throughout the graph.

Michael
Let’s walk through a numerical example using squared loss for linear regression. Take w to be the vector three, one, and x to be the vector one, two. Their dot product is three plus two, so the score is five. If the target is two, the residual is five minus two, or three, and the squared loss is nine.

Maria
That’s the forward pass: we calculate and remember the values at each step—the score is five, the residual is three, and the loss is nine. The backward pass starts at the loss, where the gradient of the loss with respect to itself is one.

Michael
The derivative of the square with respect to the residual is two times the residual, which is six. The residual changes one-for-one with the score, so the backward value at the score is also six. And the score is the dot product of w and x, so its gradient with respect to w is x.

Maria
Multiplying that backward value, six, by the feature vector one, two gives the gradient with respect to w: six, twelve. That’s the gradient evaluated at these particular numbers. The forward pass supplied the intermediate values, and the backward pass used them to compute the gradient.

Michael
In a general graph, if multiple paths lead back to the same quantity, their contributions are combined. That’s how the procedure handles shared subexpressions as well as longer chains of operations. The same forward-and-backward approach works for much more complicated graphs, including deep neural networks.

Maria
Once we have the gradients, stochastic gradient descent can use them to update the model’s parameters. But getting gradients doesn’t by itself guarantee that optimization will be easy. For a linear predictor with a convex training loss, an appropriate step size can lead gradient descent to a global minimum.

Michael
Neural-network training loss is generally non-convex, so there’s no comparable guarantee that gradient descent will reach a global minimum. The optimization can be difficult in principle, even though neural networks often train successfully in practice. Getting them to train well involves choices and adjustments—something the source compares to learning to drive a stick shift.

Maria
Initialization is one important choice. With a non-convex loss, different starting points can lead the optimization to different outcomes. Initializing the weight matrix at exactly zero can make all of its rows identical, which isn’t useful, so a common approach is to start near zero with random noise. Pre-training is another possible way to initialize a network.

Michael
Another approach is over-parameterization: giving the network more hidden units than it may seem to need. Some units might not turn out to be useful, but having more units provides more chances for the network to learn useful patterns from the data.

Maria
People also use adaptive step sizes. Basic stochastic gradient descent uses a single step size, while methods such as AdaGrad or Adam adjust the step size separately for each parameter. That can help determine how quickly to move in different parameter directions.

Michael
A broad practical concern is keeping gradients from vanishing or exploding. If gradients become too small, updates may be too small to make progress. If they become too large, updates can cause the optimization to oscillate or diverge. Initialization, step sizes, and network architecture all play a role in managing this.

Maria
Let’s bring the ideas together. Computation graphs represent calculations as compositions of simple operations, and local derivative rules tell us how each operation responds to its inputs. The chain rule lets us combine those local derivatives, and backpropagation automates that process with a forward pass followed by a backward pass.

Michael
And although we’ve emphasized neural networks, computation graphs and backpropagation apply much more broadly. Their generality makes it easier to compute gradients for different functions, models, and loss functions—and supports the broader idea of differential programming. That’s why this way of thinking is useful both for understanding gradients and for building new models.

Ask anything
We've read this whole study set, so questions about it get the best answers.