Lecture 09: Neural Networks - Learning
An in-depth guide to learning parameters in Neural Networks, covering the cost function, backpropagation algorithm, parameter unrolling, gradient checking, random weight initialization, and complete workflow implementation.
Neural Network Cost Function
Neural Networks (NNs) are one of the most powerful learning algorithms. They allow fitting complex non-linear hypothesis functions given a training set. Let's first examine the setup and cost function for neural networks.
Setup and Notation
We focus on the application of NNs to classification problems. Here is the general setup:
- Training set:
- = total number of layers in the network (e.g., in the diagram below)
- = number of units (not counting the bias unit) in layer

In the example network shown above:
- (4 layers)
- (3 input features, excluding bias )
- (5 hidden units in layer 2)
- (5 hidden units in layer 3)
- (4 output units in layer 4)
Types of Classification Problems
We distinguish two types of classification problems in neural networks:
-
Binary classification:
- Single output ()
- Output node is a scalar real number
- output unit (where denotes the number of units in the output layer)
-
Multi-class classification:
- distinct classification categories (; if , it defaults to binary classification)
- Output is a -dimensional vector of real numbers (one-hot encoded vector representing each class)

Cost Function for Neural Networks
Recall that the regularized logistic regression cost function for binary classification is:

For neural networks, the cost function is a generalization of this equation. Instead of a single scalar output, the hypothesis outputs a -dimensional vector:

Here:
- , so refers to the -th element of the output vector.
- The summation accumulates the logistic regression loss over all output units.
Understanding the Cost Function
The neural network cost function consists of two primary components:
- First Half (Unregularized Cost):

This term computes the average cross-entropy loss over all training examples and across all output units.
- Second Half (Regularization / Weight Decay):

This is a triple nested summation that sums the square of every parameter weight in the network. Notice that:
- We do not regularize the bias terms (), hence the index starts from 1. (Even if bias terms were regularized, it wouldn't make much difference, but omitting them is standard).
- This term is often called the weight decay term.
- As before, balances fitting the training data versus keeping weight parameters small to prevent overfitting.
Now that we have defined the cost function , how do we minimize it?
Overview of Training & Backpropagation
The backpropagation algorithm is one of the more involved concepts in machine learning, so let's first outline the high-level roadmap of what we are doing.
Forward Propagation vs. Backpropagation
- Forward Propagation: Takes the neural network parameters and an input vector , feeding it forward through each layer to compute activations up to the output hypothesis (which can be a scalar or a -dimensional vector).
- Backpropagation:
- Takes the network's output hypothesis and compares it against the true label to compute the error of the output layer.
- Back-calculates the error associated with each unit in preceding hidden layers (from layer down to layer 2).
- Uses these error terms to compute the partial derivatives of the cost function .
- Feeds these partial derivatives into gradient descent (or advanced optimization algorithms like BFGS, L-BFGS, conjugate gradient) to minimize and iteratively update .
Key Matrices to Keep in Mind
- For each layer , there is a parameter matrix mapping from layer to layer . The size of is .
- There is an error matrix associated with each layer , which serves as an accumulator for computing partial derivatives across all training examples.
Backpropagation Algorithm
The backpropagation algorithm allows us to efficiently calculate the partial derivatives so we can minimize .

Given the cost function , our goal is to find parameters to minimize :
To use optimization algorithms (such as gradient descent or advanced optimizers), we need code that computes two things:
- : The cost value for a given set of parameters .
- Partial derivative terms: for every parameter .
Recall the index notation for :
- : origin layer (layer mapping from)
- : origin node in layer (node mapping from)
- : destination node in layer (node mapping to)

Each partial derivative term is a single real number.
Vectorized Forward Propagation (Single Training Example)
For a single training example , forward propagation proceeds as follows:

- Layer 1 (Input):
- Layer 2 (Hidden): (add bias unit )
- Layer 3 (Hidden): (add bias unit )
- Layer 4 (Output):

What is Backpropagation?
Backpropagation calculates an error term for each node in layer . Intuitively, measures the "error" in the activation of unit in layer .
Since is an activation computed by the network, we evaluate how far off it is relative to the target:
- The only ground truth target we have is the true label at the output layer .
- For the output layer ( in our example), the error vector is simply:
In vectorized form:
Next, we propagate these errors backward to compute the error vectors for hidden layers:

Where:
- denotes element-wise (pairwise) multiplication (in Octave/MATLAB,
.*). - is the derivative of the sigmoid activation function evaluated at .
- Calculus shows that .
Thus:
Note that there is no term because layer 1 is the input layer, which corresponds to actual features with zero error.
Analyzing Vector Dimensions
Let's check the matrix dimensions in our 4-layer example network ():

- has size (excluding bias column; including bias column).
- has size .
- has size .
- Multiplying yields a vector.
- This matches the dimension of (), allowing element-wise multiplication .
Why Do We Compute Delta Terms?
Through mathematical derivation, if we ignore regularization (), the partial derivative for a single training example is simply:

By computing the activation values during forward propagation and error terms during backpropagation, we get the partial derivative terms needed for gradient descent!
Complete Algorithm: Computing Partial Derivatives for Examples
Given a training set of examples:
![]()
We compute partial derivatives using an accumulator matrix for each layer :
- Initialize Accumulators:
![]()
Set for all . (These matrices will accumulate gradients across examples).
- Loop Over Training Examples:
![]()
For to :
- Set input activation .
- Run forward propagation to compute activations for .
- Compute output error vector: .
- Run backpropagation to compute .
- Accumulate the gradients:
![]()
In vectorized form:

- Compute Final Gradient Matrices :
After exiting the loop over all examples, compute the gradient terms :

- For (bias term, no regularization):
- For (with regularization):

Once computed, each term is exact:
These values are then passed into gradient descent or advanced optimization routines!
Backpropagation Intuition
Let's break down backpropagation step-by-step to gain visual intuition for how errors flow backward through the network.
Visualizing Forward Propagation

Consider a training example with 2 input features (). Forward propagation passes activations forward:

Each hidden node calculates a weighted sum of inputs :
Applying the sigmoid function yields the activation :

Visualizing Backpropagation

For a single output binary classification problem, the cost for a single example simplifies to:
![]()
Conceptually, this measures how well the network performs on example . You can think of it as a sigmoidal version of squared error .
Formally, the delta term represents the partial derivative of the cost with respect to the weighted input sum :

Error Propagation

- At the output layer, is the difference between predicted activation and actual target.
- Going backward, node error is calculated as the weighted sum of errors from the next layer's nodes, weighted by the parameter links connecting them:

Thus, forward propagation computes activation values moving left-to-right, while backpropagation computes error terms moving right-to-left.
Implementation Details: Unrolling Parameters
When using advanced optimization routines in MATLAB/Octave (such as fminunc), the cost function and initial parameter values must be passed as 1D vectors:

However, in neural networks, our parameters and gradients are matrices:

Unrolling and Reshaping Matrices in Octave
Suppose we have a 3-layer neural network with:
- input units
- hidden units
- output unit
The parameter matrix dimensions are:

To convert these matrices into a single unrolled vector for fminunc:
% Unroll matrices into a single vector
thetaVec = [ Theta1(:); Theta2(:); Theta3(:) ];
DVec = [ D1(:); D2(:); D3(:) ];To reshape the vector back into matrices inside your cost function:
% Reshape unrolled vector back into parameter matrices
Theta1 = reshape(thetaVec(1:110), 10, 11);
Theta2 = reshape(thetaVec(111:220), 10, 11);
Theta3 = reshape(thetaVec(221:231), 1, 11);Gradient Checking
Backpropagation is complex and subtle. A small bug in backpropagation can lead to a situation where appears to decrease during gradient descent, but fails to reach a true optimum.
To ensure our backpropagation implementation is 100% bug-free, we use gradient checking.
Numerical Gradient Estimation
Consider a scalar function where . We can estimate the derivative numerically using the two-sided difference:

Typically, is chosen to be small, e.g., .
For a parameter vector , we approximate the partial derivative with respect to each parameter :

Octave Implementation of Gradient Checking

for i = 1:n
thetaPlus = theta;
thetaPlus(i) = thetaPlus(i) + EPSILON;
thetaMinus = theta;
thetaMinus(i) = thetaMinus(i) - EPSILON;
gradApprox(i) = (J(thetaPlus) - J(thetaMinus)) / (2 * EPSILON);
endGradient Checking Protocol
- Implement backpropagation to compute the analytical gradient vector
DVec. - Implement numerical gradient checking to compute
gradApprox. - Verify that
gradApproxDVecto several decimal places. - IMPORTANT: Turn off gradient checking before running learning algorithms to train the model!
Warning: Numerical gradient checking is computationally very expensive because it requires evaluating twice for every single parameter. Backpropagation is far faster and should be used for actual training.
Random Initialization
For linear regression or logistic regression, initializing parameters (all zeros) works fine. However, zero initialization fails completely for neural networks.
The Symmetry Problem
If all weights are initialized to zero:
- Every hidden unit in layer will compute the exact same activation .
- Every hidden unit will receive the exact same error .
- Every weight will undergo identical updates during gradient descent ( will be identical across units).
- The hidden units remain symmetrical and fail to learn distinct features.
Random Initialization Solution (Symmetry Breaking)
To break symmetry, initialize each weight randomly to a small value in :
% Initialize weights randomly in [-epsilon_init, epsilon_init]
Theta1 = rand(10, 11) * (2 * EPSILON_INIT) - EPSILON_INIT;
Theta2 = rand(10, 11) * (2 * EPSILON_INIT) - EPSILON_INIT;
Theta3 = rand(1, 11) * (2 * EPSILON_INIT) - EPSILON_INIT;Putting It All Together
Here is a step-by-step guide to designing and training a neural network.

Step 1: Select Network Architecture
Pick a network layout (connectivity structure between neurons):
- Input units: .
- Output units: .
- Binary classification: 1 output unit.
- Multi-class classification: output units (one-hot vector).
- Hidden layers:
- Default: 1 hidden layer.
- If using multiple hidden layers, recommended to have the same number of hidden units in each hidden layer.
- Number of hidden units: usually equal to or 1.5–2 the number of input features. More hidden units generally improve representation capacity but increase computational cost.
Step 2: Training a Neural Network
- Randomly initialize weights: Small random values near zero (e.g., in ).
- Implement forward propagation: Compute for any input .
- Implement cost function code: Compute .
- Implement backpropagation: Compute partial derivative terms .
% General loop over training set for backpropagation
for i = 1:m
% 1. Forward propagation on (x^i, y^i) to get activation (a) terms
% 2. Backpropagation on (x^i, y^i) to get error (delta) terms
% 3. Accumulate delta: Delta^(l) := Delta^(l) + delta^(l+1) * (a^(l))'
end
% Compute final D matrix partial derivatives with regularization- Perform gradient checking: Compare with numerical gradient approximation
gradApprox. Disable gradient checking once confirmed working! - Minimize : Use gradient descent or advanced optimization algorithms (e.g.,
fminunc, L-BFGS) with backpropagation to minimize as a function of parameters .

Note on Non-Convexity: For neural networks, the cost function is non-convex and can theoretically get stuck in local minima. In practice, gradient descent algorithms initialized with small random weights find very effective local (or global) minima.
Lecture 08: Neural Networks - Representation
An introduction to neural network representation, covering non-linear hypotheses, biological and artificial neuron models, forward propagation, complex non-linear function evaluation, and multiclass classification.
Lecture 10: Advice for Applying Machine Learning
Practical advice and diagnostic techniques for evaluating and improving machine learning algorithms, including train/validation/test splits, bias vs. variance analysis, regularization tuning, and learning curves.