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 are models that learn by adjusting numerical parameters called weights. The central idea is similar to learning from mistakes: the network makes a prediction, measures how wrong that prediction is, and then changes its weights in a direction that should reduce future error. The mathematical process used to determine how each weight should change is called backpropagation.

Backpropagation is foundational because nearly every modern neural-network algorithm uses some form of it. It provides an efficient way to calculate the gradients needed by optimization algorithms such as gradient descent.

1. From Scores to Loss

A neural network begins with input data. An input xxx might represent an image, a collection of measurements, or any other feature vector. The network uses weights to transform that input into scores.

For a simple linear classifier, the scoring function can be written as

s=Wxs = Wxs=Wx

where:

  • xxx is the input feature vector,
  • WWW is a matrix of weights,
  • sss is a vector of class scores.

If there are DDD input features and CCC possible classes, then xxx has dimensionality DDD, while the score vector has dimensionality CCC.

A score is not necessarily a probability. It is simply a numerical indication of how strongly the model associates the input with a particular class. A loss function evaluates those scores and produces a single number representing the model's error.

A loss function measures how poorly a model's predictions agree with the desired outputs.

The objective of training is to find weights that minimize the loss. Regularization is usually added as an additional penalty:

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

Here, LdataL_{\text{data}}Ldata​ measures prediction error, R(W)R(W)R(W) penalizes undesirable weight values, and λ\lambdaλ controls how strongly regularization contributes to the total loss.

Softmax loss

Softmax is one commonly used loss framework for classification. It converts class scores into values that can be interpreted as probabilities. The probabilities are then used to calculate how well the correct class was identified.

Softmax is widely used, but it is not the only possible loss function. Different tasks and model designs may require different losses.

Hinge loss

Hinge loss, also known as SVM loss in this context, does not convert scores into probabilities. Instead, it directly compares the score of the correct class with the scores of incorrect classes.

Let syis_{y_i}syi​​ represent the score of the correct class for example iii, and let sjs_jsj​ represent the score of an incorrect class jjj. Hinge loss encourages the correct score to be greater than every incorrect score by at least a margin, often denoted by 111:

syi≥sj+1s_{y_i} \geq s_j + 1syi​​≥sj​+1

When this condition is satisfied, the contribution to the loss is zero. When it is violated, the loss increases according to how far the incorrect score is from the required margin.

Conceptually, hinge loss does not merely ask whether the correct class has the highest score. It asks whether the correct class has a sufficiently higher score than all competing classes.

Why multiple loss functions exist

Softmax and hinge loss express different views of a good prediction:

  • Softmax emphasizes probability-like outputs.
  • Hinge loss emphasizes a margin separating the correct class from incorrect classes.
  • Other losses may be more appropriate for other prediction tasks.

The choice of loss function depends on the problem and the desired behavior of the model.

Think About It

Why might a classification model need a loss function that enforces a margin rather than one that directly produces probabilities?

2. Optimization and the Loss Landscape

The weights of a neural network can be viewed as coordinates in a very high-dimensional space. Every possible set of weights corresponds to one point in that space, and every point has an associated loss value.

Together, these loss values form a loss landscape. A useful mental picture is a large landscape containing hills, valleys, and low points. Training attempts to find a set of weights located in a low-loss region.

The key mathematical tool is the gradient. The gradient describes how the loss changes as the weights change. If the gradient points in the direction of increasing loss, then the opposite direction points toward decreasing loss.

The basic gradient descent update is

W←W−η∇WLW \leftarrow W - \eta \nabla_W LW←W−η∇W​L

where:

  • ∇WL\nabla_W L∇W​L is the gradient of the loss with respect to the weights,
  • η\etaη is the learning rate,
  • the negative sign indicates movement opposite to the gradient.

The learning rate determines the step size. A learning rate that is too small can make training unnecessarily slow. A learning rate that is too large can cause the optimization process to overshoot low-loss regions or become unstable.

Numerical and analytical gradients

There are two common ways to obtain gradients.

A numerical gradient estimates the derivative by slightly changing a parameter and observing how much the loss changes. This method is conceptually simple, but it is computationally expensive and subject to numerical approximation error.

An analytical gradient is derived mathematically using differentiation rules. It is generally much faster and more accurate for training, but deriving and implementing it can be difficult for complicated networks.

In practice, analytical gradients are used for optimization. Numerical gradients are often used to check whether an analytical-gradient implementation is correct.

Mini-batches

Computing the loss and gradient over an entire large dataset at every update can be expensive. Instead, training commonly uses a mini-batch, which is a smaller sample of the training data.

Typical mini-batch sizes include values such as 323232, 646464, 128128128, or 256256256. The model computes an approximate gradient from the mini-batch and uses that gradient to update the weights.

This approach reduces the cost of each update and allows the model to take many optimization steps efficiently. Because each mini-batch is only a sample of the full dataset, the gradient has some randomness, which is the reason for the term stochastic gradient descent.

Optimizer improvements

Several optimization methods improve on basic stochastic gradient descent:

  • Momentum uses information from previous updates to help maintain movement in useful directions.
  • RMSProp adjusts the update behavior based on the historical magnitude of gradients.
  • Adam combines adaptive step-size ideas with momentum-like behavior.

Learning-rate scheduling is also important. A common strategy begins with a relatively large learning rate and gradually reduces it. Some modern optimizers, including Adam and related variants, adjust the effective learning rate internally, reducing the need for manually designed decay schedules.

Think About It

Why is a mini-batch usually more practical than calculating the gradient over every training example before making each update?

3. Building a Multilayer Neural Network

A single linear transformation has the form

s=W1xs = W_1xs=W1​x

This is essentially a one-layer model. It can only create linear decision boundaries, meaning that it separates regions of the input space using linear surfaces such as lines or planes.

A two-layer network introduces a hidden layer:

h=W1xh = W_1xh=W1​x s=W2hs = W_2hs=W2​h

Substituting the first expression into the second gives

s=W2W1xs = W_2W_1xs=W2​W1​x

Although this looks like a multilayer model, it is still only a linear transformation. The two weight matrices can be combined into one matrix:

W3=W2W1W_3 = W_2W_1W3​=W2​W1​

so that

s=W3xs = W_3xs=W3​x

This observation explains why a nonlinear operation is essential between layers.

Dimensions of the layers

Suppose:

  • xxx has dimensionality DDD,
  • the hidden layer contains HHH neurons,
  • the output contains CCC values, usually one for each class.

Then:

  • W1W_1W1​ maps DDD inputs to HHH hidden neurons,
  • W2W_2W2​ maps HHH hidden neurons to CCC outputs.

The dimensions must match across successive layers. The output size of one layer must equal the input size expected by the next layer.

Biases

In practical neural networks, each layer generally includes a bias in addition to the weights. A more complete layer computation can be written as

h=W1x+b1h = W_1x + b_1h=W1​x+b1​

and

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

Biases allow the transformations to shift rather than forcing them to pass through a fixed origin. They are sometimes omitted in simplified notation to make the main structure easier to see.

4. Activation Functions and Nonlinearity

An activation function is applied to a layer's linear output. A common example is the rectified linear unit, or ReLU:

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

For a two-layer network with ReLU, the computation becomes

h=ReLU⁡(W1x+b1)h = \operatorname{ReLU}(W_1x + b_1)h=ReLU(W1​x+b1​) s=W2h+b2s = W_2h + b_2s=W2​h+b2​

The ReLU creates a nonlinear relationship between the input and the output.

Without an activation function, multiple linear layers collapse into one linear transformation. With an activation function between layers, the network can represent nonlinear relationships and solve problems that cannot be separated by a single line or hyperplane.

For example, data may not be linearly separable in its original coordinate space. A nonlinear transformation can map the data into a new representation where a linear boundary becomes sufficient for separation. The source describes a polar-coordinate transformation as one example of how a nonlinear mapping can change the geometry of a problem.

Fully connected networks and multilayer perceptrons

Networks built from layers in which every neuron connects to the outputs of the previous layer are called fully connected networks. They are also commonly called multilayer perceptrons, or MLPs.

A network can contain many hidden layers:

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

Each layer transforms the representation produced by the previous layer.

Templates and learned representations

A linear classifier can be understood as learning templates for the output classes. The weights identify patterns that support particular classifications.

A multilayer network can learn more flexible templates. Instead of learning only complete-object templates, hidden layers can learn templates for parts or properties shared across different classes. For example, several animal classes may share visual features such as eyes or other structural components. Hidden units can respond to such common parts, while later layers combine those responses into complete class predictions.

This is a high-level interpretation: the exact patterns learned depend on the data and the training process.

Think About It

Why does inserting a nonlinear activation between two linear transformations make the network more powerful than simply adding another linear layer?

5. Common Activation Functions

Activation functions all serve the main purpose of introducing nonlinearity, but they differ in their mathematical behavior and practical advantages.

ReLU

ReLU is defined as

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

Positive inputs pass through unchanged, while negative inputs become zero. ReLU is popular because it is simple and often works well as a default choice.

However, a neuron can become dead if it continually receives negative inputs. Its output then remains zero, and its gradient can also remain zero, preventing useful updates.

Leaky ReLU

Leaky ReLU allows a small negative output rather than setting all negative inputs exactly to zero. This can help reduce the dead-neuron problem by allowing some gradient to pass through negative inputs.

ELU

The exponential linear unit, or ELU, is another alternative designed to improve behavior on negative inputs. One motivation for ELU is that it can produce a more zero-centered activation distribution.

GELU

The Gaussian error linear unit, commonly abbreviated GELU, is used in some modern neural-network architectures, including transformer-related models.

SiLU or Swish

The sigmoid linear unit, also called SiLU or Swish, is another modern activation function used in some convolutional neural-network architectures and model families such as EfficientNet.

Sigmoid and hyperbolic tangent

The sigmoid function maps values into a limited range between 000 and 111. The hyperbolic tangent, or tanh⁡\tanhtanh, maps values into a limited range between −1-1−1 and 111.

These functions can be useful in output layers, especially when bounded or binary-like outputs are desired. However, using them repeatedly in the middle of a deep network can cause vanishing gradients. Because their outputs are compressed into a narrow range, their derivatives can become very small. During backpropagation, repeated multiplication by small derivatives can make gradients shrink dramatically as they move toward earlier layers.

For that reason, ReLU and related functions are often preferred in hidden layers, while sigmoid or tanh⁡\tanhtanh may be used in later layers for particular output requirements.

Choosing an activation function

There is no universal activation function that is guaranteed to be best for every problem. Selection is often empirical, meaning it is based on experiments, established practices, and the architecture being used.

The choice depends on factors such as:

  • the network architecture,
  • the dataset,
  • differentiability,
  • gradient behavior,
  • whether the function is centered around zero,
  • how quickly training converges.

6. The Forward Pass

The forward pass is the process of carrying input data through the network from the first layer to the output.

For a simple two-layer network with a sigmoid activation, the process can be represented as

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

followed by

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

and then an output computation such as

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

The network's predicted output is calculated from sss, and the loss function evaluates the prediction against the desired target.

The forward pass therefore consists of:

  1. Applying weights and biases.
  2. Applying activation functions.
  3. Passing the resulting activations to the next layer.
  4. Producing the final prediction.
  5. Computing the loss.

A simple implementation can define the dimensions of the input, hidden layer, and output, initialize weights, perform these operations in sequence, and finally calculate the loss.

7. Capacity, Overfitting, and Regularization

The number of neurons and layers determines the network's capacity, meaning its ability to represent complex functions.

A network with more hidden neurons can learn more complicated boundaries and more detailed patterns. This can improve performance when the original model is too simple and is underfitting the data.

However, excessive capacity can cause overfitting. An overfitted network may memorize the training examples instead of learning general patterns. It can achieve low training loss but perform poorly on unseen examples.

A common strategy is to use a somewhat larger network and control its behavior with regularization. Regularization constrains the weights so that the network is less likely to memorize unnecessary details.

The regularization coefficient λ\lambdaλ determines the strength of this constraint. Increasing λ\lambdaλ gives the regularizer a greater contribution to the total loss:

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

A larger value restricts the weights more strongly. This can produce simpler, more generic decision boundaries, but excessive regularization can cause underfitting because the network has too little freedom to model the data accurately.

Thus, regularization creates a balance:

  • Too little regularization can lead to overfitting.
  • Too much regularization can lead to underfitting.
  • An appropriate amount encourages generalization.

Network size and regularization are related but serve different purposes. Network size controls the model's potential complexity, while regularization controls how freely the model uses that capacity.

There is no single formula that determines the correct number of neurons or layers for every problem. The choice is generally based on experiments and comparison with architectures trained on similar data.

Think About It

Why might a large network with strong regularization perform better than a small network with no regularization?

8. Biological Inspiration and Its Limits

Artificial neural networks were partly inspired by biological neurons, but the analogy is only approximate.

A biological neuron includes structures such as:

  • Dendrites, which receive signals.
  • A cell body, which aggregates incoming signals.
  • An axon, which carries signals onward to other neurons.

An artificial neuron also receives values from previous units, combines them using weights, applies an activation function, and passes the result to later units. This creates a loose conceptual similarity:

  • Incoming artificial values resemble incoming biological signals.
  • Weighted summation resembles signal aggregation.
  • The activation function resembles a rule for producing an outgoing response.

However, biological neurons are far more complex than the simplified units used in typical artificial neural networks. Artificial networks are usually arranged in regular patterns partly because regular structures are efficient to implement computationally. More biologically complex arrangements exist in research, but regular artificial architectures often provide comparable practical results for the purposes of standard machine-learning models.

The biological analogy should therefore be treated as an inspiration rather than a literal description of how the brain operates.

9. Computational Graphs

Manually deriving the derivative of an entire deep network can be extremely difficult. A network may contain many layers, matrix operations, activation functions, and a complicated loss. Re-deriving everything by hand whenever one part of the loss changes would be inefficient and error-prone.

A computational graph solves this problem by expressing a complex computation as a sequence of smaller operations.

For a neural network, the graph might contain:

  1. Input data and parameters.
  2. Matrix multiplication.
  3. Addition of biases.
  4. Activation functions.
  5. Score computation.
  6. Loss calculation.
  7. Regularization.
  8. Total loss.

The graph records how each intermediate value depends on the values before it. Once the forward computation is complete, the graph can be traversed backward to calculate derivatives.

This approach is especially important for complex architectures involving many repeated or sequential operations. A computational graph allows each operation to provide a local forward calculation and a local backward-gradient calculation.

10. Scalar Backpropagation

Consider the scalar function

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

Assume

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

Forward pass

First define an intermediate value:

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

Using the given values,

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

The final output is

f=qzf=qzf=qz

so

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

The forward pass computes values from the inputs toward the final output.

Local derivatives

The first operation is addition:

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

Its local 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

The second operation is multiplication:

f=qzf=qzf=qz

Its local 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

At the end of the graph,

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

because a quantity changes one-for-one with itself.

Upstream and local gradients

The upstream gradient is the gradient arriving from a later operation in the graph. The local gradient is the derivative of the current operation's output with respect to one of its inputs.

The downstream gradient is obtained by multiplying these two quantities:

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

For zzz, the derivative is directly available:

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

For qqq,

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

The variables xxx and yyy are not directly connected to fff. They are connected through qqq. Therefore, the chain rule is used:

∂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​

Substituting the values gives

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

Similarly,

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

The final derivatives are therefore

∂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

Why this is backpropagation

The process begins at the final output, where the gradient is known to be 111. It then moves backward through the graph:

  1. Compute the gradient at the final node.
  2. Multiply by each operation's local derivatives.
  3. Pass the resulting gradients to earlier nodes.
  4. Continue until the gradients with respect to all inputs and parameters are known.

The advantage is modularity. Each operation only needs to know its own local derivative. The full network derivative is assembled by repeatedly applying the chain rule.

Think About It

Why is it easier to calculate local derivatives for individual operations than to derive one enormous formula for an entire deep network?

11. A More Complicated Scalar Example

A sigmoid applied to a linear expression can be written as

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

where aaa may itself be a weighted sum such as

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

A computational graph for this function may contain:

  • Multiplications of weights and inputs,
  • Additions,
  • Negation,
  • The exponential function,
  • Addition of 111,
  • Reciprocal calculation.

Each operation has a local derivative. For example:

ddxex=ex\frac{d}{dx}e^x=e^xdxd​ex=ex

For a reciprocal,

ddx(1x)=−1x2\frac{d}{dx}\left(\frac{1}{x}\right) = -\frac{1}{x^2}dxd​(x1​)=−x21​

For an addition involving a constant, the derivative with respect to the variable is 111.

The backward pass starts with

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

and moves backward through the reciprocal, addition, exponential, multiplication, and other operations. At each step, the gradient arriving from later in the graph is multiplied by the local derivative of the current operation.

Sigmoid's simplified local gradient

The sigmoid derivative can be simplified into a form involving the sigmoid output itself:

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

This is computationally useful because the forward pass already computed σ(x)\sigma(x)σ(x). The backward pass can reuse that value instead of reconstructing the entire derivative from the original expression.

12. Common Backpropagation Patterns

Several operations occur repeatedly in neural networks. Their gradient behavior can be remembered as useful patterns.

Addition gate

For

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

the local derivatives are

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

Therefore, the upstream gradient is passed backward unchanged to both inputs. The addition operation acts as a gradient distributor.

Multiplication gate

For

q=xyq=xyq=xy

the local derivatives are

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

and

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

The gradient with respect to one input is multiplied by the other input. This is often described as a swap pattern: each input receives the upstream gradient multiplied by the other input.

Copy gate

When one value is copied to multiple destinations, the backward pass gathers the gradient contributions from those destinations. In effect, the gradients associated with all uses of the copied value are added together.

Maximum gate

For an operation such as

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

the forward pass selects the larger input. During backpropagation, the gradient is routed to the input that achieved the maximum. The other input receives zero gradient.

ReLU follows the same general idea:

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

If xxx is positive, the gradient passes through. If xxx is negative, the output is zero and the gradient is zero.

13. Modular Forward and Backward Implementations

Because each operation has a local forward rule and a local backward rule, neural-network software can implement operations as modular components.

For example, a multiplication operation can:

  1. Receive its inputs.
  2. Compute and return the product during the forward pass.
  3. Save the inputs needed for differentiation.
  4. Receive an upstream gradient during the backward pass.
  5. Return the appropriate gradients for its inputs.

The same structure can be used for addition, ReLU, sigmoid, matrix multiplication, and other operations.

Frameworks such as PyTorch use this general idea. The details may be implemented in lower-level code for efficiency, but the conceptual structure remains the same: the forward pass computes values, and the backward pass computes gradients through the recorded operations.

14. Vector and Matrix Backpropagation

The earlier examples used scalar values. Neural networks, however, usually operate on vectors, matrices, batches, or higher-dimensional tensors.

Scalar-to-scalar derivatives

If xxx and yyy are scalars, then

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

is also a scalar. It describes how a small change in xxx affects yyy.

Vector-to-scalar derivatives

If xxx is a vector and yyy is a scalar, then the derivative with respect to xxx is a vector. Each element describes how changing one component of xxx affects the scalar output yyy.

Vector-to-vector derivatives

If xxx is a vector with nnn elements and yyy is a vector with mmm elements, then the full derivative is a matrix called the Jacobian.

The Jacobian contains the derivatives of every output element with respect to every input element:

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

Thus, each row describes how one output changes with respect to all inputs, while each column describes how one input influences all outputs.

Gradients of a scalar loss

The loss LLL is a scalar, even when the network processes vectors and matrices. The gradient of the loss with respect to a variable has the same shape as that variable.

If zzz is a vector, then

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

is also a vector of the same size as zzz.

If WWW is a matrix, then

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

is a matrix with the same dimensions as WWW.

This matching shape is necessary because each parameter needs its own update value.

Vectorized ReLU

For a vector input, ReLU usually operates element by element:

ReLU⁡(xi)=max⁡(0,xi)\operatorname{ReLU}(x_i)=\max(0,x_i)ReLU(xi​)=max(0,xi​)

Because each output depends only on the corresponding input, its Jacobian is sparse and has nonzero values only on the main diagonal. Each diagonal value is either 111 when the input passed through ReLU or 000 when ReLU replaced the input with zero.

Instead of explicitly constructing a large sparse Jacobian, implementations use a rule:

  • Pass the gradient through where the input was positive.
  • Set the gradient to zero where the input was negative.

This is much more efficient.

15. Matrix Multiplication Backpropagation

Suppose a layer performs matrix multiplication:

Y=WXY=WXY=WX

The goal is to calculate gradients with respect to both WWW and XXX.

In principle, the full Jacobian could become extremely large. For example, with a mini-batch size of 646464 and a dimensionality of 496496496, explicitly storing a Jacobian for one matrix multiplication could require hundreds of gigabytes of memory. Constructing such a matrix is therefore impractical.

Instead, the backward pass uses matrix operations that directly compute the needed gradients.

If the upstream gradient is

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

then the gradients with respect to the inputs can be expressed using matrix products. Under the conventional arrangement Y=WXY=WXY=WX, they are

∂L∂W=∂L∂YXT\frac{\partial L}{\partial W} = \frac{\partial L}{\partial Y}X^{\mathsf T}∂W∂L​=∂Y∂L​XT

and

∂L∂X=WT∂L∂Y\frac{\partial L}{\partial X} = W^{\mathsf T}\frac{\partial L}{\partial Y}∂X∂L​=WT∂Y∂L​

These expressions avoid explicitly forming the enormous Jacobian.

The underlying intuition is the same as for the scalar multiplication gate. Each output depends on particular entries of WWW and XXX, and the backward pass combines upstream gradients with the relevant values from the other factor. Matrix multiplication performs this many local interactions simultaneously.

16. The Complete Training Cycle

A neural network's training process can now be viewed as a repeating cycle.

Step 1: Initialize parameters

Weights and biases are initialized, often using small random values.

Step 2: Perform the forward pass

The input is passed through each layer:

h1=f1(W1x+b1)h_1=f_1(W_1x+b_1)h1​=f1​(W1​x+b1​) h2=f2(W2h1+b2)h_2=f_2(W_2h_1+b_2)h2​=f2​(W2​h1​+b2​)

until the network produces a prediction.

Step 3: Compute the loss

The prediction is compared with the target using a loss function such as softmax-based loss or hinge loss. A regularization term may be added:

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

Step 4: Perform the backward pass

Starting with

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

the algorithm moves backward through the computational graph. Each operation combines its local gradient with the upstream gradient and sends the result toward earlier operations.

Step 5: Update the parameters

The optimizer uses gradients such as

∂L∂W1and∂L∂W2\frac{\partial L}{\partial W_1} \quad\text{and}\quad \frac{\partial L}{\partial W_2}∂W1​∂L​and∂W2​∂L​

to update the weights. For basic gradient descent:

Wk←Wk−η∂L∂WkW_k\leftarrow W_k-\eta\frac{\partial L}{\partial W_k}Wk​←Wk​−η∂Wk​∂L​

The process repeats over many mini-batches until the model learns a useful set of parameters.

Comprehensive Review

A neural network transforms inputs into outputs through weighted layers, biases, and activation functions. A linear layer alone cannot represent general nonlinear relationships because multiple linear transformations can be combined into one. Activation functions such as ReLU introduce the nonlinearity needed to model more complex decision boundaries.

The network's predictions are evaluated with a loss function. Softmax-based losses convert scores into probability-like values, while hinge loss directly encourages the correct class score to exceed incorrect scores by a margin. Regularization adds a penalty on the weights to reduce overfitting, with λ\lambdaλ controlling the strength of that penalty.

Optimization uses gradients to determine how the weights should change. Gradient descent updates parameters in the direction opposite the gradient, while mini-batches and improved optimizers such as momentum, RMSProp, and Adam make training more practical.

Backpropagation efficiently calculates the gradients required for these updates. A computational graph decomposes the network into simple operations. The forward pass computes values from inputs to loss, and the backward pass starts at the loss and applies the chain rule in reverse. Each operation supplies a local gradient, multiplies it by the upstream gradient, and passes the resulting gradient to earlier operations.

For scalar values, this process uses ordinary derivatives. For vectors and matrices, it uses vectorized operations and avoids explicitly constructing enormous Jacobian matrices. The result is an efficient method for training multilayer neural networks by systematically learning from the error produced at the end of the network.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent