Backpropagation and Neural Networks
Backpropagation and Neural Networks
This lesson connects three central ideas:
- Loss minimization: finding model parameters that make predictions as accurate as possible.
- Backpropagation: efficiently computing gradients for complicated functions.
- Neural networks: building complex nonlinear functions by stacking simpler computations.
The key theme is that a complicated model becomes manageable when it is broken into small computational steps.
From Classification to Optimization
A classifier can be represented as a function
f(x;W),where:
- x is the input data,
- W contains the model parameters, or weights,
- f produces a vector of scores, one score for each class.
For example, an image classifier might receive an image x and output scores for classes such as “cat,” “car,” and “horse.”
A loss function measures how good or bad those scores are. The support vector machine loss, or hinge loss, is one example. The loss is small when the correct class receives a suitably high score compared with the incorrect classes, and large when the scores do not reflect the correct classification.
The total loss generally contains two parts:
L=Ldata+Lregularization.The data loss measures performance on the training examples. The regularization loss expresses a preference for simpler models. This preference is useful because a model that is overly complicated may memorize the training data instead of learning patterns that generalize to new data.
The learning problem is therefore:
Find the parameters W that minimize the total loss L.
To do this, the model needs the gradient of the loss with respect to the weights:
∂W∂L.The gradient indicates how the loss changes when the parameters change. Gradient descent updates the parameters in the direction that decreases the loss:
Wnew=Wold−η∂W∂L,where η is the step size, or learning rate.
The negative gradient points in the direction of steepest local decrease. Repeatedly taking steps in that direction moves the parameters down the loss landscape toward a region of low loss.
Numerical and Analytic Gradients
There are two main ways to compute gradients.
A numerical gradient estimates the derivative by slightly changing a variable and observing the resulting change in the function. For a scalar variable x, a finite-difference approximation is
∂x∂f≈2hf(x+h)−f(x−h),where h is a very small number.
Numerical gradients are easy to implement and do not require manually deriving formulas. However, they are:
- slow, because many function evaluations are required,
- approximate rather than exact,
- useful mainly for checking other implementations.
An analytic gradient is derived using calculus. Once the formula is derived and implemented, it is fast and exact up to numerical precision. Its disadvantage is that complicated expressions can be difficult to derive correctly.
A practical strategy is therefore:
- Derive and implement the analytic gradient.
- Compute a numerical gradient for the same function.
- Compare them to check the implementation.
The central technique for obtaining analytic gradients of complex functions is backpropagation.
Computational Graphs
A computational graph represents a function as a sequence of smaller operations. Each node represents one computation, and the edges show how values flow between computations.
For a linear classifier, a computational graph could contain:
- an input x,
- weights W,
- a matrix multiplication producing class scores,
- a data-loss computation,
- a regularization computation,
- an addition producing the total loss.
The important advantage is modularity. Instead of differentiating the entire complicated function at once, each node only needs to provide the derivative of its own simple operation.
For example, a multiplication node can provide derivatives based on the multiplication rule, while an addition node can provide derivatives based on the addition rule. Backpropagation then combines these local derivatives using the chain rule.
This becomes especially valuable in models with many transformations, such as convolutional neural networks. The input image may pass through many layers before producing a final loss. Deriving one enormous symbolic gradient by hand would be impractical, whereas a computational graph allows the gradient to be computed one small operation at a time.
A computational graph breaks a complex function into simple operations so that the chain rule can be applied locally and recursively.
Forward Pass
The forward pass evaluates the function from inputs to output.
Consider
f(x,y,z)=(x+y)z.The graph can be written using an intermediate variable:
q=x+y,followed by
f=qz.Suppose
x=−2,y=5,z=−4.The forward computation is:
q=x+y=−2+5=3,and then
f=qz=3(−4)=−12.The values flowing forward are the actual values of the function and its intermediate variables.
Local Gradients
Each node also has local gradients, which describe how its immediate output changes with respect to its immediate inputs.
For the addition node,
q=x+y,the local derivatives are
∂x∂q=1,∂y∂q=1.For the multiplication node,
f=qz,the local derivatives are
∂q∂f=z,∂z∂f=q.These derivatives only describe the immediate operation. They do not yet describe the full effect of x or y on f.
Backpropagation as a Recursive Chain Rule
Backpropagation computes gradients by starting at the final output and moving backward through the computational graph.
The output’s derivative with respect to itself is always
∂f∂f=1.This value is the initial upstream gradient.
For the example
f=(x+y)z,the backward pass proceeds as follows.
Gradient with Respect to z
Because
∂z∂f=q,and q=3,
∂z∂f=3.Gradient with Respect to q
Because
∂q∂f=z,and z=−4,
∂q∂f=−4.Gradient with Respect to y
The variable y is not directly connected to f. Its influence passes through q. The chain rule gives
∂y∂f=∂q∂f∂y∂q.Substituting the known values,
∂y∂f=(−4)(1)=−4.Gradient with Respect to x
Similarly,
∂x∂f=∂q∂f∂x∂q=(−4)(1)=−4.Thus,
∂x∂f=−4,∂y∂f=−4,∂z∂f=3.The crucial idea is that each node combines:
- the upstream gradient, which describes how the final output changes with respect to that node’s output;
- the local gradient, which describes how that node’s output changes with respect to its inputs.
The gradient passed to an input is
input gradient=upstream gradient×local gradient.This is the chain rule in operational form.
Why Backpropagation Is Easier Than Full Symbolic Differentiation
For a simple expression, ordinary calculus can produce the same result. However, as the expression becomes more complicated, expanding the entire function and differentiating it directly becomes unwieldy.
Backpropagation avoids this by requiring each node to understand only:
- its immediate inputs,
- its immediate output,
- its local derivative.
A node does not need to know the entire function that comes before or after it. It simply receives a numerical upstream gradient, multiplies it by its local gradient, and passes the result backward.
The Backward Pass for a More Complicated Function
Consider the function
f(w,x)=1+e−(w0x0+w1x1+w2)1.This is a sigmoid applied to a weighted sum. A graph can break it into the following steps:
- Multiply w0 and x0.
- Multiply w1 and x1.
- Add those products and the bias-like term w2.
- Multiply the result by −1.
- Apply the exponential function.
- Add 1.
- Take the reciprocal.
Each operation has a simple local derivative:
- For z=x+y, the derivative with respect to either input is 1.
- For z=xy, the derivative with respect to x is y, and with respect to y is x.
- For z=ex, the derivative is ex.
- For z=ax, the derivative with respect to x is a.
- For z=1/x, the derivative is
Backpropagation starts with an upstream gradient of 1 at the output and successively multiplies by each local derivative while moving backward. The calculation uses the values produced during the forward pass.
For example, when moving through the reciprocal node whose input has value 1.37, the local gradient is
−1.3721≈−0.53.That value becomes the upstream gradient for the preceding node. At an addition node, the gradient remains unchanged because the local derivative is 1. At an exponential node, the upstream gradient is multiplied by the value of the exponential output. The process continues until gradients with respect to all weights and inputs have been found.
The graph never requires the entire complicated sigmoid expression to be differentiated at once.
Gate Interpretations
Certain computational nodes have useful intuitive interpretations during backpropagation.
Addition Gate: Gradient Distributor
For
z=x+y,the local derivative with respect to each input is 1:
∂x∂z=1,∂y∂z=1.Therefore, the same upstream gradient is passed to both inputs. An addition gate distributes the gradient equally to every input branch.
Maximum Gate: Gradient Router
For a maximum operation,
z=max(x,y),only the input that achieved the maximum affected the output during the forward pass. Consequently, during backpropagation, the gradient is routed to that input, while the other input receives zero.
For example, if
z=max(2,−1)=2,and the upstream gradient is 2, then:
- the input with value 2 receives gradient 2,
- the input with value −1 receives gradient 0.
The maximum gate therefore acts as a gradient router.
Multiplication Gate: Gradient Scaler
For
z=xy,the local derivatives are
∂x∂z=y,∂y∂z=x.Thus, the gradient for one input is scaled by the value of the other input. If the other input is large, the gradient is scaled up; if it is small, the gradient is scaled down.
Branches and Summed Gradients
Sometimes one variable influences several later computations. In that case, the total gradient with respect to the variable is the sum of the gradients arriving from all paths.
If x influences intermediate variables q1,q2,…,qn, then the multivariable chain rule gives
∂x∂f=k=1∑n∂qk∂f∂x∂qk.The gradients add because changing x affects every downstream branch, so every branch contributes to the total effect of changing x.
When multiple computational paths lead from a variable to the output, backpropagation sums the gradient contributions from all of those paths.
Think About It
If a variable influences two different branches of a graph, why would ignoring one branch produce an incomplete gradient? The missing branch represents part of the variable’s total effect on the final output.
Grouping Operations into Larger Gates
A graph can be drawn at different levels of detail.
A sigmoid can be represented as many small operations:
σ(x)=1+e−x1,or as a single sigmoid gate.
The derivative of the sigmoid has the convenient form
dxdσ(x)=σ(x)(1−σ(x)).Therefore, a sigmoid can be treated as one computational node as long as that node stores or computes this local derivative.
For example, if the sigmoid output is 0.73, then its local derivative is approximately
0.73(1−0.73)≈0.20.If the upstream gradient is 1, the gradient passed backward is approximately 0.20, exactly as it would be if the sigmoid had been decomposed into smaller operations.
This creates a trade-off:
- Smaller gates require simpler local derivatives but produce larger graphs.
- Larger gates make the graph more concise but require more complicated local derivative formulas.
The only requirement is that every gate must have a known local gradient.
Vector-Valued Variables and Jacobians
So far, the examples have used scalar variables. In machine learning, variables are often vectors or matrices.
When the input and output are vectors, the gradient generalizes to a Jacobian matrix. The Jacobian contains the derivative of every output component with respect to every input component.
For a vector function z(x), the Jacobian contains terms such as
∂xj∂zi.If x has n components and z has m components, the Jacobian has shape m×n.
Element-Wise Operations
Suppose x is a 4096-dimensional vector and the operation is an element-wise maximum with zero:
f(x)=max(x,0),where the maximum is taken separately for every element.
The output also has 4096 components. A complete Jacobian would have shape
4096×4096.That is a very large matrix. With batches of examples, it would become even larger.
However, because the operation is element-wise, each output element depends only on the corresponding input element. Therefore, the Jacobian is diagonal. Most entries are zero, and the full matrix does not need to be explicitly constructed.
This sparsity is important in practical implementations: the system can propagate the relevant element-wise derivatives without storing a huge Jacobian.
A Vectorized Backpropagation Example
Consider
f(W,x)=∥Wx∥22,where x is an n-dimensional vector and W is an n×n matrix.
Define an intermediate vector
q=Wx. $$` Then the function becomesf(q)=\lVert q\rVert_2^2
\sum_i q_i^2.
The computational graph has two main operations: 1. Matrix-vector multiplication: $q=Wx$. 2. Squared $L_2$ norm: $f=\lVert q\rVert_2^2$. ### Gradient with Respect to $q$ For an individual element,\frac{\partial f}{\partial q_i}=2q_i.
Invectorform,\frac{\partial f}{\partial q}=2q.
The gradient has the same shape as $q$. This shape rule is an important implementation check: the gradient with respect to a variable must have the same dimensions as that variable. ### Gradient with Respect to $W$ Each element of $q$ isq_k=\sum_j W_{k,j}x_j.
The local derivative of $q_k$ with respect to $W_{i,j}$ is\frac{\partial q_k}{\partial W_{i,j}}
\begin{cases} x_j, & k=i,\ 0, & k\ne i. \end{cases}
The indicator-like condition reflects the fact that $W_{i,j}$ affects only the corresponding output component $q_i$. Applying the chain rule,\frac{\partial f}{\partial W_{i,j}}
\sum_k \frac{\partial f}{\partial q_k} \frac{\partial q_k}{\partial W_{i,j}}.
Only the term with $k=i$ remains, giving\frac{\partial f}{\partial W_{i,j}}
2q_i x_j.
Inmatrixform,thisisanouterproduct:\frac{\partial f}{\partial W}
2q x^{\mathsf T}.
The result has the same shape as $W$. ### Gradient with Respect to $x$ The derivative of $q_k$ with respect to $x_i$ is\frac{\partial q_k}{\partial x_i}=W_{k,i}.
Applyingthechainrulegives\frac{\partial f}{\partial x_i}
\sum_k \frac{\partial f}{\partial q_k} \frac{\partial q_k}{\partial x_i}.
Invectorform,\frac{\partial f}{\partial x}
W^{\mathsf T}\frac{\partial f}{\partial q}.
Since\frac{\partial f}{\partial q}=2q,
theexpressioncanalsobewrittenas\frac{\partial f}{\partial x}
2W^{\mathsf T}q.
The gradient with respect to $x$ has the same shape as $x$. ### Shape Checking A useful sanity check is: - the gradient with respect to a scalar is scalar, - the gradient with respect to a vector has the vector’s shape, - the gradient with respect to a matrix has the matrix’s shape. If a calculated gradient has the wrong shape, the derivative or matrix operation is probably incorrect. ### Think About It Why is shape checking useful even when the algebra appears correct? A gradient can have numerically plausible values but still be unusable if it cannot be combined with the parameter it is supposed to update. ## Implementing Computational Graphs A computational graph can be implemented using a modular forward-and-backward interface. Each gate provides: - a **forward function**, which computes the gate’s output; - a **backward function**, which receives the upstream gradient and computes gradients for the gate’s inputs. ### Forward Pass Implementation During the forward pass, the graph processes gates in an order that respects their dependencies. Every input to a gate must be computed before that gate is processed. This is called a topologically sorted order. The forward pass often caches intermediate values because the backward pass needs them. ### Backward Pass Implementation The backward pass processes gates in reverse order. Each gate receives the gradient of the final output with respect to its own output, multiplies that upstream gradient by its local derivatives, and sends gradients to its inputs. For a scalar multiplication gate,z=xy,
the forward operation computes $z$ and stores $x$ and $y$. If the upstream gradient is\frac{\partial L}{\partial z},
thentheinputgradientsare\frac{\partial L}{\partial x}
\frac{\partial L}{\partial z}y,
and\frac{\partial L}{\partial y}
\frac{\partial L}{\partial z}x.
The multiplication gate does not need to know anything about the rest of the graph. Deep-learning frameworks use this same organization. Their layers or operations each implement forward and backward behavior. A complete model is formed by arranging these layers into a larger graph. ## From Backpropagation to Neural Networks Backpropagation computes gradients, but it does not itself update the weights. Once the gradients have been computed, an optimization method such as gradient descent updates the parameters:W\leftarrow W-\eta\frac{\partial L}{\partial W}.
Backpropagation supplies the gradients; optimization uses those gradients to improve the parameters. This separation is useful: - the computational graph defines the function, - the backward pass computes its gradients, - the optimizer changes the parameters. ## Neural Networks as Compositions of Functions A single linear classifier has the formf(x)=Wx.
Aneuralnetworkcreatesamorecomplexfunctionbystackinglayers.Asimpletwo−layernetworkcanbewrittenash=\max(0,W_1x),
followedbyf=W_2h.
The operation $\max(0,\cdot)$ is applied element by element. It is a nonlinear activation function commonly called the **ReLU**, or rectified linear unit. The complete model is thereforef(x)=W_2\max(0,W_1x).
The first layer transforms the input into an intermediate representation $h$. The second layer uses that representation to produce the final class scores. ### Why Nonlinearities Are Necessary If several linear transformations are stacked without nonlinear activations, they collapse into one linear transformation. For example,W_2(W_1x)
(W_2W_1)x.
Theresultisstilljustasinglelinearfunction.Addingnonlinearitiesbetweenlayerspreventsthiscollapseandallowsthenetworktorepresentmorecomplicatedrelationships.Aneuralnetworkthereforereliesonalternating:1.linearoraffinetransformations,2.nonlinearactivationfunctions.Adeepernetworkcanbebuiltbyrepeatingthispattern:h_1=\phi(W_1x),
h_2=\phi(W_2h_1),
f=W_3h_2,
where $\phi$ is an activation function such as ReLU or sigmoid. ### Hidden Layers The intermediate representations, such as $h_1$ and $h_2$, are called **hidden layers** because they are internal to the model rather than directly observed as inputs or final outputs. Terminology can count networks in two related ways: - A network with two matrix-multiply layers may be called a **two-layer neural network**. - The same network may be called a **one-hidden-layer neural network** if there is one intermediate hidden layer. A three-matrix-multiply network may therefore be called either a three-layer network or a two-hidden-layer network, depending on the counting convention. ## Why Multiple Layers Help A linear classifier uses each row of $W$ as a template for one class. For an image classifier, one row might represent a rough visual template for a car. A limitation is that one class may have many different appearances. Cars can be red, yellow, viewed from different directions, or shaped differently. A single template cannot represent all these possibilities effectively. A multilayer network can use the first layer to detect multiple lower-level patterns or templates. For example, different units might respond to: - a left-facing horse, - a right-facing horse, - a particular color pattern, - a particular shape. The hidden representation contains scores indicating how strongly each template is present. The next layer combines these scores using another weight matrix. A class can then receive a high score from many different combinations of detected templates. The second layer does not simply choose the maximum template. It forms a weighted combination of the hidden activations. This allows the final class score to depend on several possible patterns and combinations. The interpretation is approximate because nonlinearities are present throughout the network, but the general idea is that early layers can form useful intermediate features and later layers can combine them into more meaningful concepts. ## Neural Networks and Biological Neurons Neural networks are loosely inspired by biological nervous systems, although the analogy should not be taken literally. A simplified biological neuron contains: - **Dendrites**, which receive incoming signals. - A **cell body**, which integrates those signals. - An **axon**, which carries the resulting signal to other neurons. - Connections between neurons, often discussed in terms of synapses. A simplified artificial neuron performs a related sequence: 1. Receive inputs $x_1,x_2,\ldots,x_n$. 2. Weight and combine them. 3. Add a bias term. 4. Apply an activation function. 5. Pass the result to later units. This can be written asa=\phi\left(\sum_i w_ix_i+b\right),
orinvectorformasa=\phi(Wx+b).
The weights determine how strongly each input contributes. The activation function transforms the combined signal into the neuron’s output. One loose analogy is that the activation value resembles a neuron’s activity or firing strength. A large positive activation may be viewed as a strong signal passed to later units. ### ReLU and Neural Activity The ReLU function is\operatorname{ReLU}(x)=\max(0,x).
It outputs zero for negative inputs and a linear value for positive inputs. ReLU is sometimes considered more similar to simplified neural firing behavior than some other activation functions because it separates inactive and active regimes. However, artificial neural networks are not accurate simulations of biological neurons. Biological neurons have: - many different types and structures, - complex dendritic computations, - synapses that behave as nonlinear dynamical systems, - communication patterns that cannot be fully represented by a single firing-rate value. Thus, the biological connection is best understood as a broad source of inspiration, not as a precise description of how artificial neural networks work. ## Efficient Evaluation of Neural-Network Layers A hidden layer can contain many artificial neurons. Instead of calculating each neuron separately, matrix multiplication evaluates the entire layer efficiently. For example, a layer can computeh=\phi(Wx+b),
where one matrix multiplication produces the pre-activation values for all neurons in the layer. The activation function is then applied element-wise. This vectorized form is both mathematically concise and computationally efficient. It is one reason neural networks can be trained using highly optimized numerical libraries. The backward pass uses the same modular structure. Each matrix multiplication and activation function contributes a local gradient, and backpropagation chains these gradients from the loss back through the network to the weights. ## Comprehensive Review A classifier maps input data to class scores using parameters such as weights. A loss function measures how well those scores match the desired outputs, while regularization encourages simpler models. Gradient descent minimizes the loss by moving the parameters opposite the gradient. A computational graph represents a function as connected operations. The forward pass computes the output and caches useful intermediate values. Backpropagation begins at the output and moves backward, repeatedly applying the chain rule. At each node,\text{gradient to an input}
\text{upstream gradient} \times \text{local gradient}.
Additiongatesdistributegradients,maximumgatesroutegradientstothewinninginput,andmultiplicationgatesscalegradientsbythevalueoftheotherinput.Whenavariableaffectsmultipledownstreambranches,thegradientcontributionsareadded.Forvectorandmatrixcomputations,Jacobiansdescribehoweveryoutputcomponentdependsoneveryinputcomponent.Inpractice,fullJacobiansareoftenavoidedbecausetheirstructureissparseorbecausevectorizedchain−ruleformulasaremoreefficient.Neuralnetworksarecompositionsoflineartransformationsandnonlinearactivationfunctions:h_1=\phi(W_1x), \qquad h_2=\phi(W_2h_1), \qquad f=W_3h_2.
Thenonlinearitiesareessentialbecausestackedlineartransformationsalonereducetoasinglelineartransformation.Multiplelayersallowearlystagestodetectdifferentpatternsandlaterstagestocombinethosepatternsintomoreflexibleclassscores.Backpropagationdoesnotupdateparametersbyitself.Itcomputesthegradientsrequiredbyanoptimizer,allowinggradientdescentoranotheroptimizationmethodtoadjusttheweightsandreducetheloss.
Ask anything
We've read this whole study set, so questions about it get the best answers.