Deep Learning Notes
Deep Learning Notes
Lectures 07–08
Neural Networks with Keras
Arpit Rana
21st January 2026
Based on lecture notes of Dr. Derek Bridge, UCC,
Ireland
These notes cover: Deep Learning Fundamentals · Keras API · Regression · Binary &
Multiclass Classification · Image Processing
IT549: Deep Learning Arpit Rana
0 1 Contents
5 Activation Functions 5
5.1 Sigmoid (logistic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.2 Rectified Linear Unit (ReLU) . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.3 Softmax (output layer for multiclass) . . . . . . . . . . . . . . . . . . . . . 6
5.4 Linear (output layer for regression) . . . . . . . . . . . . . . . . . . . . . . 6
5.5 Summary table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6 Loss Functions 7
6.1 Mean Squared Error (regression) . . . . . . . . . . . . . . . . . . . . . . . 7
6.2 Binary Cross-Entropy (binary classification) . . . . . . . . . . . . . . . . . 7
6.3 Categorical Cross-Entropy (multiclass) . . . . . . . . . . . . . . . . . . . . 7
7 Optimisation Algorithms 7
7.1 Gradient Descent variants . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7.2 Advanced optimisers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.2.1 RMSprop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7.2.2 Adam (Adaptive Moment Estimation) . . . . . . . . . . . . . . . . 8
7.2.3 Comparison table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1
IT549: Deep Learning Arpit Rana
2
IT549: Deep Learning Arpit Rana
1 1 Introduc
to Deep Learning
What is “Deep” in Deep Learning?
The word “deep” in deep learning does NOT mean profound or philosophically
complex. It refers simply to the depth of the neural network — i.e. the number of
layers stacked between the input and the output. A “deep” network has tens or
even hundreds of layers.
2 1 Deep
Learning Setup
2.1 Components of a deep learning model
Formula: Model Decomposition
Model
| {z } = Architecture
| {z } + Parameters
| {z }
complete system number of layers, W1 ,b1 ,
neurons per layer, W2 ,b2 ,
layer types, ...
activation functions
3
IT549: Deep Learning Arpit Rana
where g [l] is the activation function of layer l, a[0] = x(i) , and ŷ = a[L] .
3. Backward pass: compute ∇W[l] L and ∇b[l] L for all l via backpropagation.
Variation Details
Input / Output Raw pixels, normalised scalars, embeddings, one-
hot vectors, etc.
Architecture Dense, CNN, RNN, Transformer; depth and width
choices.
Activation function Sigmoid, ReLU, Tanh, Softmax (output layer),
Leaky ReLU, ELU, GELU.
Optimiser SGD, Momentum, RMSprop, Adam, Nadam,
Adagrad, AdamW.
Loss function MSE, MAE, Binary cross-entropy, Categorical
cross-entropy, Huber loss.
3 1 Logistic
Regression as a Neural Network
3.1 Binary logistic regression
From pixel to prediction
An image is flattened (“image2vector”) to a 1-D vector x(i) ∈ Rn , pixel values are
4
IT549: Deep Learning Arpit Rana
z = w⊤ x(i) + b (3)
1
ŷ = σ(z) = (4)
1 + e−z
If ŷ > 0.5 ⇒ class 1 (e.g. “Coat”); otherwise class 0.
This is simply a neural network with no hidden layers: one input layer and one
output neuron with sigmoid activation.
zk = wk⊤ x(i) + bk , k = 1, . . . , K
Then softmax is applied:
4 1 Neural
Networks: Architecture
4.1 Single hidden layer network
Hidden Layer Notation
For a network with 1 hidden layer of h neurons:
n
X
[1] [1] [1] [1] [1]
Hidden layer: zj = wji xi + bj , aj = g(zj )
i=1
Xh
[2] [1]
Output layer: z [2] = wj aj + b[2] , ŷ = gout (z [2] )
j=1
5
IT549: Deep Learning Arpit Rana
Hidden layers introduce non-linearity, allowing the network to learn complex, curved
decision boundaries.
Each hidden neuron learns a feature of the input; successive layers learn increasingly
abstract features.
2. 1–2 hidden layers: sufficient for most non-linear problems on structured (tab-
ular) data.
3. ≥ 3 hidden layers: use for large datasets (images, text); risk of overfitting
increases.
2
nhidden ≈ nin + nout (Heaton Rule 1)
3
nin < nhidden < nout · nin (Heaton Rule 2)
nhidden < 2 nin (Heaton Rule 3)
5 1 Activatio
Functions
Definition: Activation Function
An activation function g : R → R introduces non-linearity into the network.
Without it, a stack of linear layers collapses to a single linear transformation:
WL · · · W1 x = Weff x.
6
IT549: Deep Learning Arpit Rana
Advantages:
Does not suffer from vanishing gradient for z > 0.
Computationally very cheap (just a thresholding operation).
Sparse activation: roughly 50% of neurons output 0, promoting efficiency and implicit
regularisation.
Disadvantage – Dying ReLU: if a neuron’s pre-activation z is always ≤ 0, its
gradient is always 0 and the neuron never updates (“dies”).
7
IT549: Deep Learning Arpit Rana
6 1 Loss
Functions
6.1 Mean Squared Error (regression)
Formula: MSE
m
1 X (i) 2
LMSE = ŷ − y (i)
m i=1
7 1 Optimisa
Algorithms
7.1 Gradient Descent variants
8
IT549: Deep Learning Arpit Rana
Variant Description
Batch GD Uses the entire training set to compute gradients per
update. Stable but very slow for large datasets.
Stochastic GD Uses one sample per update. Fast but very noisy
(SGD) gradients; may never converge to the exact minimum.
Mini-Batch GD Uses a batch of B samples. Best of both worlds.
Keras default (set via batch size).
8 1 The
Keras Library
9
IT549: Deep Learning Arpit Rana
8.1 Overview
Keras
Keras is a high-level deep-learning API for TensorFlow (and previously Theano /
CNTK). It was created by François Chollet at Google and first released in 2015. It
provides a simple, consistent interface for building, training, and evaluating neural
networks.
Trade-offs:
2. Functional API: define layers as function calls and chain them; supports branching,
multiple inputs/outputs.
3. Model Subclassing: override init and call; full flexibility but most verbose.
5 # 1. Build
6 model = keras . Sequential ([
7 layers . Dense (64 , activation = ’ relu ’ , input_shape =( n_features ,)
),
8 layers . Dense (64 , activation = ’ relu ’) ,
9 layers . Dense ( n_output , activation = ’ softmax ’)
10 ])
11
12 # 2. Compile
13 model . compile (
14 optimizer = keras . optimizers . RMSprop ( learning_rate =0.001) ,
15 loss = ’ s p a r s e _ c a t e g o r i c a l _ c r o s s e n t r o p y ’ ,
16 metrics =[ ’ accuracy ’]
17 )
18
19 # 3. Fit
20 history = model . fit ( X_train , y_train ,
21 epochs =50 , batch_size =32 ,
22 validation_split =0.2)
10
IT549: Deep Learning Arpit Rana
23
24 # 4. Evaluate
25 model . evaluate ( X_test , y_test )
Listing 1: Keras workflow skeleton
Layer Description
Dense(units, Fully connected layer; every input neuron is
activation) connected to every output neuron.
[Link]() Computes mean and variance of training data;
normalises inputs at inference time.
[Link](1/255)Scales pixel values from [0, 255] to [0, 1].
[Link]() Reshapes a multi-dimensional input into 1-D.
9 1 Neural
Network for Regression — House Rent Prediction
9.1 Architecture choice
Input: 3 features — BHK (bedrooms), Size (sq ft), Bathrooms.
2. Initial weights are typically small (∼ N (0, 0.1)); large inputs push pre-activations far
into saturation zones.
11
IT549: Deep Learning Arpit Rana
10 1 Neural
Network for Binary Classification — Class Performance
10.1 Architecture
Input: 3 features — lecture attendance, lab score, CAO points.
12
IT549: Deep Learning Arpit Rana
11 1 Neural
Network for Multiclass Classification — Iris Dataset
11.1 Architecture
Input: 4 features — petal width, petal length, sepal width, sepal length.
12 1 Image
Classification — Fashion MNIST
12.1 Dataset overview
70,000 greyscale images of size 28 × 28 pixels.
10 classes: T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag,
Ankle boot.
13
IT549: Deep Learning Arpit Rana
12.3 Architecture
Layer Type Units Activation
Input Dense (via reshape) 784 —
Hidden 1 Dense 300 ReLU
Hidden 2 Dense 100 ReLU
Output Dense 10 Softmax
14
IT549: Deep Learning Arpit Rana
13 1 Concludi
Remarks on Hyperparameter Selection
Exam Tip
Formulate every deep learning project in terms of five dimensions:
Data → Input → Output → Architecture → Loss function
Key challenges:
2. Free hyperparameters: number of hidden layers, neurons per layer, activation func-
tions in hidden layers, optimiser, learning rate, batch size, number of epochs.
3. Grid/random search: valid but very expensive — larger search space than classical
ML.
15
IT549: Deep Learning Arpit Rana
14 1 100+
Questions and Detailed Answers
How to use this section
Questions are grouped by topic. For each question, read it carefully, write your
own answer, then check against the detailed solution. Questions range from factual
recall (lower Bloom level) to application and analysis (higher Bloom levels).
Answer
“Deep” refers to the number of layers (depth) in the network, not to any philo-
sophical profundity. A deep network has tens or hundreds of layers between input
and output.
Question 2
State the Universal Approximation Theorem and explain its practical limitation.
Answer
The theorem states that a single-hidden-layer network can approximate any con-
tinuous function to arbitrary accuracy — but the required number of neurons may
be exponentially large. In practice, using more layers (depth) achieves the same
approximation power with exponentially fewer parameters, which is the main mo-
tivation for deep networks.
Question 3
Decompose a deep learning model into its constituent parts.
Answer
Model = Architecture + Parameters.
Parameters: the learnable weights W[l] and biases b[l] for every layer l.
16
IT549: Deep Learning Arpit Rana
Question 4
Write out the equations for one full forward pass through a 2-hidden-layer dense
network for binary classification.
Answer
Let input x ∈ Rn :
Question 5
What happens if you remove all activation functions from a multi-layer network?
Answer
The entire network collapses to a single linear transformation:
No matter how many layers you stack, you can only represent a linear mapping,
which is no better than simple linear regression.
Question 6
What is the difference between supervised and unsupervised deep learning?
Answer
Supervised: the training set contains labelled pairs (x(i) , y (i) ). The model learns to
map inputs to labels by minimising a task-specific loss. All examples in the lecture
(regression, binary and multiclass classification) are supervised.
Unsupervised: no labels; the model discovers structure (clusters, generative fac-
tors) from raw data. Examples include autoencoders, GANs, variational autoen-
coders.
Question 7
Define an epoch and a batch in the context of training a neural network.
17
IT549: Deep Learning Arpit Rana
Answer
Epoch: one complete pass through the entire training dataset.
Batch (mini-batch): a subset of B training samples used to compute one gradient
update. After ⌈m/B⌉ batches, one epoch is complete.
Question 8
What is the role of the loss function in training a neural network?
Answer
The loss function L(ŷ, y) quantifies how far the model’s prediction ŷ is from
the true label y. It serves as the objective that gradient descent minimises. The
choice of loss function is determined by the task (regression vs classification) and it
must be differentiable for backpropagation.
Question 9
Why is it important to scale / normalise input features before training a neural
network?
Answer
1. Gradient symmetry: without scaling, features with large magnitude dominate
the gradient, causing elongated, ill-conditioned loss surfaces that are slow to
optimise.
2. Weight initialisation: weights are initialised near zero; large inputs push pre-
activations into saturation regions of sigmoid/tanh, causing vanishing gradients.
3. Learning rate sensitivity: unscaled features force very small learning rates to
prevent divergence.
Question 10
Describe the three main variants of gradient descent and state when each is pre-
ferred.
Answer
Batch GD: gradient computed on all m samples. Very stable, slow for large m.
Good for small datasets or convex problems.
Stochastic GD (SGD): one sample per update. Noisy, can escape local minima,
slow to converge. Rarely used in practice.
Mini-Batch GD: batch size B ∈ [32, 512]. Balances speed and stability. De-
fault in Keras (batch size argument).
18
IT549: Deep Learning Arpit Rana
Question 11
What is overfitting and why are deep networks particularly susceptible to it?
Answer
Overfitting occurs when a model learns the noise in the training data instead of
the underlying pattern, resulting in high training accuracy but poor test accuracy.
Deep networks are susceptible because they have millions of parameters — far
more than the number of training samples in many tasks — giving them the capacity
to memorise training data exactly.
Remedies: dropout, L2 regularisation, early stopping, data augmentation, batch
normalisation, using more data.
Question 12
State the three Heaton rules for choosing the number of hidden neurons.
Answer
Let nin = input features, nout = output neurons:
2
1. nhidden ≈ nin + nout
3
2. nin < nhidden < nin · nout
These are heuristics, not hard rules. Cross-validation should guide the final choice.
Question 13
Why is scikit-learn insufficient for deep learning?
Answer
scikit-learn’s MLPClassifier/MLPRegressor has very limited support:
No GPU acceleration.
Question 14
What is backpropagation and how does it relate to the chain rule?
19
IT549: Deep Learning Arpit Rana
Answer
Backpropagation is the algorithm that efficiently computes gradients ∂L/∂W[l] for
every layer by applying the chain rule of calculus in reverse through the network.
For a single output and one hidden layer:
Question 15
What is the vanishing gradient problem and which activation function helps avoid
it?
Answer
During backpropagation, gradients are multiplied by g ′ (z) at each layer. For sig-
moid, g ′ (z) ∈ (0, 0.25], so the gradient can shrink exponentially as it propagates
through many layers — the “vanishing gradient” problem. Early layers receive
near-zero gradients and learn very slowly.
ReLU has g ′ (z) = 1 for z > 0, so gradients are not compressed (no vanishing) in
the active region. This is the primary reason ReLU is preferred for hidden layers.
Answer
1
σ(z) =
1 + e−z
Derivative (using quotient rule):
e−z 1 e−z
σ ′ (z) =
= · = σ(z) 1 − σ(z)
(1 + e−z )2 1 + e−z 1 + e−z
Question 17
Why is ReLU preferred over sigmoid in hidden layers?
20
IT549: Deep Learning Arpit Rana
Answer
1. No vanishing gradient for z > 0: ReLU′ (z) = 1.
Sigmoid saturates for large |z|, causing near-zero gradients and slowing learning.
Question 18
Explain the Dying ReLU problem.
Answer
[l]
If a neuron’s pre-activation zj is always ≤ 0 (e.g. due to a large negative bias or
large negative weights), then ReLU(z) = 0 and ReLU′ (z) = 0 always. The gradient
is zero, so the neuron’s weights never update. The neuron is said to have “died.”
Solutions: Leaky ReLU (g(z) = max(αz, z) with small α > 0), ELU, or careful
weight initialisation (He/Kaiming initialisation).
Question 19
Write the softmax formula and show that its outputs sum to 1.
Answer
ezk
ŷk = PK
j=1 e zj
Sum:
K K PK zk
X X e zk k=1 e
ŷk = PK = PK z =1 ✓
k=1 k=1 j=1 ezj j=1 e
j
Question 20
For which tasks is each output activation function appropriate?
Answer
Linear (g(z) = z): regression — output must be any real value.
21
IT549: Deep Learning Arpit Rana
Question 21
Why can sigmoid not be used as the output activation for regression?
Answer
Sigmoid squashes any input to (0, 1). If the target variable can be greater than 1 or
negative (e.g. house rent in dollars, temperature in Celsius), the network can never
predict the correct value — its range is fundamentally incompatible.
Question 22
Compare tanh and sigmoid activation functions.
Answer
ez − e−z
tanh(z) = , range: (−1, 1)
ez + e−z
Tanh is zero-centred: outputs in (−1, 1), so mean activation ≈ 0. This avoids
the all-positive gradient issue of sigmoid.
Question 23
What is Leaky ReLU and how does it fix the dying ReLU problem?
Answer
(
z z>0
Leaky ReLU(z) = , α ≈ 0.01
αz z≤0
For z ≤ 0, the gradient is α ̸= 0, so the neuron still receives a small (nonzero)
gradient update even when inactive. The neuron cannot permanently “die.”
Question 24
Explain what softmax does numerically with an example.
Answer
Suppose z = [2.0, 1.0, 0.1] for 3 classes:
22
IT549: Deep Learning Arpit Rana
Question 25
What is the effect of temperature scaling on softmax outputs?
Answer
Temperature T modifies softmax as:
ezk /T
ŷk = P zj /T
je
T = 1: standard softmax.
Question 26
Why is ReLU not appropriate as an output activation for multiclass classification?
Answer
ReLU outputs values in [0, ∞) and does not produce a probability distribution.
Its outputs do not sum to 1, so they cannot be interpreted as class probabilities.
Softmax is specifically designed to produce a valid probability distribution over K
classes, which is required for cross-entropy loss computation.
Question 27
Name two activation functions that are zero-centred and explain why zero-
centredness matters.
Answer
Zero-centred: tanh (range (−1, 1)) and ELU (range (−1, ∞)).
Why it matters: if activations are all positive (like sigmoid), then the gradient
of the loss w.r.t. weights in a layer is either all positive or all negative (same sign
as δ [l] ). This forces weight updates to move only in the “positive quadrant” or
“negative quadrant,” causing zig-zagging and slow convergence.
Question 28
What is GELU and where is it used?
23
IT549: Deep Learning Arpit Rana
Answer
GELU (Gaussian Error Linear Unit):
hp i
GELU(z) = z Φ(z) ≈ 0.5z 1 + tanh 2/π(z + 0.044715z 3 )
where Φ is the CDF of the standard normal. It smoothly gates the input by its
quantile. Used in transformer-based models (BERT, GPT) where it outperforms
ReLU in practice.
Question 29
Explain the concept of “saturating” activation functions.
Answer
A saturating function has regions where g ′ (z) ≈ 0 for large |z|. Sigmoid and tanh
are saturating: for z > 4 or z < −4, the gradient is essentially zero.
This is problematic because:
Question 30
For a binary classification problem with two output neurons (instead of one), what
activation function and loss function would you use?
Answer
Use softmax on the two output neurons, giving probabilities [ŷ0 , ŷ1 ] summing to
1. Loss: sparse categorical crossentropy (or categorical crossentropy with
one-hot labels).
Alternatively, one output neuron with sigmoid + binary crossentropy is equiva-
lent and more common. The two-neuron approach is valid but redundant.
Answer
Assume y (i) ∈ {0, 1}. Model predicts ŷ (i) = P (y = 1|x(i) ).
24
IT549: Deep Learning Arpit Rana
Question 32
When do you use sparse categorical crossentropy vs
categorical crossentropy?
Answer
sparse categorical crossentropy: labels are integers (e.g. y ∈ {0, 1, 2}).
Keras internally one-hot encodes them.
Both compute the same mathematical quantity; the difference is only in how labels
are represented.
Question 33
What is Mean Absolute Error (MAE) and how does it differ from MSE?
Answer
m m
1 X (i) 1 X (i)
MAE = |ŷ − y (i) |, MSE = (ŷ − y (i) )2
m i=1 m i=1
In Keras, MAE is commonly used as a metric (to report), while MSE is the loss
(to optimise).
Question 34
Why is cross-entropy preferred over MSE for classification tasks?
25
IT549: Deep Learning Arpit Rana
Answer
1. Probabilistic grounding: cross-entropy is derived from maximum likelihood
estimation with a Bernoulli/categorical distribution.
Question 35
Write the categorical cross-entropy for a single training example with K = 3 classes.
Answer
Let the true label be class 2 (one-hot: y = [0, 0, 1]) and predictions ŷ = [0.1, 0.2, 0.7]:
3
X
L=− yk log ŷk = −(0 · log 0.1 + 0 · log 0.2 + 1 · log 0.7) = − log(0.7) ≈ 0.357
k=1
Only the term for the true class contributes, which is why cross-entropy is efficient.
Question 36
What is Huber loss and when would you prefer it over MSE?
Answer
(
1
2
− y)2
(ŷ |ŷ − y| ≤ δ
Lδ (ŷ, y) =
δ|ŷ − y| − 12 δ 2 |ŷ − y| > δ
Quadratic for small errors (like MSE), linear for large errors (like MAE).
Use case: regression datasets with outliers. Huber loss is differentiable everywhere
(unlike MAE) and robust to outliers (unlike MSE).
Question 37
Why must the loss function be differentiable?
Answer
Gradient descent requires ∇θ L to update the parameters. If L is not differentiable
(e.g. accuracy = number of correct / total), the gradient is either undefined or zero
almost everywhere, making gradient descent impossible.
This is why accuracy is only used as a metric (for monitoring), never as the training
loss.
26
IT549: Deep Learning Arpit Rana
Question 38
How does the loss landscape differ between MSE and cross-entropy for a sigmoid
output?
Answer
With sigmoid + MSE, the gradient of the loss w.r.t. z includes ŷ(1 − ŷ) from the
chain rule. When ŷ is near 0 or 1 (model is confident but wrong), this term is near
0, causing slow learning.
With sigmoid + cross-entropy, the gradient of L w.r.t. z simplifies to (ŷ − y), which
does not include the saturation term. So when the model is confidently wrong, the
gradient is large (≈ ±1) and learning is fast.
Question 39
Explain label smoothing and why it helps.
Answer
Instead of hard labels yk ∈ {0, 1}, use soft labels:
ϵ
ỹk = yk (1 − ϵ) +
K
with small ϵ ≈ 0.1. This prevents the model from becoming overconfident (assign-
ing probability 1 to one class) and acts as a regulariser, improving generalisation
especially in multiclass settings.
Question 40
What is KL divergence and how does it relate to cross-entropy?
Answer
X P (k) X X
DKL (P ∥Q) = P (k) log =− P (k) log Q(k) + P (k) log P (k)
k
Q(k)
| k {z } |k {z }
cross-entropy H(P,Q) −H(P ), entropy of P
Since H(P ) (entropy of the true distribution) is constant w.r.t. the model parame-
ters, minimising cross-entropy H(P, Q) is equivalent to minimising DKL (P ∥Q), i.e.
making the predicted distribution Q as close to the true distribution P as possible.
Question 41
What is the role of metrics (e.g. accuracy, MAE) vs the loss function in Keras?
27
IT549: Deep Learning Arpit Rana
Answer
Loss function: used to compute gradients and update weights. Must be differ-
entiable.
Metrics: used only for monitoring training progress and evaluating the model.
They do not affect training. Can be non-differentiable (e.g. accuracy).
Question 42
For a multi-label classification problem (each sample may belong to multiple
classes), what loss function would you use?
Answer
Use binary cross-entropy on each output independently, with sigmoid (not soft-
max) on the output layer. Each output neuron independently predicts the proba-
bility of one class, and labels are binary vectors (e.g. [1, 0, 1, 1, 0]). Softmax would
force the probabilities to sum to 1, which is wrong here since multiple classes can
be simultaneously true.
Question 43
Why does increasing the number of epochs not always improve performance?
Answer
Beyond a certain number of epochs, the model begins to overfit: training loss
continues to decrease while validation loss starts to increase. The model memorises
training-set noise rather than generalising.
Solution: early stopping — monitor validation loss and stop training when it
stops improving for p consecutive epochs (patience p).
Question 44
What does the validation split argument in [Link]() do?
Answer
It reserves the specified fraction (e.g. 0.2 = 20%) of the training data as a validation
set used to monitor overfitting after each epoch. Keras evaluates the model on this
held-out portion and reports validation loss and metrics alongside training loss.
This data is not used for gradient updates.
Question 45
Explain the difference between loss and cost in deep learning.
28
IT549: Deep Learning Arpit Rana
Answer
Technically:
Cost
Pm J: (i)the average (or sum) of losses over the entire training set: J =
1
m i=1 L .
Answer
θ ← θ − η ∇θ L
where η is the learning rate and ∇θ L is computed on a single example (true SGD)
or a mini-batch (mini-batch GD).
Question 47
Explain the role of the learning rate η and the consequences of setting it too high
or too low.
Answer
Too high: gradient descent oscillates or diverges — parameters “overshoot” the
minimum and may blow up.
Too low: convergence is extremely slow; training takes too many epochs.
Practical approach: start with η = 0.001 (Keras defaults) and tune with a learning-
rate schedule or grid search.
Question 48
Describe the RMSprop optimiser and state its default learning rate in Keras.
Answer
RMSprop maintains a running average of squared gradients:
29
IT549: Deep Learning Arpit Rana
Update:
η
θt+1 = θt − p gt
E[g 2 ]t + ϵ
This adapts the learning rate per parameter: parameters with large recent
gradients get a smaller effective step, and vice versa.
Default in Keras: η = 0.001, ρ = 0.9, ϵ = 10−7 .
Question 49
What is momentum in gradient descent and why does it help?
Answer
Momentum accumulates a “velocity” vector in the direction of persistent gradients:
vt = γvt−1 + η ∇θ L, θt+1 = θt − vt
Benefits:
Question 50
How does Adam combine momentum and RMSprop?
Answer
Adam maintains both:
Bias-corrected estimates (m̂t , v̂t ) avoid zero-initialization bias in early steps. The
update is:
η
θt+1 = θt − √ m̂t
v̂t + ϵ
Adam is generally the most popular default optimiser due to robust, fast conver-
gence.
Question 51
What is Adagrad and what is its main disadvantage?
30
IT549: Deep Learning Arpit Rana
Answer
Adagrad accumulates the sum of squared gradients:
η
Gt = Gt−1 + gt2 , θt+1 = θt − √ gt
Gt + ϵ
Parameters with frequently large gradients get smaller updates. Good for sparse
data.
Disadvantage: Gt grows monotonically, so the effective learning rate shrinks to
near zero, halting learning prematurely. RMSprop fixes this by using an exponential
moving average instead of a cumulative sum.
Question 52
What is Nadam and how does it differ from Adam?
Answer
Nadam replaces the standard momentum term in Adam with Nesterov momen-
tum. Nesterov momentum “looks ahead”:
It evaluates the gradient at the lookahead position rather than the current position,
which can lead to better convergence, especially near minima.
Question 53
What is the batch size argument in [Link]() and how does it affect training?
Answer
batch size is the number of training samples used per gradient update.
Small batch (e.g. 1–32): noisy gradients; more updates per epoch; better gen-
eralisation (noise acts as regulariser); slower per epoch.
Large batch (e.g. 512–2048): stable gradients; fewer updates; faster per epoch;
may converge to sharp minima that generalise poorly.
Typical: 32–256.
Question 54
What is a learning rate schedule and give two common examples.
Answer
A learning rate schedule changes η during training:
31
IT549: Deep Learning Arpit Rana
Helps avoid oscillation early in training and allows fine-grained convergence later.
Question 55
Explain the concept of a local minimum vs global minimum in the loss landscape.
Answer
Global minimum: the point θ∗ where L is absolutely lowest.
Local minimum: a point where L is lower than all nearby points but not globally
lowest.
In practice, deep networks have loss surfaces with many saddle points and shallow
local minima. Research suggests that in very high dimensions, most local minima
have similar loss values to the global minimum (Dauphin et al., 2014), so deep
networks are not as badly affected by local minima as previously feared.
Question 56
What is a saddle point and how does it affect gradient descent?
Answer
A saddle point is a critical point (∇θ L = 0) that is a minimum in some dimensions
and a maximum in others. Gradient descent can slow dramatically near saddle
points because gradients are near zero.
Optimisers with momentum (Adam, RMSprop) can escape saddle points more ef-
fectively than vanilla SGD.
Question 57
In the House Rent example, the lectures use RMSprop with default learning rate.
What would happen if you used a learning rate of 10?
Answer
A learning rate of 10 is extremely large. The parameter updates θ ← θ − 10 ∇θ L
would wildly overshoot the minimum, likely causing the loss to diverge (“explode”)
rather than decrease. In practice, the loss becomes NaN or inf. Gradient clipping
can partially mitigate this, but the root fix is to use a smaller η.
32
IT549: Deep Learning Arpit Rana
Question 58
What is gradient clipping and when is it used?
Answer
Gradient clipping caps the norm (or absolute value) of gradients before applying
the update:
c
g ← g · min 1,
∥g∥
Used primarily in recurrent neural networks (RNNs) which are prone to ex-
ploding gradients over long sequences. In Keras:
keras . optimizers . RMSprop ( clipnorm =1.0)
Question 59
Explain why adaptive optimisers (Adam, RMSprop) are generally preferred over
vanilla SGD.
Answer
Adaptive optimisers automatically adjust the learning rate per parameter:
This removes the need to hand-tune a single global learning rate and leads to faster,
more robust convergence on most problems. Vanilla SGD requires careful learning
rate tuning and scheduling.
Question 60
When might vanilla SGD outperform Adam?
Answer
Some research (Wilson et al., 2017) shows that SGD with momentum and a tuned
learning rate schedule can generalise better than Adam on image classification
benchmarks. Adam can converge to a sharp minimum (with large Hessian eigenval-
ues) that generalises poorly, while SGD tends to find flatter minima. In practice,
Adam is preferred for fast prototyping; SGD may be preferred for final fine-tuned
models.
33
IT549: Deep Learning Arpit Rana
Answer
1 from tensorflow import keras
2 from tensorflow . keras import layers
3
Question 62
Write Keras code for a binary classification network with normalisation of input.
Answer
1 import tensorflow as tf
2 from tensorflow . keras import layers
3
34
IT549: Deep Learning Arpit Rana
Question 63
Write Keras code for a multiclass network on the Iris dataset using one-hot encoding.
Answer
1 from tensorflow . keras . utils import to_categorical
2 y_train_oh = to_categorical ( y_train , num_classes =3)
3 y_test_oh = to_categorical ( y_test , num_classes =3)
4
Question 64
How do you access training history after calling [Link]()?
Answer
[Link]() returns a History object. Access metrics as:
1 history = model . fit (...)
2 print ( history . history . keys () )
3 # e . g . dict_keys ([ ’ loss ’, ’ mae ’, ’ val_loss ’, ’ val_mae ’])
4
Question 65
What is the purpose of the input shape argument in the first Dense layer?
Answer
input shape tells Keras the shape of one input sample (excluding the batch dimen-
sion), allowing it to:
35
IT549: Deep Learning Arpit Rana
Without it, Keras defers weight creation to the first call (lazy build).
Question 66
What does [Link]() display and why is it useful?
Answer
[Link]() prints:
Question 67
How does Keras’s Normalization layer differ from scikit-learn’s StandardScaler?
Answer
Both standardise inputs to zero mean and unit variance.
Question 68
What is the Functional API and when would you prefer it over the Sequential API?
Answer
1 inputs = keras . Input ( shape =( n ,) )
2 x = layers . Dense (64 , activation = ’ relu ’) ( inputs )
3 x = layers . Dense (64 , activation = ’ relu ’) ( x )
4 outputs = layers . Dense (1) ( x )
5 model = keras . Model ( inputs = inputs , outputs = outputs )
36
IT549: Deep Learning Arpit Rana
Question 69
How do you save and load a Keras model?
Answer
1 # Save entire model ( architecture + weights + compile info )
2 model . save ( ’ my_model . keras ’)
3
4 # Load
5 loaded_model = keras . models . load_model ( ’ my_model . keras ’)
6
Question 70
What is a Keras callback and give two examples used in practice.
Answer
A callback is a function called at certain points during training (end of each epoch,
batch, etc.).
Examples:
1 callbacks = [
2 keras . callbacks . EarlyStopping (
3 monitor = ’ val_loss ’ , patience =10 , r e s t o r e _ b e s t _ w e i g h t s
= True ) ,
4 keras . callbacks . ModelCheckpoint (
5 filepath = ’ best_model . keras ’ , save_best_only = True ) ,
6 keras . callbacks . Reduc eLROnP lateau (
7 monitor = ’ val_loss ’ , factor =0.5 , patience =5)
8 ]
9 model . fit (... , callbacks = callbacks )
Question 71
What is dropout in Keras and how does it act as regularisation?
37
IT549: Deep Learning Arpit Rana
Answer
Dropout randomly sets a fraction p of neurons to 0 during each training step:
1 layers . Dropout ( rate =0.3) # drop 30% of neurons
Regularisation mechanism: forces the network to not rely on any single neuron,
learning redundant representations. At test time, all neurons are active but outputs
are scaled by (1 − p).
Question 72
What does [Link]() return and how does it differ from
[Link]()?
Answer
[Link](X): returns the model’s raw output (e.g. probabilities for clas-
sification, numeric values for regression). No labels needed.
[Link](X, y): computes the loss and metrics on labelled data. Re-
turns scalar values.
Question 73
How would you convert softmax probabilities to class predictions in NumPy?
Answer
1 import numpy as np
2 proba = model . predict ( X_test ) # shape : (m , K )
3 y_pred = np . argmax ( proba , axis =1) # shape : (m ,)
[Link] returns the index of the maximum probability, which corresponds to the
predicted class.
Question 74
What is the Rescaling layer in Keras?
Answer
[Link](scale, offset=0.0) multiplies inputs by scale and adds
offset. Common use case:
1 layers . Rescaling (1./255) # scales pixel [0 ,255] to [0 ,1]
2 layers . Rescaling (1./127.5 , offset = -1) # scales to [ -1 ,1]
Unlike Normalization, Rescaling uses a fixed scale (not computed from data), so
no .adapt() call is needed.
38
IT549: Deep Learning Arpit Rana
Question 75
Explain the Sequential API’s limitation with an example.
Answer
The Sequential API only supports linear, single-input single-output topologies.
Example of what it cannot do: A ResNet skip connection:
The addition of a[l] (a shortcut) is not expressible in the Sequential API; the
Functional API or subclassing is required.
Answer
Input: 10 neurons (one per feature); add Normalization layer.
Question 77
Design the architecture for classifying handwritten digits (0–9) from 28×28 pixel
greyscale images using only dense layers.
Answer
Preprocessing: flatten to 784-D; rescale by 1/255.
Input: 784 neurons.
Hidden 1: 300 neurons, ReLU.
Hidden 2: 100 neurons, ReLU.
Output: 10 neurons, softmax.
39
IT549: Deep Learning Arpit Rana
Metric: accuracy.
Question 78
Why do image classification tasks benefit from convolutional layers rather than
dense layers?
Answer
Dense layers treat each pixel independently and ignore spatial structure. A cat’s
ear at position (10,10) and at (200,200) are treated as completely different features.
Convolutional layers:
1. Are translation equivariant: the same filter detects a feature regardless of its
location.
2. Use weight sharing: one filter applied across the entire image — far fewer
parameters.
3. Exploit local connectivity: pixels near each other are more correlated; local
receptive fields capture spatial patterns.
Question 79
What is the old (pre-deep-learning) computer vision pipeline and how does deep
learning replace it?
Answer
Old pipeline:
Deep networks learn features directly from data. This eliminates the need for
domain-expert-designed feature extractors, leading to better generalisation and
state-of-the-art performance on vision benchmarks.
40
IT549: Deep Learning Arpit Rana
Question 80
Why do we flatten the Fashion MNIST images before feeding them into a dense
network?
Answer
Dense (fully connected) layers expect a 1-D input vector. The Fashion MNIST
images are stored as 2-D arrays of shape (28, 28). Flattening reshapes each image
to a 784-D vector:
flatten
(28, 28) −−−→ (784, )
This discards spatial structure (which is why CNNs are preferred for images), but
allows dense layers to process all pixel values as independent features.
Question 81
Why is it “a bad idea to feed pixel values much larger than initial weights” into a
network?
Answer
Initial weights are typically drawn from N (0, 0.01) or using He/Glorot initialisation
(values near 0). Pre-activations:
X
z= w i xi + b
i
If xi ∈ [0, 255] and wi ≈ 0.01, then z can be very large (up to 784 × 0.01 × 255 ≈
2000). This:
Dividing by 255 brings inputs to [0, 1], matching the scale of initial weights.
Question 82
In the Iris dataset example, the accuracy was reported as ≈ 0.90. Why might this
be considered “not great” for a 3-class problem?
Answer
Iris is a classic, small, very simple dataset.
Classical classifiers (k-NN, SVM, decision tree) routinely achieve 95–100% ac-
curacy on Iris.
90% accuracy means ∼5 errors on 50 test samples, which is worse than a k-NN
classifier.
41
IT549: Deep Learning Arpit Rana
The lecture notes observe that deep learning is often not the best approach
for small, structured/tabular datasets. Classical ML methods (random
forests, gradient boosting) typically outperform neural networks on such data.
Question 83
What neural network architecture would you use for a binary classification problem
where the input is an RGB image of size 224 × 224?
Answer
1. Do not flatten: 224 × 224 × 3 = 150,528 inputs — too many for a dense layer.
Question 84
How many parameters does a Dense layer with 64 input neurons and 32 output
neurons have?
Answer
Weights: 64 × 32 = 2048
Biases: 32 (one per output neuron)
Total: 2048 + 32 = 2080 trainable parameters
Question 85
Given the Fashion MNIST architecture (784 → 300 → 100 → 10), compute the
total number of trainable parameters.
Answer
42
IT549: Deep Learning Arpit Rana
Question 86
What is the purpose of the output layer having exactly K neurons for K-class
classification?
Answer
Each of the K output neurons computes a score zk for one class. After softmax,
ŷk = P (class k|x).
If we used fewer neurons (e.g. K − 1 with threshold rules), the model cannot simul-
taneously represent the probability of all K classes, and training with cross-entropy
requires one output per class. Using exactly K neurons is both mathematically
correct and computationally convenient.
Question 87
What is meant by “compatible consecutive layers”?
Answer
Layer l produces output of shape (batch, dl ). Layer l +1 must accept input of shape
(batch, dl ). If the shapes don’t match, Keras raises a shape mismatch error.
In a Sequential model, each Dense layer takes the previous layer’s output size as its
input size automatically. The only shape you need to specify explicitly is the first
layer’s input shape.
Question 88
What is an “encoding” in the context of deep networks and why is it useful?
Answer
In deep networks, the hidden layers progressively encode the input into increasingly
abstract, compact representations. For example, in image classification:
Layer 1 encodes edges → Layer 2 encodes shapes → Layer 3 encodes parts → Output
layer classifies.
This is useful because:
2. The final hidden layer’s activations can be reused for other tasks (transfer learn-
ing).
Question 89
For structured (tabular) data, why might a random forest outperform a neural
network?
43
IT549: Deep Learning Arpit Rana
Answer
1. Sample efficiency: random forests require less data. Neural networks need
large datasets to outperform classical methods.
Question 90
Describe the five key dimensions to frame a deep learning project (from the lecture).
Answer
1. Data: what is available? how much? is it labelled? what preprocessing?
4. Architecture: how many layers, neurons, what types (dense, CNN, RNN)?
what activation functions?
Answer
2
E[(ŷ − y)2 ] = Bias
| {z } + |Variance
{z } + σ2
|{z}
underfitting overfitting irreducible noise
High bias (underfitting): model too simple; cannot capture the true function.
Fix: increase depth/width, reduce regularisation.
High variance (overfitting): model too complex; memorises noise. Fix: reduce
depth/width, add regularisation, gather more data.
Deep networks have very low bias but high variance — regularisation is crucial.
44
IT549: Deep Learning Arpit Rana
Question 92
What is weight initialisation and why does it matter?
Answer
Weight initialisation sets the starting values of W[l] before training.
Bad initialisation:
Good initialisations:
h q q i
Glorot/Xavier: U − nin +n
6
out
, 6
nin +nout
. For sigmoid/tanh.
q
He/Kaiming: N 0, n2in . For ReLU.
Question 93
What is batch normalisation and what problem does it solve?
Answer
Batch normalisation (BN) normalises the pre-activations z[l] to have zero mean and
unit variance within a mini-batch, then applies a learned scale and shift:
zj − µB
ẑj = p 2 , z̃j = γ ẑj + β
σB + ϵ
Benefits:
Question 94
What is transfer learning and when is it beneficial?
Answer
Transfer learning uses the weights of a model pretrained on a large dataset (e.g.
ImageNet) as the starting point for a new task:
45
IT549: Deep Learning Arpit Rana
When useful:
Similar domain (e.g. medical images from a model trained on natural images).
Early layers learn general features (edges, textures); these transfer well.
Question 95
What is data augmentation and how does it help neural network training?
Answer
Data augmentation artificially expands the training set by applying label-
preserving transformations to existing samples (e.g. random flips, rotations,
crops, colour jitter for images).
Benefits:
In Keras:
1 keras . Sequential ([
2 layers . RandomFlip ( " horizontal " ) ,
3 layers . RandomRotation (0.1) ,
4 layers . RandomZoom (0.2)
5 ])
Question 96
Explain the concept of a “hyperparameter” and distinguish it from a “parameter”.
Answer
Parameters (e.g. weights W, biases b): learned from data via gradient descent
during training.
Hyperparameters (e.g. learning rate, number of layers, neurons per layer, batch
size, dropout rate, activation function): set before training; not learned by gradi-
46
IT549: Deep Learning Arpit Rana
ent descent. Must be tuned via cross-validation, grid search, random search, or
Bayesian optimisation.
Question 97
What is the “no free lunch” theorem and its implication for deep learning?
Answer
The No Free Lunch (NFL) theorem states that no learning algorithm performs best
on all possible problems. An algorithm that outperforms others on some problems
must necessarily perform worse on others.
Implication for deep learning: deep networks are not universally superior. For
small, structured/tabular datasets, classical ML (gradient boosting, SVMs) often
outperforms neural networks (as observed in the Iris example). The choice of model
should be guided by the data characteristics, not fashion.
Question 98
What is the difference between underfitting and overfitting, and how can you detect
each from training curves?
Answer
Underfitting Overfitting
Train loss High Low
Val loss High High (but > train)
Gap Small Large
Fix More capacity Regularise / more data
In training curves: overfitting appears as the validation loss curve diverging upward
while the training loss continues to decrease.
Question 99
What is L2 regularisation (weight decay) and write its modified loss function.
Answer
L2 regularisation adds a penalty proportional to the squared magnitude of all
weights: X
Lreg = Loriginal + λ ∥W[l] ∥2F
l
47
IT549: Deep Learning Arpit Rana
Question 100
What is L1 regularisation and how does it differ from L2?
Answer
X
LL1 = L + λ ∥W[l] ∥1
l
Question 101
Explain how to use early stopping in Keras and describe the patience parameter.
Answer
1 es = keras . callbacks . EarlyStopping (
2 monitor = ’ val_loss ’ ,
3 patience =10 , # wait 10 epochs for
improvement
4 re s t o r e _ b e s t _ w e i g h t s = True # revert to best checkpoint
5 )
6 model . fit ( X_train , y_train , epochs =1000 , callbacks =[ es ])
patience=10: if the monitored metric does not improve for 10 consecutive epochs,
training stops. restore best weights=True restores the weights from the epoch
with the best validation loss, avoiding the model’s degraded state at the stopping
point.
Question 102
What is one-hot encoding and why is it used for categorical class labels?
Answer
One-hot encoding represents a class label k ∈ {0, 1, . . . , K − 1} as a binary vector
of length K with a 1 only at position k:
k = 2, K = 4 ⇒ [0, 0, 1, 0]
Why: integer labels (0, 1, 2, . . . ) imply an ordinal relationship that does not
exist between unordered classes. One-hot encoding treats all classes as equidistant.
Required when using categorical crossentropy loss.
48
IT549: Deep Learning Arpit Rana
Question 103
What is the Fashion MNIST classification task and what accuracy is typically
achievable with a dense network vs a CNN?
Answer
Task: classify 28×28 greyscale fashion images into 10 categories.
CNNs exploit spatial structure and are far more parameter-efficient, leading to
better performance on image data.
Question 104
What is the purpose of the [Link]() step in Keras?
Answer
[Link]() configures the model for training by specifying:
Question 105
What are the class labels in the Fashion MNIST dataset?
Answer
The 10 classes (integer labels 0–9) are:
49
IT549: Deep Learning Arpit Rana
Label Class
0 T-shirt/top
1 Trouser
2 Pullover
3 Dress
4 Coat
5 Sandal
6 Shirt
7 Sneaker
8 Bag
9 Ankle boot
Question 106
Why does the Fashion MNIST dataset not need a Normalization layer?
Answer
All features (pixel values) are in the same range [0, 255]. Normalisation addresses
the problem of features on different scales. Since all pixels share the same scale,
feature-wise standardisation is not strictly necessary.
However, it is still a good idea to rescale to [0, 1] by dividing by 255 (using a
Rescaling layer or manual division), because values of 255 are much larger than
typical initial weights.
Question 107
Compare the Keras Sequential API, Functional API, and Model Subclassing.
Answer
Question 108
Describe three ways to prevent overfitting in a Keras deep learning model.
50
IT549: Deep Learning Arpit Rana
Answer
1. Dropout: randomly zero out neurons during training. [Link](0.3)
Question 109
What is the significance of the “holdout” strategy for Fashion MNIST?
Answer
Fashion MNIST has 70,000 samples — large enough that holdout validation
(splitting into fixed train/test sets) provides a reliable, low-variance estimate of
generalisation performance.
For small datasets (like Iris, 150 samples), holdout gives high-variance estimates;
k-fold cross-validation is preferred.
The Fashion MNIST dataset comes pre-partitioned into 60,000 training and 10,000
test images, so we use these canonical splits directly.
Question 110
Summarise the constrained vs free hyperparameters in designing a Keras neural
network.
Answer
Constrained (determined by the task):
51
IT549: Deep Learning Arpit Rana
Batch size.
52
IT549: Deep Learning Arpit Rana
14 1 Quick
Reference Cheat Sheet
Output Layer Quick Reference
ez − e−z
tanh(z) = , LeakyReLU(z) = max(αz, z)
ez + e−z
model . compile (
optimizer = ’ rmsprop ’ # or Adam , SGD , ...
| keras . optimizers . RMSprop ( learning_rate
=0.001) ,
loss = ’ mse ’
| ’ b i n ar y _ cr o s se n t ro p y ’
| ’ sparse_categorical_crossentropy ’
| ’ categorical_crossentropy ’,
metrics = [ ’ mae ’] # regression
| [ ’ accuracy ’] # classification
)
End of Notes
Arpit Rana · IT549 Deep Learning · Jan 2026
53