Neural Network Gradients
Backpropagation and Training Neural Networks
Why neural networks need an efficient gradient method
A neural network can be viewed as a compound function: its layers apply weights, sums, and nonlinear activation functions in sequence to produce an output and, ultimately, a loss. Training requires finding how each parameter affects that loss.
For a simple model, its gradient may be easy to derive directly. In a network with many layers, however, a weight deep inside the network influences later computations before affecting the final loss. The gradient must account for this whole chain of dependencies.
Two straightforward approaches are possible, but only one scales well:
Numerical differentiation approximates each gradient by perturbing a parameter and measuring the resulting change in the function.
Analytical differentiation derives gradients from formulas, but doing so by hand becomes cumbersome and error-prone for large networks.
Backpropagation applies the chain rule systematically to calculate analytical gradients through a network.
Numerical gradients
The derivative of a function can be approximated by measuring how much its output changes when its input is shifted by a small amount. For a small increment δ, the approximation is
This method is simple and widely applicable. It requires the function to be defined at the points being compared, and it works best when a small change in the input produces a reasonably smooth change in the function.
Its main drawback is computational cost. To estimate the gradient for every weight, the method must perturb each weight separately and evaluate the network again. If a network has many parameters, this means many full network evaluations, making the approach impractical for training large neural networks.
Analytical gradients and the chain rule
When a function is simple enough, deriving its gradient analytically is more efficient: the result is a formula that can be evaluated directly. However, manually deriving gradients for a large compound function involves substantial algebra and creates many opportunities for mistakes.
Backpropagation automates the repeated application of the chain rule. The central idea is that derivatives multiply along a sequence of dependent operations.
If y depends on u, and u depends on x, then
For a composition f(g(x)), the same rule is
Each derivative is evaluated at the input relevant to that operation. For a longer composition,
Thus, the derivative of a sequence of operations can be computed by multiplying the local derivatives of the operations in the sequence.
Computation graphs and local derivatives
A computation graph represents a calculation as a directed graph:
Each node represents an operation.
Each edge represents data flowing from one operation to another.
A node’s output can become the input to a later node.
For example, if x enters f and the result enters g, the output is g(f(x)). The local derivatives are f′(x) and g′(f(x)), so the derivative of the entire calculation is
Although multiplication is commutative, it is useful to imagine gradients flowing backward, from the final output toward the input. This is the direction used to calculate how downstream results depend on earlier values.
Example: sine followed by exponential
Consider the calculation
The sine operation has local derivative cosx. The exponential operation has local derivative equal to its output, exp(sinx). Therefore,
For x=2, sin2≈0.91 and exp(sin2)≈2.48. Since cos2≈−0.42, the derivative is approximately
A multi-operation example: the sigmoid function
The sigmoid function can be represented as a sequence of simple operations:
Negate the input: x↦−x.
Exponentiate: −x↦e−x.
Add one: e−x↦1+e−x.
Take the reciprocal: 1+e−x↦1+e−x1.
The resulting function is
Each operation has a local derivative:
Negation: −1.
Exponentiation: the exponential output.
Addition of one: 1.
Reciprocal of an input u: −u21.
Multiplying these local derivatives gives the overall derivative:
The chain-rule calculation does not require the expression to be algebraically simplified. It is enough to compute and multiply the local derivatives in the correct order.
For example, with x=1.5, the successive values are approximately −1.5, 0.22, 1.22, and 0.82. The local derivatives can be evaluated at those intermediate values and multiplied to obtain an overall derivative of approximately 0.15.
Backward computation as numeric gradient propagation
A neural network does not need a complete symbolic expression for every gradient. For a particular input and set of parameters, it needs the numeric gradient values that indicate how to adjust the parameters.
In a forward computation, each operation produces an intermediate value. During the backward computation, the process starts at the final result and combines:
The operation’s local derivative, evaluated using its input or output values.
The gradient arriving from later operations in the graph.
For a sequence of operations, each node can therefore calculate how the final output changes with respect to its own input, using only its local derivative and the downstream gradient. This produces gradients for intermediate values as well as for the original input.
Example: multiply, then apply sigmoid
Consider
where x and w are inputs to a multiplication node. The multiplication produces xw, which is passed to the sigmoid.
The sigmoid’s local derivative is σ′(xw). The multiplication’s local derivatives are
Applying the chain rule gives
For x=−1.2 and w=0.3, the product is −0.36, and σ(−0.36)≈0.41. The sigmoid derivative at that input is approximately 0.24. Therefore,
The two gradients differ because the output’s sensitivity to each input depends on the other input to the multiplication.
Locality and the choice of node boundaries
A useful property of computation graphs is that each node can operate using local information:
It retains the inputs and outputs needed to calculate its local derivative.
It sends its forward output to later nodes.
During the backward pass, it receives a downstream gradient and uses that together with its local derivative to calculate gradients for its own inputs.
A node does not need to know the full structure or behavior of the rest of the network. It only needs its own local computation and the gradient passed back to it.
The boundaries between nodes can be chosen to suit the calculation:
A complicated function can be decomposed into simple arithmetic operations.
A compound function with a known derivative can be treated as one atomic node.
For instance, the sigmoid can be represented as several elementary operations or as a single operation with its known derivative. Treating a well-understood compound function as one node can make the graph simpler.
Branches and multiple inputs
Some nodes receive more than one input. For a multiplication node, z=xw, the local derivative with respect to x is w, while the local derivative with respect to w is x. A downstream gradient is combined with each of these local derivatives to obtain a separate gradient for each input.
More generally, when a value influences the final result through multiple paths in a graph, its total gradient must account for all those paths. This is handled by accumulating the gradient contributions arriving from the different downstream branches.
Vector and matrix gradients
Neural networks commonly process vectors and matrices rather than individual scalar values. The same chain-rule principle applies, but the gradients must retain the appropriate shapes and track how output elements depend on input elements.
A vector-valued function can have a Jacobian, which records the partial derivatives of each output element with respect to each input element. In simpler cases, the structure of the operation makes the gradient calculation more direct.
Inner products and linear layers
A linear operation may calculate the dot product of an input vector x and a weight vector w:
The gradient of this scalar output with respect to each vector is
Both gradients are useful:
The gradient with respect to x is passed backward to earlier layers.
The gradient with respect to w is used to update the layer’s weights.
Elementwise operations
For an elementwise activation function, the scalar function is applied independently to each element of the input vector. Its gradient vector contains the scalar derivative evaluated at each corresponding input element.
Multiple outputs and batches
When a layer has multiple outputs, its weights may form a matrix, and the gradient with respect to those weights must have the same shape.
In batch or mini-batch processing, gradients may be represented for each example in the batch. They can then be combined, commonly by taking their mean. Using the mean helps make gradient magnitudes more stable and more comparable across different batch sizes.
Combining operations to simplify gradients
Some combined operations have simpler gradients than their components considered separately. For example, softmax on its own requires a Jacobian because each output can depend on multiple inputs. When softmax is combined with cross-entropy loss, many terms simplify. Treating the combined calculation as one layer can avoid passing around unnecessary Jacobian information.
Forward and backward passes
A network needs a larger-scale structure that coordinates its layers and manages how data and gradients move between them. This coordination is usually performed by a graph or network structure that invokes each layer in the correct order.
Training uses two passes:
Forward pass
The forward pass computes the network’s outputs:
Data enters the network.
Each operation receives its inputs and computes its output.
The output of each operation becomes input to later operations.
The final network output is used to calculate the loss.
Operations must be evaluated in an order that respects their input dependencies: a node can be evaluated only after its required inputs have been calculated.
Backward pass
The backward pass begins with the loss and propagates gradients toward the inputs:
The loss supplies gradients for the final quantities in the network.
Each layer combines the incoming downstream gradients with its own local derivatives.
The resulting gradients are passed to earlier layers.
The process continues until gradients have been calculated throughout the network.
After this pass, the network has the gradients needed for learning.
Backpropagation and optimization are different steps
Backpropagation calculates gradients; it does not itself update the weights. The optimization algorithm, or optimizer, decides how to use those gradients.
An optimizer may use gradient descent or one of its variants. It applies an update to the weights in each layer based on the gradients calculated for those weights. The training process then repeats:
Run a forward pass.
Calculate the loss.
Run a backward pass to calculate gradients.
Use the optimizer to update the weights.
Continue until a chosen stopping condition is reached.
Non-convex losses in neural networks
Some models, including logistic regression and softmax regression without hidden layers, have convex loss functions. Neural networks with hidden layers are generally non-convex, meaning their loss surfaces may contain local minima and other complex structure.
Consequently, optimization may encounter local minima. How serious this is depends on the data, network structure, and task. For some commonly studied deep-learning problems, such as certain computer-vision tasks, evidence suggests that local minima may not be a major obstacle. A “bad” local minimum would be one that provides a poor approximation to the global minimum; in some problem settings, local minima can still yield solutions that are not poor approximations.

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