Deep Learning Unit 1 Notes
Deep Learning Unit 1 Notes
Introduction to Data Handling – Data processing and Normalization using Deep Learning libraries
– Data Augmentation Techniques – Deep Learning Frameworks – PyTorch – TensorFlow – Keras
– Deep Learning Parameters – Epoch – Learning rate – Batch size – Deep Networks – Introduction
to Neural Networks– Deep Feed-forward Networks – Learning XOR – Gradient-Based learning –
Hidden Units – Activation Functions – Sigmoid – Tanh – ReLU –Leaky ReLU – Softmax.
[Link] TO DATA HANDLING
Data handling in deep learning refers to the systematic process of acquiring, cleaning, organizing,
transforming, and preparing data to train deep learning models effectively. The success of deep
learning models depends heavily on the quality and quantity of data and how well it is handled
before feeding into the models.
1. Data Collections
Data collection is the process of gathering and measuring information from a variety of sources to
obtain a complete dataset suitable for deep learning.
Sources of Data:
Source Description
Sensors/IoT
Real-time data from devices (e.g., temperature, pressure, ECG sensors).
Devices
Web Scraping Extracting structured/unstructured data from websites using scripts or tools.
APIs Accessing external data via services (e.g., Twitter API, Google Maps API).
Databases Structured data from SQL or NoSQL databases.
Datasets made available by research or academic institutions (e.g., MNIST,
Public Datasets
CIFAR-10, ImageNet).
Manual
Surveys, questionnaires, human labeling, and experiments.
Collection
Importance:
● The accuracy of deep learning models is directly related to the quality, quantity, and
variety of data collected.
2. Data Preprocessing
Data preprocessing involves transforming raw data into a clean, understandable, and machine-
readable format before feeding it into a model.
➤ Steps in Preprocessing:
1. Data Cleaning:
o Handle missing values (e.g., by imputation or deletion).
o Remove duplicate records.
o Correct inconsistent data (e.g., typos in categorical variables).
2. Noise Removal:
o Eliminate outliers or errors in data.
o Apply smoothing techniques (especially in time-series or image data).
3. Feature Engineering:
o Create new relevant features from existing data.
o Remove irrelevant or redundant features.
4. Encoding Categorical Variables:
o Convert categorical data into numerical format using:
▪ Label Encoding
▪ One-Hot Encoding
5. Data Formatting:
o Standardize the format (e.g., all text to lowercase, image resizing).
o Convert to appropriate data types (e.g., integer, float).
6. Data Shuffling:
o Randomize data to prevent the model from learning any order-based bias.
7. Splitting the Dataset:
o Training Set: To train the model.
o Validation Set: To tune hyperparameters.
o Test Set: To evaluate final performance.
Normalization: Normalization is the process of scaling individual input features so that they fall
within a specific range or distribution. It helps to speed up convergence, reduce numerical
instability, and improve model performance.
# PyTorch example:
transform = [Link](mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
Benefits of Normalization:
1
● Improves stability in optimization algorithms.
Summary
Component Purpose
Data Collection Gather high-quality data from various sources.
Preprocessing Clean, encode, and prepare data for modeling.
Normalization Scale features to a standard range for stable and fast model training.
Overview:
Deep learning libraries provide powerful tools for data loading, preprocessing, transformation, and
normalization. They offer high-level APIs that automate many of the tasks involved in preparing
data for deep neural networks. Efficient data processing is essential for reducing training time,
improving accuracy, and enhancing model generalization.
Popular frameworks:
● PyTorch
● TensorFlow
● Keras
Libraries/Tools Used:
2
● [Link]: For loading datasets
● [Link]: For preprocessing and augmentation
● DataLoader: For efficient data batching and shuffling
Common Steps:
# Load dataset
dataset = [Link](root='./data', train=True, download=True, transform=transform)
# Create DataLoader
loader = DataLoader(dataset, batch_size=64, shuffle=True)
Libraries/Tools Used:
Example Pipeline:
import tensorflow as tf
# Load dataset
(train_images, train_labels), _ = [Link].load_data()
3
C. Data Processing in Keras
Tool: ImageDataGenerator
Example:
2. Normalization in Practice
What is Normalization?
Normalization is a preprocessing step to bring all feature values into a similar range, which
stabilizes and speeds up learning.
PyTorch:
4
TensorFlow:
Keras:
Overview:
Data Augmentation is the process of artificially increasing the size and diversity of a training dataset
by applying transformations or modifications to the existing data. It is especially useful when the
dataset is small or prone to overfitting.
5
1. Need for Data Augmentation
Overfitting on training data Increases generalization by exposing the model to varied inputs
A. Geometric Transformations
Technique Effect
Technique Effect
Contrast Modification Adjusts the difference between dark and light regions
C. Noise Injection
● Randomly masks out parts of the image (patches) to force the model to focus on multiple
features.
Technique Description
Creates new training samples by linearly combining pairs of images and their labels.
Mixup
Helps smooth decision boundaries.
CutMix Cuts and pastes patches from one image onto another, mixing their labels accordingly.
PyTorch ([Link]):
transform = [Link]([
[Link](),
[Link](15),
[Link](32, padding=4),
[Link](brightness=0.2, contrast=0.2, saturation=0.2),
[Link]()
])
import tensorflow as tf
Manual augmentation
image = [Link].random_flip_left_right(image)
image = [Link].random_brightness(image, max_delta=0.1)
image = [Link].random_contrast(image, 0.9, 1.1)
Keras:
7
from [Link] import ImageDataGenerator
datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
Summary Table
● Reduces overfitting
● Improves model generalization
● Makes model robust to noise and variations
● Allows better performance on limited data
● Simulates real-world scenarios
Limitations
Deep Learning frameworks are software libraries that simplify the process of building, training,
and deploying deep learning models. They provide:
1. PyTorch
Introduction:
Key Features:
Key Modules:
Module Purpose
10
Module Purpose
import [Link] as nn
class Net([Link]):
def __init__(self):
super(Net, self).__init__()
self.fc1 = [Link](784, 128)
[Link] = [Link]()
self.fc2 = [Link](128, 10)
2. TensorFlow
Introduction:
Key Features:
Key Modules:
11
Module Purpose
import tensorflow as tf
model = [Link]([
[Link](128, activation='relu', input_shape=(784,)),
[Link](10, activation='softmax')
])
3. Keras
Introduction:
Key Features:
Model APIs:
python
CopyEdit
from [Link] import Sequential
from [Link] import Dense
12
model = Sequential([
Dense(64, activation='relu', input_shape=(784,)),
Dense(10, activation='softmax')
])
Summary Table
Framework Best For Strengths Limitations
Beginners, fast
Keras Simplicity, readability Less control (only high-level)
prototyping
Choosing the right framework depends on the project requirements, experience level, and desired
scalability.
13
[Link] LEARNING PARAMETERS
Training a deep learning model involves optimization using iterative algorithms. Three key
hyperparameters govern how learning occurs:
● Epoch
● Learning Rate
● Batch Size
These are not learned by the model—they must be defined before training and significantly affect
convergence, accuracy, and training time.
1. Epoch
An epoch refers to one complete pass through the entire training dataset.
Details:
● After each epoch, the model has seen and processed every sample in the dataset once.
● Models typically require multiple epochs (e.g., 50, 100, 200) to converge.
● Performance is monitored using training and validation loss after each epoch.
Example:
If you have 1,000 training images and you train for 10 epochs, your model will process 10,000
images in total.
Tip:
Use Early Stopping to stop training when validation performance stops improving.
The learning rate controls how much the model’s weights are updated during training.
Formula:
In gradient descent:
14
Effect:
Typical Values:
Example in Keras:
optimizer = [Link](learning_rate=0.001)
Adaptive Techniques:
3. Batch Size
The number of training samples processed before the model updates its weights.
Types:
● Batch Gradient Descent: Full dataset as one batch (slow, accurate gradients)
● Stochastic Gradient Descent (SGD): One sample per batch (fast, noisy updates)
● Mini-Batch Gradient Descent: Small subsets (e.g., 32, 64, 128 samples)
Trade-offs:
15
Batch Size Pros Cons
Small (e.g., 16) Fast updates, better generalization Noisy gradients, less stable
Large (e.g., 256) Stable convergence, efficient on GPU Higher memory usage, may overfit
Interrelationship
Parameter Influence on Training
Practical Guidelines
Scenario Suggested Setting
Model not learning (high loss) Increase epochs or decrease learning rate
These three parameters are essential in tuning the training behavior of a deep learning model.
Properly setting them can: [Link] up convergence [Link] model accuracy [Link]
overfitting or underfitting
Use grid search, random search, or hyperparameter tuning frameworks (like Optuna or Keras Tuner)
for optimization.
Deep neural networks (DNNs) are a subset of artificial neural networks (ANNs) that contain
multiple layers between the input and output. These layers allow the network to learn complex
patterns and improve accuracy in tasks such as image recognition, natural language processing,
and autonomous systems.
16
Structure of a Neural Network
Each neuron in a layer is connected to neurons in the next layer through weighted connections.
These weights are adjusted during training to optimize the network’s performance.
Traditional neural networks typically have one or two hidden layers, making them suitable for
simpler tasks. Deep neural networks, on the other hand, have multiple hidden layers, allowing
them to learn more intricate patterns and relationships in data.
1. Forward Propagation: Data moves through the network from the input layer to the
output layer.
2. Activation Functions: Each neuron applies an activation function (e.g., ReLU,
Sigmoid, or Tanh) to introduce non-linearity.
3. Backpropagation: The network adjusts weights using an optimization algorithm (e.g.,
gradient descent) to minimize errors.
4. Training: The network learns by iterating through data multiple times, refining its
weights to improve accuracy.
Deep neural networks have revolutionized artificial intelligence, making it possible to solve
complex problems with high accuracy.
17
Layers in a Feedforward Network
1. Input Layer: Receives raw data and passes it to the next layer.
2. Hidden Layers: Process and transform the data using weighted connections.
3. Output Layer: Produces the final result or prediction.
Each neuron in a layer is connected to neurons in the next layer through weighted connections.
These weights are adjusted during training to optimize the network’s performance.
Activation Functions
Activation functions introduce non-linearity into the network, enabling it to learn complex
patterns. Common activation functions include:
18
Forward Propagation
During forward propagation, data moves through the network from the input layer to the output
layer. Each neuron applies an activation function to determine its output.
Backpropagation & Optimization
Backpropagation is used to adjust the weights of the neurons to minimize the error
between the predicted output and the actual output. This process involves:
Weight Initialization
Proper weight initialization prevents issues like vanishing or exploding gradients. Common
methods include:
Regularization Methods
Regularization prevents overfitting and improves generalization:
19
Optimization Algorithms
Optimization algorithms adjust weights efficiently:
Gradient descent is an iterative optimization algorithm used to minimize a loss function, which
represents how far the model’s predictions are from the actual values. The main goal is to adjust
the parameters of a model (weights, biases, etc.) so that the error is minimized.
20
The update rule for the traditional gradient descent algorithm is:
θ=θ−η∇θJ(θ)
In traditional gradient descent, the gradients are computed based on the entire dataset,
which can be computationally expensive for large datasets.
For large datasets, computing the gradient using all data points can be slow and memory-
intensive. This is where SGD comes into play. Instead of using the full dataset to compute the
gradient at each step, SGD uses only one random data point (or a small batch of data points)
at each iteration. This makes the computation much faster. Path followed by batch gradient
descent vs. path followed by SGD:
In Stochastic Gradient Descent, the gradient is calculated for each training example (or a small
subset of training examples) rather than the entire dataset. The update rule becomes:
θ=θ−η∇θJ(θ;xi,yi)
Where:
21
• xi and yi represent the features and target of the i-th training example.
• The gradient ∇θJ(θ;xi,yi) is now calculated for a single data point or a small batch.
The key difference from traditional gradient descent is that, in SGD, the parameter updates are
made based on a single data point, not the entire dataset. The random selection of data points
introduces stochasticity, which can be both an advantage and a challenge.
● Adam Optimizer: Combines momentum and adaptive learning rates.
Batch Normalization
Batch normalization stabilizes training by normalizing activations across layers, improving
convergence speed.
Medical Diagnosis
Financial Forecasting
Deep feedforward networks form the backbone of many AI applications, enabling machines to
learn complex patterns and make accurate predictions.
Learning XOR with Neural Networks: A Detailed Explanation
The XOR (exclusive OR) problem is a classic challenge in machine learning and neural
networks. It highlights the limitations of simple perceptrons and demonstrates the need for
multi-layer neural networks.
22
Input A Input B XOR Output
0 0 0
0 1 1
1 0 1
1 1 0
A single-layer perceptron cannot solve XOR because the data is not linearly separable—
meaning no single straight line can separate the 0s and 1s.
Where:
● ( w ) represents weights,
● ( x ) represents inputs,
● ( b ) is the bias term,
● w⋅x: Dot product
● step(⋅) is the activation function.
Since XOR is not linearly separable, no single line (or hyperplane) can separate the outputs 0
and 1, making a single-layer perceptron inadequate for solving the XOR problem.
Linearly Separable Problems: A problem is linearly separable if there exists a straight line
(2D) or hyperplane (higher dimensions) that can separate the input classes perfectly.
For XOR:
23
Plotting these points shows that no straight line can separate the 0s from the 1s, meaning XOR
requires a non-linear decision boundary.
Limitation:
24
4. Training the Neural Network
To train the network:
0 0 0
0 1 1
1 0 1
1 1 0
A single-layer perceptron cannot solve XOR because the data is not linearly separable—
meaning no single straight line can separate the 0s and 1s.
A B XOR(A,B)
0 0 0
0 1 1
1 0 1
1 1 0
Plotting these points shows that no straight line can separate the 0s from the 1s, meaning XOR
requires a non-linear decision boundary.
Limitation:
Key Idea: Introduce one or more hidden layers with non-linear activation functions to
model non-linear boundaries.
A single-layer perceptron can only learn linearly separable patterns. Mathematically, the decision
boundary is represented by:
Where:
● ( w ) represents weights,
● ( x ) represents inputs,
● ( b ) is the bias term,
● Step() is the activation function.
Since XOR is not linearly separable, no single line (or hyperplane) can separate the outputs 0
and 1, making a single-layer perceptron inadequate for solving the XOR problem.
A neural network with a hidden layer can combine multiple decision boundaries.
Hidden Neuron H₁
Hidden Neuron H₂
H₁ = x₁ OR x₂
H₂ = x₁ AND x₂
Network Structure
x1 ──► H1 ──┐
x2 ──► H1 ──┘
x1 ──► H2 ──┐
├──► Output
x2 ──► H2 ──┘
27
7. Gradient-Based Learning & Hidden Units in Neural Networks: A Detailed Explanation
Gradient-based learning is a fundamental approach in training neural networks, where the model
adjusts its parameters using optimization techniques like gradient descent. Hidden units play a
crucial role in this process by transforming input data through multiple layers, enabling deep
learning models to capture complex patterns.
Gradient-based learning is essential for training deep neural networks, as it allows models to
learn from data and improve their predictions over time.
28
If x≤0, the neuron outputs 0.
The issue is that for negative inputs, the gradient is zero. If a neuron's weights cause it
to always receive negative inputs, it may output 0 forever and stop learning.
f(x)=max(α,x)
Regularization Methods
Regularization prevents overfitting:
Batch Normalization
Batch normalization stabilizes training by normalizing activations across layers, improving
convergence speed.
29
Computer Vision
Medical Diagnosis
Financial Forecasting
Gradient-based learning and hidden units form the backbone of deep learning models, enabling
machines to learn complex patterns and make accurate predictions.
An activation function determines the output of a neuron given an input or set of inputs. It
introduces non-linearity into the network, allowing the model to learn complex patterns.
Without activation functions, a neural network would behave like a linear regression model
regardless of how many layers it has.
30
Properties:
Disadvantages:
● Vanishing Gradient Problem: Gradients become very small for extreme values of xxx,
slowing down learning.
● Outputs are not zero-centered → affects convergence speed.
31
2. Tanh (Hyperbolic Tangent) Function
Properties:
Disadvantages:
32
●
Symmetry: The tanh function is symmetric around the origin (0), unlike other activation
functions like the sigmoid which has a range between 0 and 1.
Why Use Tanh in Neural Networks?
The tanh function has several advantages that make it widely used in neural networks:
1. Non-linearity: Tanh introduces non-linearity to the model, which allows neural
networks to learn complex patterns and relationships in the data. Without non-linear
activation functions, a neural network would essentially behave as a linear model, no
matter how many layers it has.
2. Centered Around Zero: The output of the tanh function is centered around 0, unlike
the sigmoid function, which outputs values between 0 and 1. This makes the tanh activation
33
function more useful for many types of tasks, as the mean of the output is closer to zero,
leading to more efficient training and faster convergence.
3. Gradient Behavior: Tanh helps mitigate the vanishing gradient problem (to some
extent), especially when compared to sigmoid activation. This is because the gradient of
the tanh function is generally higher than that of the sigmoid, enabling better weight
updates during backpropagation.
Advantages of Using Tanh
1. Symmetry Around Zero: Since the output is centered around zero, the network has a
better chance of balancing the weights. This helps in ensuring that the gradients don't just
keep increasing or decreasing in magnitude, making training faster and more stable.
2. Improved Convergence: The tanh function is differentiable, making it a good
candidate for training deep networks using gradient-based optimization algorithms like
stochastic gradient descent (SGD).
3. Gradient Descent Efficiency: Unlike the sigmoid, which is constrained between 0 and
1, the tanh function’s output between -1 and 1 helps in better weight updates during
training, leading to improved convergence speed.
Disadvantages of Tanh
1. Vanishing Gradient Problem: Similar to the sigmoid function, tanh suffers from the
vanishing gradient problem for large values of the input (both positive and negative). When
the input to the tanh function is very large or very small, the gradient approaches zero,
which can slow down or halt learning during backpropagation, especially in deep networks.
2. Not Suitable for All Tasks: While tanh works well in many cases, it might not be the
best option for all types of neural network architectures. For instance, ReLU (Rectified
Linear Unit) has gained popularity for deep networks due to its simplicity and efficiency
in mitigating the vanishing gradient problem.
3. Sensitive to Outliers: Extreme values in the input can lead to saturated regions where
the gradient is close to zero, making learning slow or ineffective. This could happen if the
inputs to the tanh function are not scaled properly.
When to Use Tanh?
The tanh function is useful when:
· You are building shallow neural networks (i.e., networks with fewer layers).
· You are working with data where negative values are significant and should be retained.
However, for deeper networks, alternatives like ReLU or Leaky ReLU may be better
due to their ability to avoid the vanishing gradient problem more effectively.
· Value Range: Outputs values from -1 to +1.
34
Use in Hidden Layers: Commonly used in hidden layers due to its zero-cantered output,
facilitating easier learning for subsequent layers.
Properties:
Disadvantages:
● Dying ReLU Problem: Neurons can "die" (always output 0) during training if they get stuck
in the negative input region.
Rectified Linear Unit (ReLU) is a popular activation functions used in neural networks, especially
in deep learning models. It has become the default choice in many architectures due to its
simplicity and efficiency. The ReLU function is a piecewise linear function that outputs the input
directly if it is positive; otherwise, it outputs zero.
In simpler terms, ReLU allows positive values to pass through unchanged while setting all negative
values to zero. This helps the neural network maintain the necessary complexity to learn patterns
while avoiding some of the pitfalls associated with other activation functions, like the vanishing
gradient problem.
The ReLU function can be described mathematically as follows: f(x)=max(0,x)f(x)=max(0,x)
Where:
35
x is the input to the neuron.
The function returns x if x is greater than 0.
If x is less than or equal to 0, the function returns 0. The formula can also be written as:
This simplicity is what makes ReLU so effective in training deep neural networks, as it helps to
maintain non-linearity without complicated transformations, allowing models to learn more
efficiently.
If we plot the graph of ReLU activation function, it will appear like this:
4. Leaky ReLU
36
Properties:
● Avoids "dying ReLU" by allowing a small gradient when x<0x < 0x<0.
● Improves gradient flow in the network.
Disadvantages:
● The value of α\alphaα must be set manually (unless using Parametric ReLU).
5. Softmax Function
37
● The Softmax function ensures that each class is assigned a probability, helping to
identify which class the input belongs to.
38
Properties:
Disadvantages:
Summary Table
Function Range Centered Common Use Case Key Limitation
39
Function Range Centered Common Use Case Key Limitation
Visualization
Function Shape
40