1. Home
  2. Explore
  3. Computer Science
  4. Neural Networks and Backpropagation

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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 XXX and uses parameters such as weight matrices WWW to produce scores or predictions. A loss function measures how different the model’s predictions are from the desired outputs.

For a classification model:

  • XXX represents the input features.

  • yyy represents the correct class label.

  • WWW 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

s=Wxs = Wxs=Wx

where xxx is an input vector and sss contains one score for each class.

The complete training objective generally combines two components:

Ltotal=Ldata+λR(W)L_{\text{total}} = L_{\text{data}} + \lambda R(W)Ltotal​=Ldata​+λR(W)

where:

  • LdataL_{\text{data}}Ldata​ is the data loss, measuring prediction error.

  • R(W)R(W)R(W) is the regularization term.

  • λ\lambdaλ 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 yiy_iyi​, the loss encourages its score syis_{y_i}syi​​ to exceed the score of every incorrect class sjs_jsj​ by at least a margin.

A typical multiclass hinge-loss expression is

Li=∑j≠yimax⁡(0,  sj−syi+Δ)L_i = \sum_{j \neq y_i} \max\left(0,\; s_j - s_{y_i} + \Delta\right)Li​=∑j=yi​​max(0,sj​−syi​​+Δ)

where Δ\DeltaΔ is the required margin, often set to 111.

The loss behaves as follows:

  • If syi≥sj+Δs_{y_i} \geq s_j + \Deltasyi​​≥sj​+Δ, the margin requirement is satisfied and the contribution is 000.

  • 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 WWW, the gradient is written as

∂L∂W\frac{\partial L}{\partial W}∂W∂L​

The gradient-descent update is

W←W−η∂L∂WW \leftarrow W - \eta \frac{\partial L}{\partial W}W←W−η∂W∂L​

where η\etaη 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:

  • 323232

  • 646464

  • 128128128

  • 256256256

The procedure is:

  1. Sample a mini-batch from the training data.

  2. Compute predictions for the mini-batch.

  3. Compute the loss.

  4. Compute gradients using the mini-batch.

  5. Update the weights.

  6. 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

s=Wxs = Wxs=Wx

where:

  • DDD is the input dimensionality or number of features.

  • CCC is the number of output classes.

  • WWW has a compatible shape, typically C×DC \times DC×D.

  • sss contains CCC class scores.

Bias terms are also normally included:

s=Wx+bs = Wx + bs=Wx+b

where bbb 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

h=f(W1x+b1)h = f(W_1x + b_1)h=f(W1​x+b1​)

followed by

s=W2h+b2s = W_2h + b_2s=W2​h+b2​

where:

  • W1W_1W1​ maps the input to the hidden layer.

  • hhh contains the hidden-layer activations.

  • W2W_2W2​ maps the hidden layer to the output layer.

  • fff is an activation function.

  • b1b_1b1​ and b2b_2b2​ are bias vectors.

If the input has dimension DDD, the hidden layer has HHH neurons, and the output has CCC classes, then the typical dimensions are:

  • xxx: DDD-dimensional.

  • W1W_1W1​: H×DH \times DH×D.

  • hhh: HHH-dimensional.

  • W2W_2W2​: C×HC \times HC×H.

  • sss: CCC-dimensional.

The hidden-layer size HHH determines how many intermediate features or templates the network can represent.

Multiple layers

Additional layers can be stacked:

h1=f(W1x+b1)h_1 = f(W_1x + b_1)h1​=f(W1​x+b1​)
h2=f(W2h1+b2)h_2 = f(W_2h_1 + b_2)h2​=f(W2​h1​+b2​)
s=W3h2+b3s = W_3h_2 + b_3s=W3​h2​+b3​

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:

s=W2W1xs = W_2W_1xs=W2​W1​x

The two weight matrices can be combined into a single matrix:

W3=W2W1W_3 = W_2W_1W3​=W2​W1​

Therefore,

s=W3xs = W_3xs=W3​x

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)(x,y)(x,y) to polar coordinates (r,θ)(r,\theta)(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 aaa, the activation is

h=f(a)h = f(a)h=f(a)

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

ReLU⁡(x)=max⁡(0,x)\operatorname{ReLU}(x) = \max(0,x)ReLU(x)=max(0,x)

Its behavior is:

  • If x>0x > 0x>0, the output is xxx.

  • If x≤0x \leq 0x≤0, the output is 000.

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

LeakyReLU⁡(x)={x,x>0αx,x≤0\operatorname{LeakyReLU}(x) = \begin{cases} x, & x > 0 \\ \alpha x, & x \leq 0 \end{cases}LeakyReLU(x)={x,αx,​x>0x≤0​

where α\alphaα 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⁡(x)={x,x>0α(ex−1),x≤0\operatorname{ELU}(x) = \begin{cases} x, & x > 0 \\ \alpha(e^x - 1), & x \leq 0 \end{cases}ELU(x)={x,α(ex−1),​x>0x≤0​

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

SiLU⁡(x)=xσ(x)\operatorname{SiLU}(x) = x \sigma(x)SiLU(x)=xσ(x)

where σ(x)\sigma(x)σ(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

σ(x)=11+e−x\sigma(x) = \frac{1}{1+e^{-x}}σ(x)=1+e−x1​

It maps any real-valued input to the interval (0,1)(0,1)(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

tanh⁡(x)=ex−e−xex+e−x\tanh(x) = \frac{e^x-e^{-x}}{e^x+e^{-x}}tanh(x)=ex+e−xex−e−x​

It maps inputs to the interval (−1,1)(-1,1)(−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:

  1. Compute the first affine transformation: $$ a_1 = W_1x + b_1 $$

  2. Apply the hidden-layer activation: $$ h = f(a_1) $$

  3. Compute the output transformation: $$ a_2 = W_2h + b_2 $$

  4. Apply an output activation if required.

  5. Compute the loss using the prediction and the target.

For a sigmoid-based hidden layer, the equations might be

h1=σ(W1x+b1)h_1 = \sigma(W_1x+b_1)h1​=σ(W1​x+b1​)

and

h2=σ(W2h1+b2)h_2 = \sigma(W_2h_1+b_2)h2​=σ(W2​h1​+b2​)

followed by an output computation such as

s=W3h2+b3s = W_3h_2+b_3s=W3​h2​+b3​

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

Ltotal=Ldata+λR(W)L_{\text{total}} = L_{\text{data}} + \lambda R(W)Ltotal​=Ldata​+λR(W)

The regularizer constrains the weights, reducing the freedom of the model and encouraging simpler decision boundaries.

If λ\lambdaλ 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 λ\lambdaλ 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:

  1. Increase the number of parameters until the model has enough capacity to learn the important structure.

  2. Observe whether the model begins to overfit.

  3. Use regularization to reduce excessive memorization.

  4. 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:

  1. Examine successful networks for similar problems.

  2. Start with a reasonable range of layer sizes.

  3. Train and evaluate several configurations.

  4. Adjust the network capacity and regularization.

  5. 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:

  1. A neuron receives values from the previous layer.

  2. It combines them using weighted sums.

  3. It applies an activation function.

  4. It passes the resulting activation to the next layer.

A simplified artificial neuron is

a=∑iwixi+ba = \sum_i w_i x_i + ba=∑i​wi​xi​+b

followed by

h=f(a)h = f(a)h=f(a)

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:

  1. Input values.

  2. Matrix multiplication.

  3. Addition of a bias.

  4. Activation function.

  5. Loss calculation.

  6. Regularization.

  7. 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:

s=Wxs = Wxs=Wx
Ltotal=Ldata(s,y)+λR(W)L_{\text{total}} = L_{\text{data}}(s,y) + \lambda R(W)Ltotal​=Ldata​(s,y)+λR(W)

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

f=f(q)f = f(q)f=f(q)

and

q=q(y)q = q(y)q=q(y)

Then

∂f∂y=∂f∂q∂q∂y\frac{\partial f}{\partial y} = \frac{\partial f}{\partial q} \frac{\partial q}{\partial y}∂y∂f​=∂q∂f​∂y∂q​

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

downstream gradient=upstream gradient×local gradient\text{downstream gradient} = \text{upstream gradient} \times \text{local gradient}downstream gradient=upstream gradient×local gradient

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

f(x,y,z)=(x+y)zf(x,y,z) = (x+y)zf(x,y,z)=(x+y)z

with values

x=−2,y=5,z=−4x=-2,\qquad y=5,\qquad z=-4x=−2,y=5,z=−4

Forward pass

Introduce an intermediate variable:

q=x+yq=x+yq=x+y

Then

q=−2+5=3q=-2+5=3q=−2+5=3

The final output is

f=qz=3(−4)=−12f=qz=3(-4)=-12f=qz=3(−4)=−12

The computation graph contains:

  1. An addition node computing q=x+yq=x+yq=x+y.

  2. A multiplication node computing f=qzf=qzf=qz.

Local derivatives at the addition node

For

q=x+yq=x+yq=x+y

the derivatives are

∂q∂x=1\frac{\partial q}{\partial x}=1∂x∂q​=1

and

∂q∂y=1\frac{\partial q}{\partial y}=1∂y∂q​=1

A change in either input changes qqq by the same amount.

Local derivatives at the multiplication node

For

f=qzf=qzf=qz

the derivatives are

∂f∂q=z\frac{\partial f}{\partial q}=z∂q∂f​=z

and

∂f∂z=q\frac{\partial f}{\partial z}=q∂z∂f​=q

Using the values q=3q=3q=3 and z=−4z=-4z=−4:

∂f∂q=−4\frac{\partial f}{\partial q}=-4∂q∂f​=−4

and

∂f∂z=3\frac{\partial f}{\partial z}=3∂z∂f​=3

Backward pass

At the final output,

∂f∂f=1\frac{\partial f}{\partial f}=1∂f∂f​=1

This is always true because a quantity changes one-for-one with itself.

Gradient with respect to zzz

Since zzz is directly connected to fff,

∂f∂z=q=3\frac{\partial f}{\partial z}=q=3∂z∂f​=q=3

Gradient with respect to qqq

Similarly,

∂f∂q=z=−4\frac{\partial f}{\partial q}=z=-4∂q∂f​=z=−4

Gradient with respect to xxx

Because xxx is connected to fff through qqq, the chain rule gives

∂f∂x=∂f∂q∂q∂x\frac{\partial f}{\partial x} = \frac{\partial f}{\partial q} \frac{\partial q}{\partial x}∂x∂f​=∂q∂f​∂x∂q​

Substituting the values:

∂f∂x=(−4)(1)=−4\frac{\partial f}{\partial x} = (-4)(1) = -4∂x∂f​=(−4)(1)=−4

Gradient with respect to yyy

Likewise,

∂f∂y=∂f∂q∂q∂y\frac{\partial f}{\partial y} = \frac{\partial f}{\partial q} \frac{\partial q}{\partial y}∂y∂f​=∂q∂f​∂y∂q​

Therefore,

∂f∂y=(−4)(1)=−4\frac{\partial f}{\partial y} = (-4)(1) = -4∂y∂f​=(−4)(1)=−4

The final gradients are

∂f∂x=−4,∂f∂y=−4,∂f∂z=3\frac{\partial f}{\partial x}=-4,\qquad \frac{\partial f}{\partial y}=-4,\qquad \frac{\partial f}{\partial z}=3∂x∂f​=−4,∂y∂f​=−4,∂z∂f​=3

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

σ(a)=11+e−a\sigma(a)=\frac{1}{1+e^{-a}}σ(a)=1+e−a1​

where the linear combination might be

a=w0x0+w1x1+w2x2a=w_0x_0+w_1x_1+w_2x_2a=w0​x0​+w1​x1​+w2​x2​

The computational graph can either represent the sigmoid as one complete operation or break it into smaller operations:

  1. Multiply each weight by its input.

  2. Add the products.

  3. Negate the result.

  4. Apply the exponential.

  5. Add 111.

  6. Take the reciprocal.

Each operation has a known local derivative:

  • For a constant addition:

    ddx(x+c)=1\frac{d}{dx}(x+c)=1dxd​(x+c)=1
  • For multiplication by a constant ccc:

    ddx(cx)=c\frac{d}{dx}(cx)=cdxd​(cx)=c
  • For the exponential:

    ddxex=ex\frac{d}{dx}e^x=e^xdxd​ex=ex
  • For the reciprocal:

    ddx1x=−1x2\frac{d}{dx}\frac{1}{x}=-\frac{1}{x^2}dxd​x1​=−x21​

The backward pass begins with gradient 111 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:

dσ(x)dx=σ(x)(1−σ(x))\frac{d\sigma(x)}{dx} = \sigma(x)\left(1-\sigma(x)\right)dxdσ(x)​=σ(x)(1−σ(x))

This means that the local gradient can be computed using the sigmoid output itself. If the node has already stored σ(x)\sigma(x)σ(x) during the forward pass, the backward pass does not need to recompute the entire function.

If the upstream gradient is ggg, then the downstream gradient is

g⋅σ(x)(1−σ(x))g \cdot \sigma(x)\left(1-\sigma(x)\right)g⋅σ(x)(1−σ(x))

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

z=x+yz=x+yz=x+y

the local derivatives are

∂z∂x=1,∂z∂y=1\frac{\partial z}{\partial x}=1,\qquad \frac{\partial z}{\partial y}=1∂x∂z​=1,∂y∂z​=1

Therefore, the addition gate distributes the upstream gradient unchanged to both inputs.

Multiplication gate

For

z=xyz=xyz=xy

the local derivatives are

∂z∂x=y,∂z∂y=x\frac{\partial z}{\partial x}=y,\qquad \frac{\partial z}{\partial y}=x∂x∂z​=y,∂y∂z​=x

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

z=max⁡(x,y)z=\max(x,y)z=max(x,y)

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:

ReLU⁡(x)=max⁡(0,x)\operatorname{ReLU}(x)=\max(0,x)ReLU(x)=max(0,x)

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

z=xyz=xyz=xy

and stores xxx and yyy. The backward procedure then uses

∂L∂x=∂L∂zy\frac{\partial L}{\partial x} = \frac{\partial L}{\partial z}y∂x∂L​=∂z∂L​y

and

∂L∂y=∂L∂zx\frac{\partial L}{\partial y} = \frac{\partial L}{\partial z}x∂y∂L​=∂z∂L​x

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,

x∈R,y∈Rx\in\mathbb{R},\qquad y\in\mathbb{R}x∈R,y∈R

then the derivative is also a scalar:

dydx\frac{dy}{dx}dxdy​

It describes how much yyy changes when xxx changes slightly.

Vector-to-scalar derivatives

If xxx is a vector and yyy is a scalar,

x∈Rn,y∈Rx\in\mathbb{R}^n,\qquad y\in\mathbb{R}x∈Rn,y∈R

then the derivative with respect to xxx is a vector:

∂y∂x\frac{\partial y}{\partial x}∂x∂y​

Each element describes the sensitivity of the scalar output to one component of xxx.

Vector-to-vector derivatives

If both input and output are vectors,

x∈Rn,y∈Rmx\in\mathbb{R}^n,\qquad y\in\mathbb{R}^mx∈Rn,y∈Rm

then the derivative is a matrix called the Jacobian:

Jij=∂yi∂xjJ_{ij} = \frac{\partial y_i}{\partial x_j}Jij​=∂xj​∂yi​​

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 LLL is usually a scalar, but each variable in the network may be a vector or matrix.

If zzz is a vector, then

∂L∂z\frac{\partial L}{\partial z}∂z∂L​

has the same shape as zzz.

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)z=f(x,y)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

zi=max⁡(0,xi)z_i=\max(0,x_i)zi​=max(0,xi​)

for each component xix_ixi​.

Because each output component depends only on the corresponding input component, the Jacobian is diagonal:

∂zi∂xj={1,i=j and xi>00,otherwise\frac{\partial z_i}{\partial x_j} = \begin{cases} 1, & i=j \text{ and } x_i>0 \\ 0, & \text{otherwise} \end{cases}∂xj​∂zi​​={1,0,​i=j and xi​>0otherwise​

Therefore, the Jacobian is sparse. Rather than explicitly constructing a large matrix, the backward pass can apply the simple rule:

  • If xi>0x_i>0xi​>0, pass the upstream gradient through.

  • If xi≤0x_i\leq 0xi​≤0, output a gradient of zero.

If the upstream gradient is gig_igi​, the downstream gradient is

∂L∂xi={gi,xi>00,xi≤0\frac{\partial L}{\partial x_i} = \begin{cases} g_i, & x_i>0 \\ 0, & x_i\leq 0 \end{cases}∂xi​∂L​={gi​,0,​xi​>0xi​≤0​

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

Y=WXY=WXY=WX

where WWW and XXX are matrices. Let the upstream gradient be

GY=∂L∂YG_Y=\frac{\partial L}{\partial Y}GY​=∂Y∂L​

Then the gradients with respect to the inputs are computed using matrix multiplications:

∂L∂W=GYXT\frac{\partial L}{\partial W} = G_YX^{\mathsf T}∂W∂L​=GY​XT

and

∂L∂X=WTGY\frac{\partial L}{\partial X} = W^{\mathsf T}G_Y∂X∂L​=WTGY​

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=xyz=xyz=xy, the gradient with respect to xxx uses yyy, and the gradient with respect to yyy uses xxx. 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 646464 and feature dimensions such as 496496496, 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.

  1. Initialize parameters such as weights and biases.

  2. Perform the forward pass through each layer.

  3. Compute the data loss from predictions and target values.

  4. Compute the regularization loss if regularization is used.

  5. Combine the losses: $$ L_{\text{total}}=L_{\text{data}}+\lambda R(W) $$

  6. Begin the backward pass with $$ \frac{\partial L}{\partial L}=1 $$

  7. Backpropagate through each operation using local gradients and upstream gradients.

  8. Obtain gradients for every weight and bias.

  9. Update parameters using an optimization rule such as gradient descent: $$ W\leftarrow W-\eta\frac{\partial L}{\partial W} $$

  10. 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent