Neural Networks and Backpropagation
Neural Networks and Backpropagation
Neural networks learn by adjusting their parameters so that their predictions become more accurate. Backpropagation is the central procedure used to calculate how each parameter contributed to the final loss. It allows a network to “learn from its mistakes” in a systematic mathematical way.
Backpropagation is fundamental because nearly every modern neural-network algorithm uses some form of it, even when the algorithm does not explicitly mention the term.
Review: Loss Functions, Regularization, and Optimization
Loss functions
A neural network receives input data X and uses parameters such as weight matrices W to produce scores or predictions. A loss function measures how different the model’s predictions are from the desired outputs.
For a classification model:
X represents the input features.
y represents the correct class label.
W represents the trainable weights.
The scoring function maps inputs to class scores.
The loss function converts the scores into a scalar measure of error.
A common linear scoring function has the form
where x is an input vector and s contains one score for each class.
The complete training objective generally combines two components:
where:
Ldata is the data loss, measuring prediction error.
R(W) is the regularization term.
λ controls the strength of regularization.
Softmax loss
Softmax loss is widely used for classification. It converts class scores into values that can be interpreted as probabilities and then penalizes the model when the correct class receives a low probability.
Softmax is common, but it is not the only available loss function. Different tasks and model architectures may require different loss functions.
Hinge loss
Hinge loss, also historically called SVM loss, is another classification loss. Unlike softmax loss, hinge loss does not convert scores into probabilities.
For a correct class yi, the loss encourages its score syi to exceed the score of every incorrect class sj by at least a margin.
A typical multiclass hinge-loss expression is
where Δ is the required margin, often set to 1.
The loss behaves as follows:
If syi≥sj+Δ, the margin requirement is satisfied and the contribution is 0.
If an incorrect class receives a score that is too high, the loss becomes positive.
The larger the violation of the margin, the larger the penalty.
Key idea: Hinge loss promotes correct classifications by penalizing cases in which incorrect classes receive scores that are too close to, or higher than, the correct class score.
Optimization and Gradient Descent
Training requires finding parameters that minimize the total loss. The set of all possible parameter values can be viewed as a loss landscape.
Each point in the landscape represents one possible set of weights.
The height of a point represents the loss for that set of weights.
Training attempts to move toward a low point or minimum of the landscape.
Gradients
The gradient describes the direction in which the loss increases most rapidly. Therefore, moving in the negative direction of the gradient generally reduces the loss.
For parameters W, the gradient is written as
The gradient-descent update is
where η is the learning rate.
Learning rate
The learning rate determines the size of each optimization step.
If the learning rate is too small, training may be extremely slow.
If it is too large, the model may overshoot good solutions or become unstable.
A larger learning rate is often useful early in training.
The learning rate may then be reduced according to a schedule.
Some modern optimizers, including Adam and related variants, adapt the effective learning rate internally, reducing the need for manually designed schedules.
Numerical and analytical gradients
Two approaches can be used to obtain gradients:
Numerical gradients
A numerical gradient approximates the derivative by slightly changing a parameter and observing the resulting change in loss.
Advantages:
Easy to implement conceptually.
Useful for checking an implementation.
Disadvantages:
Computationally expensive.
Subject to approximation error.
Impractical for large neural networks.
Analytical gradients
An analytical gradient is derived mathematically using differentiation and the chain rule.
Advantages:
Accurate.
Efficient when implemented correctly.
Scales to large models.
Disadvantages:
Deriving and implementing the expressions can be difficult.
Errors in the derivation or code can be hard to find.
In practice, analytical gradients are used for training, while numerical gradients are often used to verify that the analytical implementation is correct.
Mini-batch training
Computing the loss and gradient over an entire large dataset at every step can be expensive. Instead, training usually uses a mini-batch, a randomly selected subset of examples.
Common mini-batch sizes include:
32
64
128
256
The procedure is:
Sample a mini-batch from the training data.
Compute predictions for the mini-batch.
Compute the loss.
Compute gradients using the mini-batch.
Update the weights.
Repeat.
This approach is the basis of stochastic gradient descent and its variants.
Optimizers
Several methods improve on basic stochastic gradient descent:
SGD with momentum: Uses a running direction of previous updates to reduce oscillation and accelerate movement in consistent directions.
RMSProp: Adapts the step size according to recent gradient magnitudes.
Adam: Combines momentum-like estimates with adaptive scaling of the learning rate.
Neural-Network Structure
Linear models as single-layer networks
A linear classifier can be viewed as the simplest neural network. Its basic computation is
where:
D is the input dimensionality or number of features.
C is the number of output classes.
W has a compatible shape, typically C×D.
s contains C class scores.
Bias terms are also normally included:
where b provides an additional trainable offset for each output unit.
Two-layer neural networks
A two-layer network introduces a hidden layer. A typical computation is
followed by
where:
W1 maps the input to the hidden layer.
h contains the hidden-layer activations.
W2 maps the hidden layer to the output layer.
f is an activation function.
b1 and b2 are bias vectors.
If the input has dimension D, the hidden layer has H neurons, and the output has C classes, then the typical dimensions are:
x: D-dimensional.
W1: H×D.
h: H-dimensional.
W2: C×H.
s: C-dimensional.
The hidden-layer size H determines how many intermediate features or templates the network can represent.
Multiple layers
Additional layers can be stacked:
Each layer’s output must have a dimension compatible with the next layer’s input.
Networks composed primarily of matrix multiplications, biases, and activation functions are commonly called:
Fully connected networks
Multilayer perceptrons, or MLPs
Why nonlinear activation functions are necessary
Suppose a two-layer network contains no activation function:
The two weight matrices can be combined into a single matrix:
Therefore,
The entire network would still be a linear function. Adding more linear layers would not provide additional expressive power because all the layers could be mathematically collapsed into one linear transformation.
Key idea: Nonlinear activation functions prevent multiple layers from collapsing into a single linear transformation.
Nonlinearity allows a neural network to represent complex decision boundaries and solve problems that cannot be separated by one straight line or hyperplane.
Nonlinear feature transformations
Some datasets are not linearly separable in their original feature space. A nonlinear transformation can map the data into a new space where the classes become separable.
For example, a transformation from Cartesian coordinates (x,y) to polar coordinates (r,θ) can reorganize the representation of the data. In the transformed space, a boundary that was nonlinear in the original space may become linear.
Neural networks learn useful transformations automatically through their layers instead of requiring the feature transformation to be manually specified.
Learned Templates and Hierarchical Representations
A linear classifier can be understood as learning templates associated with its output classes. Applying the learned weights to an input produces scores indicating how well the input matches those templates.
A multilayer network can learn more varied and hierarchical representations:
The output layer may learn templates for complete objects or classes.
A hidden layer can learn templates for parts of objects.
Different classes may share lower-level features.
For example, if the classes include birds, cats, deer, dogs, frogs, and horses, many classes contain eyes. A hidden neuron might respond to an eye-like pattern rather than to an entire animal.
With more hidden neurons, a network can learn a larger collection of intermediate patterns. These patterns can be combined by later layers to represent increasingly complex objects.
This hierarchical representation is one reason multilayer networks are more expressive than single-layer linear models.
Activation Functions
An activation function transforms the output of a neuron before passing it to the next layer.
For a neuron with pre-activation value a, the activation is
Activation functions are important because they introduce nonlinearity, allowing the network to model complex relationships.
They also need to be suitable for gradient-based learning. Important design considerations include:
Nonlinearity.
Differentiability or useful derivative behavior.
Avoidance of vanishing gradients.
Computational efficiency.
Appropriate centering and scaling of outputs.
Compatibility with the architecture and task.
ReLU
The rectified linear unit, or ReLU, is defined as
Its behavior is:
If x>0, the output is x.
If x≤0, the output is 0.
ReLU is popular because it is simple, computationally efficient, and generally provides useful gradients for positive inputs.
Dead neurons
A potential problem is the dead-neuron problem. If a neuron consistently receives negative inputs, ReLU outputs zero. Its gradient may also remain zero, preventing the neuron from recovering during training.
Leaky ReLU
Leaky ReLU allows a small negative output instead of setting all negative inputs to zero. A common form is
where α is a small positive constant.
This gives the neuron a nonzero gradient for negative inputs and can reduce the dead-neuron problem.
ELU
The exponential linear unit, or ELU, behaves linearly for positive values and exponentially for negative values:
ELU can produce more zero-centered activations than ordinary ReLU, which may improve optimization.
GELU
The Gaussian error linear unit, or GELU, is used in several modern architectures, particularly transformer-based models. It smoothly weights inputs rather than applying a sharp cutoff at zero.
GELU is useful because its smooth behavior can provide favorable optimization properties.
SiLU or Swish
The sigmoid linear unit, also called SiLU or Swish, is commonly written as
where σ(x) is the sigmoid function.
SiLU and related functions have been used in modern convolutional and other deep-learning architectures.
Sigmoid
The sigmoid function is
It maps any real-valued input to the interval (0,1).
Sigmoid can be useful when an output is intended to represent a probability or binary value. However, its derivative becomes very small when the input is highly positive or highly negative. This can cause vanishing gradients in deep networks.
Tanh
The hyperbolic tangent function is
It maps inputs to the interval (−1,1) and is zero-centered. Like sigmoid, however, it can saturate for large positive or negative inputs and produce vanishing gradients.
Practical activation-function choices
ReLU is often a strong default for hidden layers.
Leaky ReLU and ELU can reduce problems caused by zero gradients for negative inputs.
GELU and SiLU are common in many modern architectures.
Sigmoid is often used in binary-output layers.
Tanh may be used when outputs centered around zero are useful.
The output activation depends strongly on the task and the chosen loss function.
The best activation function is usually selected empirically or based on practices established for similar architectures.
Forward Pass and Network Implementation
A neural network’s forward pass applies the layers in order to produce a prediction.
For a two-layer network:
Compute the first affine transformation: $$ a_1 = W_1x + b_1 $$
Apply the hidden-layer activation: $$ h = f(a_1) $$
Compute the output transformation: $$ a_2 = W_2h + b_2 $$
Apply an output activation if required.
Compute the loss using the prediction and the target.
For a sigmoid-based hidden layer, the equations might be
and
followed by an output computation such as
The forward pass produces all intermediate values needed for the loss and for the later backward pass.
A basic implementation therefore needs to:
Define the dimensions of the data and layers.
Initialize weights, often randomly.
Store input and intermediate values.
Perform the forward pass.
Compute the loss.
Compute gradients.
Update the weights.
The mathematical calculation of analytical gradients is usually the most technically demanding part.
Network Capacity, Overfitting, and Regularization
Increasing the number of hidden neurons increases the network’s capacity, meaning its ability to represent complex functions and decision boundaries.
A larger network can:
Learn more detailed patterns.
Separate complicated classes more effectively.
Represent more templates.
Fit the training data more closely.
However, excessive capacity can cause overfitting. An overfitted network may memorize the training examples rather than learning general patterns. Its training performance may be excellent while its performance on unseen data is poor.
Regularization
Regularization limits the complexity of the learned parameters. A common objective is
The regularizer constrains the weights, reducing the freedom of the model and encouraging simpler decision boundaries.
If λ is too large:
The weights are constrained too strongly.
The model may be unable to represent important patterns.
Decision boundaries become overly simple.
The model may underfit.
If λ is too small:
The model has more freedom to fit the training data.
Overfitting becomes more likely.
Key idea: Regularization balances accurate prediction against excessive model complexity.
Why network size is not usually used as the primary regularizer
A common strategy is to use a somewhat larger network than seems minimally necessary and then control its effective complexity with regularization.
The reasoning is:
Increase the number of parameters until the model has enough capacity to learn the important structure.
Observe whether the model begins to overfit.
Use regularization to reduce excessive memorization.
Select the regularization strength using validation experiments.
The network size still matters for computational cost and representational ability, but regularization is often the main tool used to control overfitting.
Choosing the number of neurons
There is no universal formula that gives the correct number of neurons for every problem. The choice is usually empirical and depends on:
Dataset size.
Input complexity.
Number of classes.
Difficulty of the task.
Similar architectures used for related datasets.
Computational budget.
Validation performance.
A practical approach is to:
Examine successful networks for similar problems.
Start with a reasonable range of layer sizes.
Train and evaluate several configurations.
Adjust the network capacity and regularization.
Select the configuration that provides the best validation performance.
Biological Inspiration and Its Limits
Artificial neural networks are loosely inspired by biological neurons, but the analogy should not be treated as an exact description of neuroscience.
Biological neuron structure
A biological neuron generally includes:
Dendrites, which receive signals from other neurons.
A cell body, which aggregates and processes incoming signals.
An axon, which transmits signals to other neurons.
Artificial neural networks use a related abstract pattern:
A neuron receives values from the previous layer.
It combines them using weighted sums.
It applies an activation function.
It passes the resulting activation to the next layer.
A simplified artificial neuron is
followed by
The activation function is loosely analogous to a mechanism that determines how strongly a neuron responds.
Important limitations of the analogy
Artificial neurons differ substantially from biological neurons:
Biological neurons have much richer temporal and chemical behavior.
Biological networks are not generally arranged as simple regular layers.
Biological learning mechanisms are not identical to gradient descent.
Artificial neurons are mathematical abstractions designed for computational efficiency.
Similar terminology does not imply identical biological function.
Regular layered networks are often used because they are efficient to implement and optimize. More biologically complex architectures have been studied, but standard regular neural networks remain highly effective for many tasks.
Computational Graphs
Manually differentiating an entire neural network can become impractical. A network may contain many layers, matrix operations, nonlinearities, and a complex loss function.
A computational graph solves this problem by representing a computation as a sequence of smaller operations.
For example, a model may consist of:
Input values.
Matrix multiplication.
Addition of a bias.
Activation function.
Loss calculation.
Regularization.
Total-loss calculation.
The graph decomposes a large function into local operations. Each operation can provide:
A forward computation.
A local gradient for the backward computation.
This modular structure makes complex networks easier to implement and modify.
Example structure
A typical loss graph may include:
The graph first computes scores, then the data loss and regularization loss, and finally adds them to produce the total loss.
Computational graphs are especially valuable for complex architectures, including networks that are repeatedly applied across time or sequence positions. Without modular graph-based differentiation, manually deriving the gradients of such systems would be extremely difficult.
Backpropagation
Backpropagation computes gradients by starting at the final loss and moving backward through the computational graph.
It relies on the chain rule of calculus.
Suppose
and
Then
The process passes gradient information from later operations to earlier operations.
Upstream, local, and downstream gradients
For a computational-graph node:
The upstream gradient is the gradient arriving from later computations, closer to the loss.
The local gradient is the derivative of the node’s output with respect to its inputs.
The downstream gradient is the gradient passed to earlier nodes.
The central rule is
Each node only needs to understand its own local operation. The global gradient is assembled by repeatedly applying this rule backward through the graph.
Scalar Backpropagation Example
Consider
with values
Forward pass
Introduce an intermediate variable:
Then
The final output is
The computation graph contains:
An addition node computing q=x+y.
A multiplication node computing f=qz.
Local derivatives at the addition node
For
the derivatives are
and
A change in either input changes q by the same amount.
Local derivatives at the multiplication node
For
the derivatives are
and
Using the values q=3 and z=−4:
and
Backward pass
At the final output,
This is always true because a quantity changes one-for-one with itself.
Gradient with respect to z
Since z is directly connected to f,
Gradient with respect to q
Similarly,
Gradient with respect to x
Because x is connected to f through q, the chain rule gives
Substituting the values:
Gradient with respect to y
Likewise,
Therefore,
The final gradients are
The key point is that the gradient with respect to earlier variables is obtained by multiplying the upstream gradient by the appropriate local gradient.
A More Complex Scalar Example
A more complicated function may contain:
Multiplications.
Additions.
Negations.
Exponentials.
Reciprocals.
A sigmoid of a linear combination can be written as
where the linear combination might be
The computational graph can either represent the sigmoid as one complete operation or break it into smaller operations:
Multiply each weight by its input.
Add the products.
Negate the result.
Apply the exponential.
Add 1.
Take the reciprocal.
Each operation has a known local derivative:
For a constant addition:
dxd(x+c)=1For multiplication by a constant c:
dxd(cx)=cFor the exponential:
dxdex=exFor the reciprocal:
dxdx1=−x21
The backward pass begins with gradient 1 at the final output and successively multiplies by each local gradient while moving backward.
Sigmoid as a Computational-Graph Node
The sigmoid derivative has a particularly convenient form:
This means that the local gradient can be computed using the sigmoid output itself. If the node has already stored σ(x) during the forward pass, the backward pass does not need to recompute the entire function.
If the upstream gradient is g, then the downstream gradient is
This illustrates why computational graph nodes often store intermediate forward-pass values for use during backpropagation.
Common Computational-Graph Patterns
Several small graph structures occur repeatedly in neural networks.
Addition gate
For
the local derivatives are
Therefore, the addition gate distributes the upstream gradient unchanged to both inputs.
Multiplication gate
For
the local derivatives are
The multiplication gate effectively swaps the values: the gradient with respect to one input is multiplied by the other input.
Copy gate
A copy gate sends the same value to multiple locations in a graph. During the backward pass, gradients from all destinations must be added together because the original value influenced every destination.
Maximum gate
For
the gradient is routed to whichever input achieved the maximum:
The input with the larger value receives the upstream gradient.
The other input receives zero.
If the inputs are equal, the behavior depends on the implementation.
ReLU is a special case of a maximum gate:
Thus, positive inputs receive the gradient, while nonpositive inputs generally receive zero.
Modular Forward and Backward APIs
Each operation in a neural network can be implemented as a module with two procedures:
Forward procedure
The forward procedure:
Receives input values.
Computes the output.
Stores any intermediate values needed later.
Backward procedure
The backward procedure:
Receives the upstream gradient.
Computes local gradients.
Produces downstream gradients for the inputs.
For a multiplication operation, the forward procedure computes
and stores x and y. The backward procedure then uses
and
This modular design allows complex networks to be assembled from reusable components. Modern deep-learning frameworks such as PyTorch use this general principle: operators define forward computations and provide corresponding backward-gradient rules.
Vector and Matrix Backpropagation
The scalar examples extend naturally to vectors, matrices, and tensors.
Scalar-to-scalar derivatives
If both input and output are scalars,
then the derivative is also a scalar:
It describes how much y changes when x changes slightly.
Vector-to-scalar derivatives
If x is a vector and y is a scalar,
then the derivative with respect to x is a vector:
Each element describes the sensitivity of the scalar output to one component of x.
Vector-to-vector derivatives
If both input and output are vectors,
then the derivative is a matrix called the Jacobian:
The Jacobian records how every output component changes in response to every input component.
Although Jacobians are mathematically useful, explicitly constructing them can be very expensive. Neural-network implementations usually exploit the structure of each operation to calculate the needed products without storing the entire Jacobian.
Backpropagation with Vectors
The loss L is usually a scalar, but each variable in the network may be a vector or matrix.
If z is a vector, then
has the same shape as z.
This shape-matching property is essential:
A scalar loss produces a vector gradient with respect to a vector variable.
It produces a matrix gradient with respect to a matrix variable.
It produces a tensor gradient with respect to a tensor variable.
For a vector-valued intermediate node z=f(x,y), the local derivatives may be Jacobian matrices. The upstream gradient is multiplied by the relevant Jacobian to produce downstream gradients.
Vector ReLU Example
Consider the elementwise ReLU function
for each component xi.
Because each output component depends only on the corresponding input component, the Jacobian is diagonal:
Therefore, the Jacobian is sparse. Rather than explicitly constructing a large matrix, the backward pass can apply the simple rule:
If xi>0, pass the upstream gradient through.
If xi≤0, output a gradient of zero.
If the upstream gradient is gi, the downstream gradient is
This is much more efficient than creating and multiplying by the full Jacobian.
Matrix Multiplication Backpropagation
Matrix multiplication is one of the most important operations in neural networks.
Suppose
where W and X are matrices. Let the upstream gradient be
Then the gradients with respect to the inputs are computed using matrix multiplications:
and
The exact transpose arrangement depends on the chosen shapes and convention, but the underlying principle is consistent: matrix multiplication in the forward pass becomes appropriately arranged matrix multiplication in the backward pass.
The scalar “swap” rule still applies conceptually. For a scalar product z=xy, the gradient with respect to x uses y, and the gradient with respect to y uses x. In the matrix case, the same relationship is expressed through matrix products and transposes.
Why explicit Jacobians are avoided
For a mini-batch of size 64 and feature dimensions such as 496, explicitly forming the Jacobian for one matrix multiplication can require hundreds of gigabytes of memory.
This is unnecessary because:
Each output depends on the inputs in a structured way.
Matrix calculus gives direct formulas for the required gradient products.
The implementation can compute gradients using efficient matrix multiplications.
The full Jacobian does not need to be stored.
This approach is called Jacobian-vector or vector-Jacobian computation, depending on the direction of multiplication and notation.
Backpropagation Through Tensors
Modern neural networks often operate on tensors rather than simple vectors or matrices. Examples include:
Images.
Video sequences.
Batches of samples.
Feature maps.
Transformer representations.
The same principles apply:
The loss is usually a scalar.
The gradient of the loss with respect to a variable has the same shape as that variable.
Each operation supplies a local backward rule.
Gradients are propagated from later operations to earlier operations.
Structured operations are handled without explicitly constructing enormous Jacobians.
Complete Training Workflow
A neural network combines forward computation, loss evaluation, backpropagation, and parameter optimization.
Initialize parameters such as weights and biases.
Perform the forward pass through each layer.
Compute the data loss from predictions and target values.
Compute the regularization loss if regularization is used.
Combine the losses: $$ L_{\text{total}}=L_{\text{data}}+\lambda R(W) $$
Begin the backward pass with $$ \frac{\partial L}{\partial L}=1 $$
Backpropagate through each operation using local gradients and upstream gradients.
Obtain gradients for every weight and bias.
Update parameters using an optimization rule such as gradient descent: $$ W\leftarrow W-\eta\frac{\partial L}{\partial W} $$
Repeat over many mini-batches and training iterations.
Backpropagation does not itself choose the new weights. It computes the gradients that an optimizer uses to choose the direction and size of each update.
Central principle: Backpropagation efficiently computes how the loss changes with respect to every parameter, enabling gradient-based learning in networks with many layers and operations.
Neural networks therefore depend on three connected ideas: nonlinear layered representations provide expressive power, loss functions measure prediction quality, and backpropagation supplies the gradients needed to optimize the parameters.

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