Deep Learning Lecture 2
Deep Learning: Neural Networks – Lecture Notes
Backpropagation: Deriving Gradients with the Chain Rule
Neural networks are trained by minimizing a cost function J, which measures the average error over a batch of m training examples. The cost function is defined as the average of the loss function L across the batch:
For binary classification (e.g., cat detection), the loss function used is binary cross-entropy (also called logistic loss):
Where y^ is the network’s predicted probability and y is the ground truth label (0 or 1).
The network has parameters for each layer: W[l] and b[l]. For a three-layer network, the layers are W[1],b[1], W[2],b[2], and W[3],b[3]. These parameters are updated iteratively using gradient descent:
Where α is the learning rate.
Since the derivative is a linear operation, computing ∂W[l]∂J is equivalent to averaging the derivatives of the individual loss functions:
To compute these gradients efficiently, we use backpropagation — applying the chain rule from calculus, starting from the output and moving backward through the network.
1. Derivative with Respect to W[3] (Last Layer)
Let the output of the network be:
Where σ is the sigmoid activation function.
We compute ∂W[3]∂L using the chain rule:
Carrying out the derivation step by step:
∂a[3]∂L=−a[3]y+1−a[3]1−y
∂z[3]∂a[3]=σ′(z[3])=a[3](1−a[3])
∂W[3]∂z[3]=(a[2])T (from shape analysis)
Multiplying these and simplifying yields:
Thus, the batch gradient is:
The shape of ∂W[3]∂L must match the shape of W[3]. For example, if W[3] is 1×2 (connecting 2 neurons to 1 output), then the derivative must also be 1×2. This is achieved because (a[2])T is 1×2, and a[3]−y is a scalar.
2. Derivative with Respect to W[2] (Hidden Layer)
For earlier layers, we reuse computations from the layer above. A key insight is that ∂z[3]∂L has already been computed:
This is the error signal from the last layer. To propagate it back to W[2], we use the chain rule:
Each term:
∂a[2]∂z[3]=(W[3])T (shape: 2×1)
∂z[2]∂a[2]=a[2]⊙(1−a[2]) (element-wise derivative of sigmoid)
∂W[2]∂z[2]=(a[1])T
Combining, the correct expression (after accounting for shapes via element-wise multiplication and transpositions) is:
Here, ⊙ denotes element-wise multiplication. The shape analysis ensures consistency: (W[3])T(a[3]−y) is 2×1, a[2]⊙(1−a[2]) is 2×1, and after element-wise multiplication we get a 2×1 vector. Multiplying by (a[1])T (size 1×3) yields a 2×3 matrix, matching the shape of W[2].
Key takeaway: The chain rule decomposes the derivative into a product of local derivatives. The signals flow backward, and many intermediate values (activations a, linear outputs z, and weights W) are cached during forward propagation to avoid redundant computation.
3. Pattern for General Layers
For any layer l, the gradient with respect to W[l] can be expressed as:
Where δ[l] is the error term for layer l, defined recursively:
Here g′ is the derivative of the activation function for layer l. For sigmoid, g′(z)=a⊙(1−a).
This recursive structure is the heart of backpropagation: errors propagate backward, and each layer’s gradient is computed from the error and the previous layer’s activation.
Improving Neural Networks: Practical Techniques
Designing a neural network that trains effectively requires more than just implementing forward and backward propagation. Several hacks and tricks are essential for good performance.
Activation Functions
The choice of activation function has a major impact on training. Three common activation functions are:
Sigmoid: σ(z)=1+e−z1, outputs in (0,1). Derivative: σ(z)(1−σ(z)).
Advantage: outputs can be interpreted as probabilities; good for binary classification output layers.
Disadvantage: vanishing gradients — for large positive or negative z, the derivative is near zero, slowing learning in early layers.
ReLU (Rectified Linear Unit): ReLU(z)=max(0,z). Derivative: 1 if z>0, 0 otherwise.
Advantage: no gradient saturation for positive z, helps mitigate vanishing gradient problem; computationally efficient.
Disadvantage: "dead neurons" — if z is always negative, gradient is zero and the unit never updates.
Tanh (Hyperbolic Tangent): tanh(z)=ez+e−zez−e−z, outputs in (−1,1). Derivative: 1−tanh2(z).
Similar saturation issue as sigmoid, but output is zero-centered.
Comparison of sigmoid, tanh, and ReLU activation functions. ReLU avoids saturation for positive inputs.
Why activation functions are necessary: Without activation functions (i.e., using identity), a deep network collapses into a single linear transformation. For example, in a three-layer network with no activations, the output y^=W[3]W[2]W[1]x+biases is still a linear function of x — the depth adds no expressive power. Non-linear activations are what allow neural networks to learn complex, non-linear patterns.
In practice, ReLU is the most common choice for hidden layers, while sigmoid is typically used only for binary classification output layers. Tanh is sometimes used in recurrent networks. The choice is a hyperparameter tuned experimentally.
Input Normalization
When input features have very different scales (e.g., pixel values 0–255), the network can suffer from saturation of activation functions and slow convergence.
Normalization procedure (on training set):
Compute mean: μ=m1∑ix(i)
Compute variance: σ2=m1∑i(x(i)−μ)2
Normalize: xnorm=σx−μ
This centers the data around zero with unit variance. For two-dimensional data, the contour of the cost function becomes more circular, making gradient descent converge much faster — the gradient points more directly toward the minimum.
Important: The μ and σ computed on the training set must be reused on the test set (and any new data) to keep the input distribution consistent. Never use test set statistics.
Weight Initialization
Poor initialization can cause vanishing or exploding gradients, especially in deep networks. Consider a deep network with identity activations and zero biases. The output is:
If each weight matrix has entries slightly larger than 1 (e.g., 1.5), the product grows exponentially with depth — the output explodes. If entries are slightly less than 1 (e.g., 0.5), the product shrinks to zero — the output vanishes. This problem also affects gradients during backpropagation.
To counter this, weights should be initialized with values carefully scaled based on the number of inputs to the layer.
Common initialization strategies:
For sigmoid/tanh activations: Initialize weights with n[l−1]1 (where n[l−1] is the number of inputs to layer l).
For ReLU activations: A factor of 2 often works better: n[l−1]2.
Xavier (Glorot) initialization: Uses a geometric average of input and output dimensions:
n[l−1]+n[l]2Where n[l] is the number of neurons in layer l. This accounts for both forward and backward signal propagation.
Random initialization is essential to break symmetry — if all weights start identical, every neuron in a layer learns the same features.
Mini-batch Gradient Descent
Batch gradient descent uses the entire training set to compute each update — slow for large datasets. Stochastic gradient descent (SGD) uses a single example per update — fast but noisy, loses vectorization benefits. Mini-batch gradient descent offers a middle ground.
The training set {X,Y} is split into mini-batches of size B (e.g., 64, 128, 256). Each mini-batch {X{t},Y{t}} contains B examples. The algorithm iterates over mini-batches:
For epoch (pass through data):
For t=1 to number of mini-batches:
Forward propagate X{t} through the network
Compute cost J{t}=B1∑i=1BL(i)
Backpropagate to compute gradients
Update parameters: W[l]=W[l]−α∂W[l]∂J{t}
The cost plot for mini-batch descent shows noise (oscillations) because each update uses a different subset of data. Smaller batches give more noise; larger batches give smoother but slower updates. Typical mini-batch sizes range from 32 to 512, chosen to fit GPU memory.
Gradient Descent with Momentum
Standard gradient descent can oscillate in ravines — long, narrow valleys where the cost function is steep in one direction and shallow in another. Momentum smooths the updates by incorporating a velocity term that accumulates past gradients.
Algorithm (per parameter W):
Initialize velocity vdW=0 (same shape as W).
On each iteration:
Compute gradient dW=∂W∂J
Update velocity: vdW=βvdW+(1−β)dW
Update weight: W=W−αvdW
The hyperparameter β (typically 0.9) controls the contribution of past gradients. In regions where gradients oscillate (e.g., vertical direction), the velocities partially cancel, reducing oscillation. In directions of consistent gradient (e.g., horizontal direction), the velocity builds up, accelerating progress.
Intuition: Momentum acts like a heavy ball rolling down the cost surface — it resists rapid direction changes and speeds up along consistently downward slopes. It adds only one extra variable per parameter and often leads to faster convergence.
More advanced optimizers like RMSProp and Adam build on momentum by also adapting learning rates per parameter. Adam is widely used in practice.
Summary of Key Concepts
Backpropagation uses the chain rule to efficiently compute gradients for all parameters. Gradients are computed backward, reusing intermediate values cached during forward propagation.
Activation functions are essential for non-linearity. ReLU is common for hidden layers; sigmoid is used for binary classification outputs.
Input normalization centers and scales data, making gradient descent faster and more stable.
Weight initialization must be carefully scaled to prevent vanishing or exploding gradients. Xavier/Glorot initialization is a popular choice.
Mini-batch gradient descent balances speed and gradient accuracy, allowing vectorized computation on manageable subsets of data.
Momentum accelerates convergence by smoothing gradient updates using a running average of past gradients.

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