Docsity

deep learning methods, Schemes and Mind Maps of Computer Science

Toggle sidebar
bg1
CSE 5111: Deep Learning
Lecture 4: Building Our First Deep Neural Network [Class 9,10]
Master of Science in Computer Science & Engineering
Department of Computer Science and Engineering
Comilla University
Instructor: Mahmudul Hasan, PhD
Reference Text: Deep Learning (GBC) - Chapter 6.1, 6.3
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b

Partial preview of the text

Download deep learning methods and more Schemes and Mind Maps Computer Science in PDF only on Docsity!

CSE 5111: Deep Learning

Lecture 4: Building Our First Deep Neural Network [Class 9,10]

Master of Science in Computer Science & Engineering

Department of Computer Science and Engineering

Comilla University

Instructor: Mahmudul Hasan, PhD

Reference Text: Deep Learning (GBC) - Chapter 6.1, 6.

Slide 2: Recap: The Complete Puzzle So Far

What We've Learned

We now have all the mathematical pieces:

1. Gradient Descent: The optimization

algorithm that minimizes loss.

2. Backpropagation: The efficient

algorithm for calculating gradients.

3. PyTorch Autograd: Automates

backpropagation for us.

Today's Mission: Assemble these pieces to build our first Deep Neural Network

(DNN) and understand why depth is powerful.

Slide 4: The Solution: Adding Layers & Non-Linearity

Building Complexity Step by Step

Think of it like this:

• Layer 1: Creates simple decision boundaries (straight

lines)

• Layer 2: Combines these lines to create more complex

shapes

• Layer 3: Combines those shapes to create even more complex regions

Analogy: Building with LEGO

• Single layer = Basic bricks

• Multiple layers = Complex structures from simple bricks

• Activation functions = The connectors that hold everything together

Slide 5: Activation Functions: The "Spark" of Neural Networks

What Are Activation Functions?

Activation functions determine whether a neuron

should "fire" or not. They introduce non-linearity!

Without activation functions:

• Deep network = Just multiple linear

transformations

• Multiple layers = Equivalent to a single layer

With activation functions:

• Deep network = Can learn complex, non-linear

relationships

Slide 7: Why ReLU is the Default Choice

The ReLU Revolution

Advantages:

• Computationally simple: Just max(0, x)

• Avoids vanishing gradient: Gradient is either 0 or 1

• Sparsity: About 50% of neurons can be inactive

Disadvantage:

• Dying ReLU: If inputs are always negative, neuron never

activates

Solution variants:

• Leaky ReLU: max(0.01x, x) - small slope for negative values

• Parametric ReLU (PReLU): Learn the slope

Slide 8: Architecture of a Deep Neural Network

Anatomy of a DNN

Input Layer → Hidden Layer 1 → Hidden Layer 2 → ... → Output Layer

Raw Data Simple More Complex Final Prediction

Features Features

Key Components:

• Input Layer: Size = number of features

• Hidden Layers: Where the magic happens

• Output Layer: Size = number of classes (classification) or 1 (regression)

• Connections: Fully connected = each neuron connects to all neurons in next layer

Slide 10: Building a DNN in PyTorch: Step 1 - Imports

Setting Up Our Toolkit

python

import torch

import torch.nn as nn

import torch.optim as optim

import torchvision

import torchvision.transforms as transforms

import matplotlib.pyplot as plt

# Check if GPU is available

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

print(f"Using device: {device}")

Key Imports:

• torch.nn: Neural network modules

• torch.optim: Optimization algorithms

• torchvision: Computer vision datasets

Slide 11: Building a DNN in PyTorch: Step 2 - Define the Model

Creating Our Neural Network Class

class FashionDNN(nn.Module): def init(self): super(FashionDNN, self).init() self.network = nn.Sequential( # Input: 784 features (28x28 pixels) nn.Linear( 784 , 128 ), # First hidden layer nn.ReLU(), # Activation function nn.Linear( 128 , 64 ), # Second hidden layer nn.ReLU(), # Activation function nn.Linear( 64 , 10 ) # Output: 10 classes ) def forward(self, x): # Flatten the image from 28x28 to 784 x = x.view(x.size( 0 ), - 1 ) return self.network(x) # Create model and move to GPU model = FashionDNN().to(device) print(model)

Slide 13: Building a DNN: Step 3 - Prepare the Data

Getting Our Data Ready

python # Transform: convert images to tensors and normalize transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) # Download and load training data trainset = torchvision.datasets.FashionMNIST( root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader( trainset, batch_size= 64 , shuffle=True) # Download and load test data testset = torchvision.datasets.FashionMNIST( root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader( testset, batch_size= 64 , shuffle=False)

Why batch_size=64?

• Training with mini-batches is more efficient

• Provides more stable gradient estimates

• Common sizes: 32, 64, 128, 256

Why Batch Sizes Are Often Powers of 2 in Deep Learning

In machine learning, particularly deep learning, the batch size refers to the number of training

samples processed together in one iteration before updating the model's parameters.

• GPU Parallelism : Aligns with GPU core counts (e.g., 32) for efficient processing.

• Memory Alignment : Matches memory page sizes to reduce padding and waste.

• Matrix Optimization : Speeds up cuDNN matrix operations for multiples of 8.

Why Adam?

a) Adaptive Learning Rates : Adam adjusts learning rates for each parameter using estimates

of first and second moments, leading to faster convergence.

b) Efficiency with Large Datasets : It performs well with large-scale data and parameters,

requiring less memory than other optimizers.

c) Robust to Noisy Gradients : Adam handles noisy or sparse gradients effectively, making it

suitable for complex, non-convex problems.

d) Combines Momentum and RMSProp : By integrating momentum and RMSProp, Adam

balances speed and stability in optimization.

Slide 15: The Complete Training Loop

Putting It All Together: Training

python def train_model(model, trainloader, criterion, optimizer, epochs= 10 ): model.train() # Set model to training mode train_losses = [] for epoch in range(epochs): running_loss = 0. for images, labels in trainloader: # Move data to GPU images, labels = images.to(device), labels.to(device) # Zero the gradients optimizer.zero_grad() # Forward pass outputs = model(images) loss = criterion(outputs, labels) # Backward pass and optimize

Slide 16: Understanding Model Training vs Evaluation Modes

model.train() vs model.eval()

Training Mode ( model.train() ):

• Enables dropout and batch normalization

• Tracks gradients for backpropagation

• Used during training

Evaluation Mode ( model.eval() ):

• Disables dropout and uses full network

• Uses running statistics for batch norm

• No gradient tracking (saves memory)

• Used during testing/validation

python

# For testing: model.eval() with torch.no_grad(): # No gradients needed for testing test_outputs = model(test_images) # Back to training: model.train()

Slide 17: Evaluating Our Model

How Good is Our Model?

python def evaluate_model(model, testloader): model.eval() correct = 0 total = 0 with torch.no_grad(): # No gradients needed = faster! for images, labels in testloader: images, labels = images.to(device), labels.to(device) outputs = model(images) _, predicted = torch.max(outputs.data, 1 ) total += labels.size( 0 ) correct += (predicted == labels).sum().item() accuracy = 100 * correct / total print(f'Test Accuracy: {accuracy:.2f}%') return accuracy # Test our trained model accuracy = evaluate_model(model, testloader)