Understanding Deep Neural Networks
Understanding Deep Neural Networks
In simple terms:
• A DNN is just a neural network with more than one hidden layer —
allowing it to “go deeper” into understanding data.
Input Layer → Hidden Layer 1 → Hidden Layer 2 → Hidden Layer 3 → ... → Output Layer
Structure of Deep Neural Networks
• Deep learning automatically finds the important features for
classification because of deep neural networks, whereas in Machine
Learning, we had to define these features manually.
• As shown in the image above, Deep Learning works as follows:
1. At the lowest level, the network fixates on patterns of local contrast as
important.
2. The following layer is then able to use those patterns of local contrast to
fixate on things that resemble eyes, noses, and mouths
3. Finally, the top layer can apply those facial features to face templates.
4. A deep neural network is capable of composing more and more complex
features in each of its successive layers.
Example: Image Classification (Cat vs Dog)
• Let’s say you are training a DNN to identify whether an image is of a cat or a dog.
Feature Learning Features are often manually extracted. Features are automatically learned from data.
Complexity Suitable for simple problems. Suitable for complex and large-scale problems.
Computation Time Requires less computation. Requires high computation power (GPUs).
Training Data Works with small datasets. Needs large datasets for good performance.
Example Predicting house price using few input variables. Image recognition, NLP, speech recognition.
3. Computational Resources
• Training deep learning models demands significant computational power and
resources. This can be expensive and inaccessible for many organizations. High-
performance hardware like GPUs and TPUs is often necessary to handle the
intensive computations.
4. Interpretability
• Deep learning models often function as "black boxes," making it difficult to
understand how they make decisions. This lack of transparency can be
problematic, especially in critical applications. Understanding the decision-making
process is crucial for trust and accountability.
5. Hyperparameter Tuning
• Finding the optimal settings for a model’s hyperparameters requires expertise.
This process can be time-consuming and computationally intensive.
Hyperparameters significantly impact the model’s performance, and tuning them
effectively is essential for achieving high accuracy.
6. Scalability
• Scaling deep learning models to handle large datasets and complex tasks
efficiently is a major challenge. Ensuring models perform well in real-world
applications often requires significant adjustments. This involves optimizing both
algorithms and infrastructure to manage increased loads.
7. Ethical and Bias Issues
• Deep learning models can inadvertently learn and perpetuate biases
present in the training data. This can lead to unfair outcomes and ethical
concerns. Addressing bias and ensuring fairness in models is critical for
their acceptance and trustworthiness.
8. Hardware Limitations
• Training deep learning models requires substantial computational
resources, including high-performance GPUs or TPUs. Access to such
hardware can be a bottleneck for researchers and practitioners.
9. Adversarial Attacks
• Deep learning models are susceptible to adversarial attacks, where subtle
perturbations to input data can cause misclassification. Robustness against
such attacks remains a significant concern in safety-critical applications.
Strategies to Overcome Deep Learning Challenges
• Addressing the challenges in deep learning is crucial for developing
effective and reliable models. By implementing the right strategies, we
can mitigate these issues and enhance the performance of our deep
learning systems.
• Here are the key strategies:
1.
2.
3.
4.
5.
6.
7.
Model Parameters Vs Hyperparameters
• The two most confusing terms in Machine Learning are Model
Parameters and Hyperparameters.
• In deep neural networks, the distinction between parameters and
hyperparameters is fundamental to understanding how these models
learn and are constructed.
1. Model Parameters
• Parameters are the internal variables of the model that are learned directly
from the training data during the training process as the algorithm used
tries to remember the mapping between the input features and the labels
or targets..
• They represent the model's internal state and are adjusted to minimize the
error between the model's predictions and the actual target values.
Parameter Learning and Training Process:
1. Model training typically starts with parameters being initialized to some
values (random values or set to zeros).
2. As training/learning progresses, the initial values are updated using an
optimization algorithm (e.g., gradient descent).
3. The learning algorithm is continuously updating the parameter values as
learning progresses but hyperparameter values set by the model
designer remain unchanged.
4. At the end of the learning process, model parameters are what
constitute the model itself.
Learning Outcome of Model Parameters:
• Parameters are updated iteratively during training using optimization
algorithms like Gradient Descent and its variants (e.g., Adam,
RMSprop), often guided by backpropagation.
Examples of parameters
1. The coefficients (or weights) of linear and logistic regression
models.
2. Weights and biases of an NN
3. The cluster centroids in clustering
2. Hyperparameters
• Hyperparameters are external configuration variables that the
practitioner sets before the training process begins.
• They control the overall structure of the model and the learning
process itself, influencing how the parameters are learned.
• The prefix ‘hyper_’ suggests that they are ‘top-level’ parameters that
control the learning process and the model parameters that result
from it.
• As a machine learning engineer designing a model, you choose and
set hyperparameter values that your learning algorithm will use
before the training of the model even begins.
• In this light, hyperparameters are said to be external to the model
because the model cannot change its values during learning/training.
Learning Hyperparameters in a Model
• Hyperparameters are not learned from the data but are typically
chosen through experimentation, domain knowledge, or systematic
search techniques like grid search, random search, or Bayesian
optimization.
• Hyperparameters are used by the learning algorithm when it is
learning but they are not part of the resulting model.
• At the end of the learning process, we have the trained model
parameters which effectively is what we refer to as the model.
• The hyperparameters that were used during training are not part of
this model.
Examples of Hyperparameters in Deep Neural Networks:
1. Weights and Biases
2. Train-test split ratio
3. Learning rate in optimization algorithms (e.g., gradient descent)
4. Choice of optimization algorithm (e.g., gradient descent, stochastic gradient descent,
or Adam optimizer)
5. Choice of activation function in a neural network (NN) layer (e.g., Sigmoid, ReLU, Tanh)
6. The choice of the cost or loss function that the model will use
7. Number of hidden layers in a NN
8. Number of activation units in each layer
9. The drop-out rate in NN (dropout probability)
10. Number of iterations (epochs) in training a nn
11. Number of clusters in a clustering task
12. Kernel or filter size in convolutional layers
13. Pooling size
14. Batch size
Summary
• Basically, anything in machine learning and deep learning that you
decide their values or choose their configuration before training
begins, and whose values or configuration will remain the same when
training ends, is a hyperparameter.
Greedy layer-wise training (GLWT)
• Before the development of modern GPUs and techniques like dropout
and ReLU activations, training deep networks (with many layers) was
extremely difficult due to:
Poor weight initialization
Limited labeled data
Training deep networks from scratch using backpropagation often
failed.
Problems like vanishing gradients/exploding gradients, slow
convergence, and poor generalization occurred.
• To solve this, researchers, notably Geoffrey Hinton around 2006)
proposed Greedy Layer-Wise Training — a way to train deep neural
networks one layer at a time in an unsupervised or semi-supervised
fashion.
Greedy layer-wise training (GLWT)
• Instead of training all layers of a deep network together,
we train one layer at a time — greedily — meaning each layer tries
to do its best without waiting for the others.
• Each layer learns to represent the data slightly better (more
abstractly) than the previous one.
• Assume you have a deep neural network with multiple hidden layers:
Input → Layer 1 → Layer 2 → Layer 3 → Output
5. Generative Adversarial
Learns to generate new data similar to
Network (GAN) (partially Image generation, data synthesis
input examples.
unsupervised)
Working of GLWT (cont.)
2. Freeze the first layer and use its output as input to train the second
layer.
Layer 2 learns higher-level features from the representation of Layer 1.
Working of GLWT
3. Continue this process for each layer.
Each layer is trained independently.
Repeat this process for all hidden layers: each time using the output of the
previous layer as the input for the next.
4. Fine-tuning
After all layers are pretrained:
Stack them together to form the full network.
Now fine-tune the entire model using supervised learning (backpropagation)
on labeled data.
This adjusts all weights slightly to improve final performance.
Final Verdict
• Greedy Layer-Wise Training is a bottom-up unsupervised pretraining
method where each layer learns independently to extract meaningful
features, and the full network is later fine-tuned using supervised
learning.
Example: Greedy Layer-Wise Training using
Autoencoders
• Let’s take a simple example: Suppose we want to build a Deep
Autoencoder for MNIST handwritten digits (28×28 images).
Fine-tune
• Stack encoders: Input(784) → 500 → 250 → 100 → Output(10)
• Add a softmax layer for digit classification.
• Train the whole network using backpropagation on labeled data (digits 0–
9).
Advantages of GLWT
1. Solves vanishing gradients: It provides a better initialization for
deep networks, which helps prevent the vanishing gradient problem
during the subsequent supervised training phase.
2. Improved accuracy: It can lead to better model accuracy compared
to training a deep network from random initialization.
3. Data efficiency: It is particularly useful when you have a lot of
unlabeled data and a smaller amount of labeled data.
4. Faster training: Pre-training with good initial weights can speed up
the overall training process.
Limitations of GLWT
1. Computational cost: Pre-training each layer can be computationally
intensive.
2. Requires large datasets: While it can be used with small labeled
datasets, the unsupervised pre-training stage still requires a large
amount of data to be effective.
3. Not always necessary: With the advent of other techniques like
improved activation functions and architectures, the need for this
specific pre-training method has decreased for many modern deep
learning tasks.
Recurrent Neural Networks
(RNNs)
Types of Neural Networks
• There are three types of widely used Neural Networks:
Main Layers Used Dense (fully connected) Convolution + Pooling Recurrent (with feedback)
Simple Feed Forward Neural Network architecture. Simple Recurrent Neural Network architecture.
First, let’s remind ourselves what a typical Feed Forward Neural Network looks like. Note
that it can contain any number of input nodes, hidden nodes, and output nodes. The below
2–3–2 structure is purely for illustration.
Simple Feed Forward Neural Network architecture. Simple Recurrent Neural Network architecture.
Next, if we look at RNN, we notice a slight difference. The hidden units inside RNN have a
built-in feedback loop, enabling the information to be passed back to the same node multiple
times. These hidden units are commonly called RECURRENT UNITS.
Recurrent unit operation
• A recurrent unit processes information for a predefined number of timesteps,
each time passing a hidden state and an input for that specific timestep through
an activation function.
• Timestep – single processing of the inputs through the recurrent unit. E.g., if you
have only one timestep, your inputs will be processed only once (equivalent to a
regular hidden node). If you have 7 timesteps, your inputs will be processed 7
times. See the illustration below showing the feedback loop inside the recurrent
unit:
• The basic idea of the forward pass in an RNN is to compute the hidden state
values at each time step, i.e., ht. So, considering this idea, the general
formula for performing forward propagation through the hidden states will
be
• Simple, just computing the dot product between Woh and ht plus a bias bo.
The ϕ is basically the activation function, which can be any function
according to the problem you are trying to solve. For instance, you can use
sigmoid or SoftMax if you are dealing with probability problems.
Backward pass
• Let's figure out how to derive BPTT in RNN. The first thing we need to do
is to choose a Loss function. Here, we choose the Mean Squared Error
(MSE) Loss.
• For propagating the loss backward, we need to find the derivative of loss;
the derivative of MSE is simply,
Here is a way to understand the flow of gradients in a single time step,
When dealing with multiple time steps, the gradients of each time step should
be summed up.
The generalized formula is:
Updating Weights and Bias Using Gradient Descent
The update rule is quite similar across different types of neural networks, including
recurrent neural networks (RNNs), with some variations depending on the
optimization algorithm used. Since we are using Gradient Descent, the update rule
will be,
Output Output Output
We can visualize
each time step as a
collection of Feed
Forward Neural
Networks where the
hidden layers of
each network are
connected together.
Now if you flatten it
you'll get something
like this, on the right.
• On the left side is a recurrent neuron, and on the right-hand side is the recurrent
neuron unrolled through time.
• This adds some inherent “memory” in the system that aids the model in picking up
historical patterns that happened previously in time.
• When predicting Y1, the recurrent neuron uses the inputs of X1 and the output from
the previous time step, Y0. This means that Y0′s influence on Y1 is direct, and it also
indirectly influences Y2.
Backpropagation is applied
to each time step, starting
from the last one and
moving backward to the
first. This process is known
as Backpropagation
Through Time.
Why tanh (Hyperbolic Tangent) used as
Activation Function?
• The hyperbolic tangent (tanh) activation function is frequently employed in
Recurrent Neural Networks (RNNs) due to several key advantages:
1. Zero-Centered Output: Tanh outputs values ranging from -1 to 1. This
zero-centered property aids in the optimization process during training, as it
can lead to more stable and efficient weight updates compared to activation
functions like sigmoid, which output values between 0 and 1. The gradients
tend to oscillate less, potentially leading to faster convergence.
2. Stronger Gradients: Compared to the sigmoid function, tanh exhibits
steeper gradients across a larger portion of its domain. This characteristic
can result in faster learning and convergence during the backpropagation
through time (BPTT) process in RNNs.
3. Better Representation of State Changes: In RNNs, the hidden state acts as
a form of memory, carrying information from previous time steps. The ability
of tanh to output both positive and negative values (between -1 and 1)
allows for a more nuanced and precise representation of changes in the
hidden state. This can be particularly beneficial for modeling complex
temporal dependencies and sequences.
4. Differentiability for Gradient-Based Optimization: Tanh is a differentiable
function, which is a prerequisite for using gradient-based optimization
algorithms like stochastic gradient descent (SGD) to train neural networks,
including RNNs.
While tanh offers advantages, it is important to note that it can still suffer
from the vanishing gradient problem, especially in very deep RNNs or when
dealing with extremely long sequences. This occurs when the gradients
become very small, hindering effective learning in earlier layers. However,
the zero-centered output and stronger gradients of tanh often make it a
more effective choice than sigmoid for hidden layers in many RNN
architectures.
Problems in BPTT
BPTT faces two common issues when applied to long sequences. When we
train it using Backpropagation Through Time (BPTT), gradients either cause:
1. Vanishing Gradient Problem: When gradients become very small as they’re
multiplied through time, the network “forgets” early information.
2. Exploding Gradient Problem: When gradients grow too large, and cause
unstable training.
As a result, simple RNNs can’t learn long-term relationships in sequences (like
meaning in long sentences).
Solution:
Step Description
Converts each word into a numeric vector (e.g., using Word2Vec, GloVe, or
2. Word Embedding Layer
learned embeddings).
3. RNN Layer (LSTM/GRU) Processes words one by one, maintaining context through hidden states.
For each word, outputs a probability distribution over entity labels (e.g.,
4. Output Layer
PERSON, ORG, LOC, O).
5. Prediction The label with the highest probability is chosen for each word.
Example Sentence and Flow
Let’s take:
“Barack Obama visited Delhi.”
Step 2: Embedding
Barack (PERSON)
Obama (PERSON)
visited (O)
Delhi (LOCATION)
6. Part-of-Speech (POS) Tagging
• Assigns grammatical tags to words.
Example:
“She eats apples.”
→ She (PRONOUN), eats (VERB), apples (NOUN)
Why RNNs work well:
They learn that:
“She” likely precedes a verb.
“Eats” is followed by a noun.
Common architectures:
RNN
BiLSTM
GRU
Long Short-Term Memory (LSTM)
Problems of RNN
Problem Explanation Example
During backpropagation, gradients (used
In a long sentence, RNN forgets the
to update weights) become extremely
1. Vanishing Gradient Problem subject when reaching the verb at the
small → the network “forgets” early
end.
information.
Some mes gradients become very large → The model gives NaN (not-a-number)
2. Exploding Gradient Problem
unstable training and weight overflow. or diverges.
RNNs remember only recent inputs — In “The man who went to the park is
3. Short-Term Memory they can’t capture long-term tall,” the word “man” should link to “is
dependencies. tall,” but RNN forgets it.
Simple RNNs treat all previous data
Doesn’t know that “not” changes
4. Difficulty in Learning Context equally, can’t decide what to remember or
meaning of “good” in “not good.”
forget.
Gradients must pass through every time
5. Slow Training for Long Large text data takes a long time to
step → slow and inefficient for long text or
Sequences converge.
time-series.
Long Short-Term Memory (LSTM)
• LSTM stands for Long Short-Term Memory.
• It is a special kind of Recurrent Neural Network (RNN) that is very good at
remembering information for a long time.
• LSTMs introduce memory cells that can store information over long periods,
thereby addressing issues like vanishing gradients during backpropagation.
• It is mainly used when the data comes in a sequence — for example:
A sentence (sequence of words)
A sound clip (sequence of audio samples)
A video (sequence of frames)
A stock price over time
• LSTM fixes the “forgetfulness” of RNNs —
it helps the model remember important things for long and ignore the rest,
making it perfect for language, time-series, and sequential data.
Why do we need LSTM?
• A normal RNN can remember only short-term information.
When the sequence becomes long, the RNN forgets the earlier
information — this is called the vanishing gradient problem.
Example:
In the sentence — “The movie that I watched yesterday was amazing”
The word “amazing” refers to “movie,” which came a long time before.
A simple RNN often forgets “movie” by the time it reads “amazing.”
• LSTM solves this problem by adding a memory cell — a special
structure that can decide what to remember and what to forget.
How LSTM Works??
• The LSTM architectures involve the memory cell which is controlled by three gates, as
shown in the image below, and each part performs an individual function.
Previous Cell State Updated Cell State
Where:
𝑊 represents the weight matrix associated with the forget gate.
ℎ −1, 𝑥 denotes the concatenation of the current input and the previous hidden state.
𝑏 is the bias with the forget gate and 𝜎 is the sigmoid activation function.
2. Input gate
• The addition of useful information to the cell state is
done by the input gate.
• First the information (it) is regulated using the sigmoid
function and filter the values to be remembered similar
to the forget gate using inputs and .
• Then, a vector (Ct) is created using tanh function that
gives an output from -1 to +1 which contains all the
possible values from and .
• At last the values of the vector and the regulated
values are multiplied to obtain the useful information.
• The equation for the input gate is:
3. Output gate
• The output gate is responsible for deciding what part of the current
cell state should be sent as the hidden state (output) for this time
step.
• First, the gate uses a sigmoid function to determine which information
from the current cell state will be output.
• This is done using the previous hidden state ℎ and the current
input 𝑥 :
• Next, the current cell state 𝐶 is passed through a tanh activation to scale
its values between −1 and +1.
• Finally, this transformed cell state is multiplied element-wise with 𝑜 to
produce the hidden state ℎ :
1. The forget gate decides which old notes are no longer needed.
(“Forget unimportant topics, not in the syllabus!”)
2. The input gate decides which new notes to keep.
(“This new chapter on probability looks important.”)
3. The cell state is like the notebook where the student writes important
information.
4. The output gate decides what to recall in the exam.
(“From all I know, this formula seems useful now.”)
Here:
• is the input token and is the output token
• and are Forward and backward LSTM units
•The final output of is the combination of and LSTM nodes.
A Bidirectional LSTM (BiLSTM) consists of two separate LSTM layers:
1. Forward LSTM: Processes the sequence from start to end
2. Backward LSTM: Processes the sequence from end to start
• The outputs of both LSTMs are then combined to form the final output.
Mathematically, the final output at time t is computed as:
Where:
• :Final probability vector of the network.
• :Probability vector from the forward LSTM network.
The combined output gives context from both past and future, leading
to better predictions or understanding.
LSTM Vs BiLSTM
Formula:
• Creates a new candidate memory using the current input and the previous
memory (controlled by the reset gate).
• Combines old memory and new memory using the update gate.
Applications of GRU Limitations of GRU
• Text and Speech Processing • Sometimes less accurate for
• Sentiment analysis very long sequences
• Machine translation • Slightly less flexible than LSTM
• Chatbots and text generation (no separate long-term
• Time-Series Forecasting memory)
• Stock prices, weather prediction
• Sequential Data Tasks
• Speech recognition
• Handwriting recognition
Key Differences Between GRU and LSTM
Performance Slightly better for complex tasks Almost equal in many tasks