Data Handling in Deep Learning
Data Handling in Deep Learning
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.
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 Collection
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.
🔄
Normalization in Image Data:
# PyTorch example:
transform = [Link](mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
Benefits of Normalization:
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.
1. Role of Deep Learning Libraries in Data Processing
Modern libraries simplify and speed up the data pipeline with modules for:
Popular frameworks:
PyTorch
TensorFlow
Keras
Libraries/Tools Used:
Common Steps:
# Load dataset
dataset = [Link](root='./data', train=True, download=True, transform=transform)
# Create DataLoader
loader = DataLoader(dataset, batch_size=64, shuffle=True)
B. Data Processing in TensorFlow
Libraries/Tools Used:
Example Pipeline:
import tensorflow as tf
# Load dataset
(train_images, train_labels), _ = [Link].load_data()
# Create Dataset
train_dataset = [Link].from_tensor_slices((train_images, train_labels))
train_dataset = train_dataset.shuffle(10000).batch(32).prefetch([Link])
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:
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.
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
D. Kernel-based Filtering
Randomly masks out parts of the image (patches) to force the model to focus on multiple
features.
Technique Description
Mixup Creates new training samples by linearly combining pairs of images and their labels.
Technique Description
Cuts and pastes patches from one image onto another, mixing their labels
CutMix
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:
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
Augmentation Type Common Libraries Effect
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:
Dynamic Computation Graphs: Flexibility during runtime
TorchScript: Convert models for production
Autograd: Automatic differentiation engine
Strong GPU acceleration
Native support for CUDA
Key Modules:
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:
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:
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
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:
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:
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.
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.
Deep feedforward networks, also known as multilayer perceptrons (MLPs), are a fundamental
type of artificial neural network where information moves in one direction—from input to output
—without loops or feedback. These networks are widely used in machine learning and artificial
intelligence for tasks such as image recognition, speech processing, and financial forecasting.
1. Architecture of Deep Feedforward Networks
A deep feedforward network consists of multiple layers of neurons that process data sequentially.
The architecture includes:
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:
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 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:
Optimization Algorithms
Batch Normalization
Computer Vision
Medical Diagnosis
Financial Forecasting
Deep feedforward networks form the backbone of many AI applications, enabling machines to
learn complex patterns and make accurate predictions.
The XOR operation takes two binary inputs and returns 1 if the inputs are different, otherwise 0.
The truth table for XOR is:
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 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,
( \text{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.
To solve XOR, we use a multi-layer perceptron (MLP) with at least one hidden layer. The
architecture consists of:
Each neuron in the hidden layer applies a weighted sum and an activation function:
Where:
( w ) represents weights,
( b ) represents biases,
( \sigma ) is the activation function.
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.
The XOR operation takes two binary inputs and returns 1 if the inputs are different, otherwise 0.
The truth table for XOR is:
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.
: input vector
: weight vector
: bias
step(): threshold function (e.g., outputs 0 or 1)
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.
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.
To solve XOR, we use a multi-layer perceptron (MLP) with at least one hidden layer. The
architecture consists of:
Mathematical Representation
4. Training the Neural Network
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.
Hidden units are neurons in the hidden layers of a neural network. They apply activation
functions to introduce non-linearity, allowing the network to learn complex relationships.
Weight Initialization
Regularization Methods
Batch Normalization
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.
Disadvantages:
Vanishing Gradient Problem: Gradients become very small for extreme values of xxx,
slowing down learning.
Outputs are not zero-centered → affects convergence speed.
Properties:
Disadvantages:
Still suffers from vanishing gradients.
Computationally expensive due to exponential operations.
Properties:
Disadvantages:
Dying ReLU Problem: Neurons can "die" (always output 0) during training if they get
stuck in the negative input region.
4. Leaky ReLU
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
✅
Properties:
Disadvantages:
Summary Table
Function Range Centered Common Use Case Key Limitation