Calculating the gradients of each weight efficiently is done through a process known as backpropagation.
Backpropagation works by computing the gradient of the loss with respect to each weight by the chain rule, moving backwards through the network. The gradients are usually stored as they are computed, which allows for efficient computation.
Here is a more detailed illustration:
Let's consider a neural network with L layers and the lth layer has w[l] as its weight. The forward propagation can be defined as a[l]=f(z[l])= where a[l] is the activation of the lth layer and f() is the activation function.
-
Compute the last layer's gradient: The gradient of the loss function with respect to the output layer is often simple to compute. For example, if the loss function is the mean squared error, the gradient is just (y−t).
-
Propagate the gradient backwards: For each layer, starting from the last hidden layer and going backwards to the input, we compute the gradients with respect to the weights and biases. This is done by the chain rule of differentiation. For example, the gradient of the loss function with respect to the weights in the lth layer is computed as:
The key feature of backpropagation is that the gradients at each layer are computed from the gradients at the next layer, which makes it very efficient. Instead of having to compute the gradient of the loss with respect to each weight independently, we can compute them all at once.