Lecture 1 / 30
Topic 01 - Unit I - Neural Network Foundations

What is Deep Learning?

Syllabus Topic Template
Definition

Deep Learning (DL) is a specialized subset of Machine Learning based on artificial neural networks. The "deep" in deep learning refers to the use of multiple layers in the network. These algorithms attempt to simulate the behavior of the human brain to "learn" from large amounts of data.

Machine Learning vs. Deep Learning

While both are branches of AI, their approach to data processing differs significantly:

  • Machine Learning: Usually requires manual feature extraction. A human expert must tell the algorithm what data points (features) to look at to make a decision.
  • Deep Learning: Performs automatic feature extraction. You feed the raw data (like pixels of an image) directly into the network, and the hidden layers automatically learn which features are important.
💡 Why Now?

The math behind deep learning has existed since the 1980s. It only became a dominant force recently due to two factors: the explosion of Big Data (to train the models) and the advancement of GPUs (to perform the massive matrix calculations quickly).

Real World Applications

Deep Learning drives the most cutting-edge technologies we use today:

  • Computer Vision: Facial recognition, medical image analysis (detecting tumors), and object detection.
  • Natural Language Processing (NLP): ChatGPT, language translation, and sentiment analysis.
  • Speech Recognition: Virtual assistants like Siri and Alexa.

A Quick Look at Keras/TensorFlow

Building a deep neural network is remarkably accessible with modern frameworks. Here is a conceptual peek at creating a simple multi-layer network:

intro_dl.py
# 1. Import TensorFlow/Keras
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# 2. Initialize a Sequential model (a linear stack of layers)
model = Sequential()

# 3. Add 'Deep' Layers to the network
model.add(Dense(128, activation='relu', input_shape=(784,))) # Hidden Layer 1
model.add(Dense(64, activation='relu'))                      # Hidden Layer 2
model.add(Dense(10, activation='softmax'))                   # Output Layer

# 4. Compile the model ready for training
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Practice Task

Research the difference between TensorFlow and PyTorch. What are the pros and cons of each framework, and which one is generally preferred in academia versus industry?

Topic 02 - Unit I - Neural Network Foundations

Artificial Neural Networks (ANNs)

Syllabus Topic
ANN Architecture
Structure of an ANN

An Artificial Neural Network consists of an Input Layer, multiple Hidden Layers, and an Output Layer of interconnected artificial neurons (perceptrons).

PyTorch Multi-Layer Perceptron (MLP)

ann_pytorch.py
import torch
import torch.nn as nn

class ANN(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(ANN, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_dim, output_dim)
        
    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

model = ANN(input_dim=784, hidden_dim=128, output_dim=10)
print(model)
Topic 03 - Unit I - Neural Network Foundations

The Perceptron

Syllabus Topic
Linear Discriminant
Single Neuron Model

The Perceptron computes a weighted sum of inputs plus a bias ($z = \sum w_i x_i + b$) passed through a step activation function.

Perceptron Equation

$y = f(w_1 x_1 + w_2 x_2 + ... + b)$

Topic 04 - Unit I - Neural Network Foundations

Activation Functions

Syllabus Topic
Non-Linearities
Enabling Non-Linear Representations

Activation functions introduce non-linear transformations, allowing neural networks to approximate arbitrary complex functions.

Common Activation Functions

  • ReLU (Rectified Linear Unit): $f(x) = \max(0, x)$ — prevents vanishing gradients in deep networks.
  • Sigmoid: $f(x) = \frac{1}{1 + e^{-x}}$ — maps outputs to probabilities (0 to 1).
  • Softmax: Converts a vector of raw logits into a normalized probability distribution across multiple classes.
Topic 05 - Unit I - Neural Network Foundations

Forward Propagation

Syllabus Topic
Tensor Multiplication
Information Flow

Forward propagation computes layer-by-layer matrix multiplications and non-linear activation passes from inputs to final predictions.

Forward Pass Code

forward_pass.py
import torch

X = torch.randn(32, 784) # Batch of 32 images
W1 = torch.randn(784, 128)
b1 = torch.zeros(128)

Z1 = torch.matmul(X, W1) + b1
A1 = torch.relu(Z1)
print("Forward Pass Tensor Shape:", A1.shape)
Topic 06 - Unit II - Training Deep Networks

Loss Functions

Syllabus Topic
Loss Computation
Quantifying Prediction Error

Loss functions measure the discrepancy between model predictions $\hat{y}$ and true ground-truth targets $y$.

Loss Functions Code

loss_fn.py
import torch.nn as nn

criterion_clf = nn.CrossEntropyLoss() # Classification
criterion_reg = nn.MSELoss()          # Regression
Topic 07 - Unit II - Training Deep Networks

Gradient Descent & Backpropagation

Syllabus Topic
Chain Rule & Autograd
Updating Model Weights

Backpropagation calculates partial derivatives of the Loss function with respect to every weight using the Calculus Chain Rule.

PyTorch Autograd Backprop

backprop.py
import torch

x = torch.tensor(2.0, requires_grad=True)
y = x**2 + 3*x + 1
y.backward() // Computes dy/dx = 2x + 3
print("Gradient at x=2.0:", x.grad.item()) // 7.0
Topic 08 - Unit II - Training Deep Networks

Optimizers (Adam, RMSprop)

Syllabus Topic
Optimization Algorithms
Weight Update Rules

Optimizers update network weights using computed gradients. Adam (Adaptive Moment Estimation) combines momentum and adaptive learning rates.

Optimizer Configuration Code

optimizer.py
import torch.optim as optim

optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-4)
optimizer.zero_grad()
loss.backward()
optimizer.step()
Topic 09 - Unit II - Training Deep Networks

Handling Overfitting (Dropout)

Syllabus Topic
Regularization
Preventing Overfitting

Dropout randomly deactivates a fraction $p$ of neurons during training, forcing the network to learn redundant robust features.

Dropout Layer Code

dropout.py
import torch.nn as nn
layer = nn.Sequential(
    nn.Linear(128, 64),
    nn.Dropout(p=0.5), # 50% dropout probability
    nn.ReLU()
)
Topic 10 - Unit II - Training Deep Networks

Batch Normalization

Syllabus Topic
Internal Covariate Shift
Standardizing Layer Activations

Batch Normalization normalizes activations across mini-batches, stabilizing training and enabling higher learning rates.

BatchNorm Code

batch_norm.py
import torch.nn as nn
layer = nn.Sequential(
    nn.Linear(128, 64),
    nn.BatchNorm1d(64),
    nn.ReLU()
)
Topic 11 - Unit III - Computer Vision (CNNs)

Introduction to CNNs

Syllabus Topic
Computer Vision
Grid-Structured Spatial Data

CNNs use spatial weight sharing to preserve spatial grid hierarchies in image and video processing.

PyTorch Conv2d Layer

cnn_intro.py
import torch.nn as nn
conv = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1)
Topic 12 - Unit III - Computer Vision (CNNs)

Convolution Operations

Syllabus Topic
Feature Maps
Convolution Filters

Kernels slide across input channels to detect edges, textures, and higher-level visual patterns.

Convolution Code

conv_ops.py
import torch
input_img = torch.randn(1, 3, 64, 64)
output_map = conv(input_img)
print("Output Feature Map Shape:", output_map.shape)
Topic 13 - Unit III - Computer Vision (CNNs)

Pooling Layers

Syllabus Topic
Downsampling
Spatial Dimension Reduction

Pooling downsamples spatial dimensions, reducing computational parameter load and providing translation invariance.

MaxPool2d Code

pooling.py
import torch.nn as nn
pool = nn.MaxPool2d(kernel_size=2, stride=2)
Topic 14 - Unit III - Computer Vision (CNNs)

Famous CNN Architectures (ResNet)

Syllabus Topic
Deep Architectures
Residual Skip Connections

ResNet introduced Skip Connections ($y = F(x) + x$) to train ultra-deep networks (152+ layers) without gradient degradation.

Residual Block Architecture

$y = \mathcal{F}(x, \{W_i\}) + x$

Topic 15 - Unit III - Computer Vision (CNNs)

Transfer Learning

Syllabus Topic
Pre-Trained Models
Reusing Feature Extractor Weights

Transfer learning leverages models pre-trained on ImageNet to achieve high accuracy on specialized custom datasets with minimal training data.

PyTorch Transfer Learning Code

transfer_learning.py
import torchvision.models as models
import torch.nn as nn

resnet = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
# Freeze convolutional backbone
for param in resnet.parameters():
    param.requires_grad = False

# Replace classification head
resnet.fc = nn.Linear(resnet.fc.in_features, 2) # 2 custom classes
Topic 16 - Unit IV - Sequence Models (RNNs)

Sequence Data & RNNs

Syllabus Topic
Sequence Modeling
Temporal Memory

RNNs process sequential time-series and natural language inputs by passing hidden state memory $h_t$ across time steps.

PyTorch RNN Layer

rnn.py
import torch.nn as nn
rnn = nn.RNN(input_size=10, hidden_size=20, num_layers=2, batch_first=True)
Topic 17 - Unit IV - Sequence Models (RNNs)

The Vanishing Gradient Problem

Syllabus Topic
Gradient Instability
Long Sequences Challenge

Repeated matrix multiplications over long time steps cause gradients to decay exponentially to 0 or explode to infinity.

Gradient Clipping Remedy

clip_grad.py
import torch.nn.utils as utils
utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
Topic 18 - Unit IV - Sequence Models (RNNs)

Long Short-Term Memory (LSTM)

Syllabus Topic
Gated Memory Cells
Forget, Input & Output Gates

LSTMs solve vanishing gradients using a persistent Cell State $C_t$ governed by Forget, Input, and Output gates.

PyTorch LSTM Code

lstm.py
import torch.nn as nn
lstm = nn.LSTM(input_size=64, hidden_size=128, batch_first=True)
Topic 19 - Unit IV - Sequence Models (RNNs)

Gated Recurrent Units (GRUs)

Syllabus Topic
GRU Architecture
Streamlined Sequential Memory

GRUs simplify LSTM architecture by combining cell state and hidden state into a single state managed by Update and Reset gates.

PyTorch GRU Code

gru.py
import torch.nn as nn
gru = nn.GRU(input_size=64, hidden_size=128, batch_first=True)
Topic 20 - Unit IV - Sequence Models (RNNs)

Sequence-to-Sequence Models

Syllabus Topic
Encoder-Decoder
Seq2Seq Architecture

Seq2Seq uses an Encoder to condense source sequences into context vectors and a Decoder to generate target outputs (used in Machine Translation).

Encoder-Decoder Overview

Encodes variable-length input sequences $X_1..X_N$ into context vector $C$, decoding into target $Y_1..Y_M$.

Topic 21 - Unit V - Advanced DL & Transformers

Attention Mechanisms

Syllabus Topic
Attention Mechanism
Dynamic Context Weights

Attention allows models to dynamically focus on relevant parts of input sequences regardless of distance.

Attention Equation

$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$

Topic 22 - Unit V - Advanced DL & Transformers

The Transformer Architecture

Syllabus Topic
Transformers & Self-Attention
Parallel Sequence Processing

Transformers replace recurrent loops completely with Multi-Head Self-Attention and Positional Encodings, enabling massive parallel pre-training (GPT, BERT, LLMs).

PyTorch TransformerEncoder

transformer.py
import torch.nn as nn
encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)
transformer = nn.TransformerEncoder(encoder_layer, num_layers=6)
Topic 23 - Unit V - Advanced DL & Transformers

Autoencoders

Syllabus Topic
Unsupervised Representation
Dimension Bottleneck

Autoencoders compress inputs into a low-dimensional bottleneck code $Z$ before reconstructing the original input $\hat{X}$.

Autoencoder Reconstruction

autoencoder.py
import torch.nn as nn
class Autoencoder(nn.Module):
    def __init__(self):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(784, 32), nn.ReLU())
        self.decoder = nn.Sequential(nn.Linear(32, 784), nn.Sigmoid())
Topic 24 - Unit V - Advanced DL & Transformers

Variational Autoencoders (VAEs)

Syllabus Topic
Generative Latent Space
Probabilistic Latent Sampling

VAEs enforce a continuous Gaussian latent distribution $(\mu, \sigma)$ allowing smooth generative sampling of new images/data.

Reparameterization Trick

$z = \mu + \sigma \odot \epsilon, \quad \epsilon \sim \mathcal{N}(0, I)$

Topic 25 - Unit V - Advanced DL & Transformers

Generative Adversarial Networks (GANs)

Syllabus Topic
Generator vs Discriminator
Adversarial Training Game

GANs pit a Generator $G$ (creating fake data) against a Discriminator $D$ (spotting real vs fake) in a minimax game.

Minimax Objective Equation

$\min_G \max_D V(D, G) = \mathbb{E}_{x}[\log D(x)] + \mathbb{E}_{z}[\log(1 - D(G(z)))]$

Topic 26 - Unit VI - Frameworks & Deployment

Deep Q-Networks (RL Basics)

Syllabus Topic
Deep RL
Q-Learning with Neural Nets

DQNs approximate optimal action-value functions $Q(s, a)$ using deep neural networks to play games and control autonomous agents.

DQN Bellman Loss Code

dqn.py
import torch
target_q = reward + gamma * torch.max(next_q_values)
Topic 27 - Unit VI - Frameworks & Deployment

Introduction to PyTorch

Syllabus Topic
Tensors & Autograd
Dynamic Computational Graphs

PyTorch features dynamic computational graphs (eager execution), GPU acceleration via CUDA, and Pythonic debugging.

PyTorch Basics Code

pytorch_intro.py
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tensor = torch.randn(3, 3).to(device)
print("Device Tensor:
", tensor)
Topic 28 - Unit VI - Frameworks & Deployment

Introduction to TensorFlow & Keras

Syllabus Topic
tf.keras Sequential API
High-Level Deep Learning API

TensorFlow 2.x and Keras provide production-grade model building APIs with instant export to mobile (TF Lite) and web (TF.js).

Keras Model Code

keras_intro.py
import tensorflow as tf
model = tf.keras.Sequential([
    tf.keras.layers.Dense(64, activation='relu', input_shape=(784,)),
    tf.keras.layers.Dense(10, activation='softmax')
])
Topic 29 - Unit VI - Frameworks & Deployment

Model Deployment Strategies

Syllabus Topic
Model Serving
Production Inference Pipelines

Convert trained deep learning models into optimized ONNX or TorchScript binaries and serve inference via REST APIs (FastAPI).

TorchScript Export Code

export_model.py
import torch
traced_script_module = torch.jit.trace(model, example_input)
traced_script_module.save("model_traced.pt")
Topic 30 - Unit VI - Frameworks & Deployment

Ethics in Deep Learning

Syllabus Topic
AI Ethics & Safety
Responsible AI

Addresses algorithmic bias, data privacy, model explainability (SHAP/LIME), and safety guardrails in AI deployment.

Responsible AI Practices

  • Auditing training datasets for demographic representation bias.
  • Explaining model predictions using SHAP (SHapley Additive exPlanations).
  • Ensuring differential privacy and user data protection.
Topic 32 - Real-World Practical Projects

Project 1: Image Classification with Neural Networks (CNN)

Hands-on Project PyTorch / TensorFlow
🎯 Project Goal

Build a Convolutional Neural Network (CNN) to classify image datasets into categorical classes using PyTorch or TensorFlow/Keras.

Project Overview

Master Conv2D layers, MaxPool2D, Softmax activations, CrossEntropy loss optimization, and accuracy metrics.

Full Code Implementation

cnn_classifier.py
import tensorflow as tf
from tensorflow.keras import layers, models

def build_cnn_model(input_shape=(32, 32, 3), num_classes=10):
    model = models.Sequential([
        layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
        layers.MaxPooling2D((2, 2)),
        layers.Conv2D(64, (3, 3), activation='relu'),
        layers.Flatten(),
        layers.Dense(64, activation='relu'),
        layers.Dense(num_classes, activation='softmax')
    ])
    return model

model = build_cnn_model()
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
Practice Challenge

Add Data Augmentation layers (RandomFlip, RandomRotation) to prevent overfitting on small datasets!