Artificial Neural Networks, CNN, RNN, TensorFlow और PyTorch – Detailed notes in English and हिंदी
import tensorflow as tf
from tensorflow.keras import layers, models
model = models.Sequential([
layers.Flatten(input_shape=(28, 28)), # input: 784 pixels
layers.Dense(128, activation='relu'), # hidden layer 1
layers.Dense(64, activation='relu'), # hidden layer 2
layers.Dense(10, activation='softmax') # output: 10 classes
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# model.fit(x_train, y_train, epochs=5)
| Type | Idea | Typical Use |
|---|---|---|
| Feedforward (MLP/DNN) | Data flows forward through dense layers | Tabular data, small images |
| CNN | Local filters + weight sharing | Images, video, signals |
| RNN / LSTM / GRU | Sequential memory | Text, time series, speech |
| Transformer | Self-attention over sequences | NLP, vision, multimodal |
| Autoencoder | Bottleneck compression + reconstruction | Dim reduction, anomaly detection |
| GAN | Generator vs discriminator | Image synthesis, super-res |
| Reinforcement NN | Learn policies from reward | Games, robotics |
INPUT HIDDEN 1 HIDDEN 2 OUTPUT
x1 ─────▶ h1 ──┐ ┌── h1' ──┐
x2 ─────▶ h2 ──┼──▶ h2' ──┼──▶ y1
x3 ─────▶ h3 ──┼──▶ h3' ──┼──▶ y2
│ │
Bias Bias
Every line = a weight. Each hidden neuron:
z = Σ (wᵢ · xᵢ) + b
a = activation(z)
import tensorflow as tf
from tensorflow.keras import layers, models
model = models.Sequential([
layers.Flatten(input_shape=(28, 28)), # input: 784 pixels
layers.Dense(128, activation='relu'), # hidden layer 1
layers.Dense(64, activation='relu'), # hidden layer 2
layers.Dense(10, activation='softmax') # output: 10 classes
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# model.fit(x_train, y_train, epochs=5)
| Type | Idea | Typical Use |
|---|---|---|
| Feedforward (MLP/DNN) | Data dense layers से आगे बहता है | Tabular data, छोटी images |
| CNN | Local filters + weight sharing | Images, video, signals |
| RNN / LSTM / GRU | Sequential memory | Text, time series, speech |
| Transformer | Sequences पर self-attention | NLP, vision, multimodal |
| Autoencoder | Bottleneck compression + reconstruction | Dim reduction, anomaly detection |
| GAN | Generator vs discriminator | Image synthesis, super-res |
| Reinforcement NN | Reward से policies सीखें | Games, robotics |
INPUT HIDDEN 1 HIDDEN 2 OUTPUT
x1 ─────▶ h1 ──┐ ┌── h1' ──┐
x2 ─────▶ h2 ──┼──▶ h2' ──┼──▶ y1
x3 ─────▶ h3 ──┼──▶ h3' ──┼──▶ y2
│ │
Bias Bias
हर line = एक weight। हर hidden neuron:
z = Σ (wᵢ · xᵢ) + b
a = activation(z)
y = activation(Σ wᵢ·xᵢ + b). The activation function
introduces non-linearity, enabling networks to approximate any continuous function.
Common activations: sigmoid, tanh, ReLU, Leaky ReLU, ELU, GELU, Swish, softmax.
# Pure Python perceptron
import numpy as np
def perceptron(x, w, b):
z = np.dot(w, x) + b
return 1 if z >= 0 else 0
# PyTorch single neuron
import torch, torch.nn as nn
neuron = nn.Linear(in_features=3, out_features=1)
x = torch.tensor([[1.0, 2.0, 3.0]])
y = torch.relu(neuron(x))
print(y)
A. Common activation functions:
| Function | Formula | Range | Notes |
|---|---|---|---|
| Sigmoid | 1 / (1 + e⁻ᶻ) | (0, 1) | Vanishing gradient; good for binary output. |
| Tanh | (eᶻ − e⁻ᶻ) / (eᶻ + e⁻ᶻ) | (−1, 1) | Zero-centred; still saturates. |
| ReLU | max(0, z) | [0, ∞) | Default for hidden layers; fast; dying ReLU risk. |
| Leaky ReLU | max(αz, z), α ≈ 0.01 | (−∞, ∞) | Fixes dying ReLU. |
| ELU | z if z > 0 else α(eᶻ − 1) | (−α, ∞) | Smoother, negative values. |
| GELU | z · Φ(z) | (−0.17, ∞) | Used in Transformers (BERT, GPT). |
| Swish | z · sigmoid(βz) | (−0.28, ∞) | Smooth; used in EfficientNet. |
| Softmax | eᶻⁱ / Σ eᶻʲ | (0, 1), sums to 1 | Multi-class output. |
B. Perceptron types: Single-layer perceptron (linear), Multi-Layer Perceptron (MLP, non-linear), and variants with different activations. The "linear perceptron" without activation can only classify linearly separable data.
Sigmoid Tanh ReLU
─────── ──── ────
1 ┤─╮ 1 ┤ ╭─ ┤ /
│ ╰─ │ / │ /
0 ┤───╮ 0 ┤╯ │ /
│ ╰─ │ │ /
-1 ┤ -1 ┤ └───────
z z z
Dying ReLU problem:
ReLU(z) = max(0, z)
If z < 0 for all inputs → gradient = 0
Neuron "dies" and never recovers.
Fix: Leaky ReLU, ELU, GELU, Swish.
y = activation(Σ wᵢ·xᵢ + b) compute करता है। Activation
function non-linearity लाता है, जिससे networks कोई भी continuous function
approximate कर पाते हैं। Common activations: sigmoid, tanh, ReLU, Leaky ReLU, ELU, GELU,
Swish, softmax।
# Pure Python perceptron
import numpy as np
def perceptron(x, w, b):
z = np.dot(w, x) + b
return 1 if z >= 0 else 0
# PyTorch single neuron
import torch, torch.nn as nn
neuron = nn.Linear(in_features=3, out_features=1)
x = torch.tensor([[1.0, 2.0, 3.0]])
y = torch.relu(neuron(x))
print(y)
A. Common activation functions:
| Function | Formula | Range | Notes |
|---|---|---|---|
| Sigmoid | 1 / (1 + e⁻ᶻ) | (0, 1) | Vanishing gradient; binary output के लिए। |
| Tanh | (eᶻ − e⁻ᶻ) / (eᶻ + e⁻ᶻ) | (−1, 1) | Zero-centred; saturate। |
| ReLU | max(0, z) | [0, ∞) | Hidden layers का default; तेज़; dying ReLU। |
| Leaky ReLU | max(αz, z), α ≈ 0.01 | (−∞, ∞) | Dying ReLU fix। |
| ELU | z if z > 0 else α(eᶻ − 1) | (−α, ∞) | Smoother, negative values। |
| GELU | z · Φ(z) | (−0.17, ∞) | Transformers (BERT, GPT) में। |
| Swish | z · sigmoid(βz) | (−0.28, ∞) | Smooth; EfficientNet में। |
| Softmax | eᶻⁱ / Σ eᶻʲ | (0, 1), sum = 1 | Multi-class output। |
B. Perceptron types: Single-layer perceptron (linear), Multi-Layer Perceptron (MLP, non-linear), और अलग activations वाले variants। बिना activation वाला "linear perceptron" सिर्फ linearly separable data classify कर सकता है।
Sigmoid Tanh ReLU
─────── ──── ────
1 ┤─╮ 1 ┤ ╭─ ┤ /
│ ╰─ │ / │ /
0 ┤───╮ 0 ┤╯ │ /
│ ╰─ │ │ /
-1 ┤ -1 ┤ └───────
z z z
Dying ReLU problem:
ReLU(z) = max(0, z)
अगर सभी inputs के लिए z < 0 → gradient = 0
Neuron "मर" जाता है और recover नहीं करता।
Fix: Leaky ReLU, ELU, GELU, Swish।
# Forward pass z1 = X @ W1 + b1 a1 = relu(z1) z2 = a1 @ W2 + b2 y_hat = softmax(z2) # Loss loss = -mean( y_onehot * log(y_hat) ) # Backward pass (chain rule — PyTorch does this for you) loss.backward() # Update optimizer.step() optimizer.zero_grad()
A. Network types:
| Type | Description |
|---|---|
| Single-layer perceptron | Input → output, linear |
| Multi-Layer Perceptron (MLP) | Input → several hidden → output |
| Deep Neural Network (DNN) | Many hidden layers; used loosely |
| Fully-connected network | Every neuron connects to every neuron in next layer |
B. Backpropagation variants: Full-batch, stochastic (SGD), mini-batch, and variants with momentum, Nesterov, RMSProp, Adam, AdamW.
C. Loss functions: MSE (regression), Binary cross-entropy (binary classification), Categorical cross-entropy (multi-class), Focal loss (class imbalance).
Forward: X → [W1] → z1 → ReLU → [W2] → z2 → softmax → ŷ
│
▼
Loss
│
▼
Backward: ◀── ∂L/∂W2 ◀── ∂L/∂a1 ◀── ∂L/∂z1
(chain rule)
│
▼
W2 ← W2 − η·∂L/∂W2
W1 ← W1 − η·∂L/∂W1
Each training step:
1. Forward pass → predictions
2. Compute loss
3. Backward pass → gradients
4. Optimizer step (update weights)
5. zero_grad() → reset for next step
# Forward pass z1 = X @ W1 + b1 a1 = relu(z1) z2 = a1 @ W2 + b2 y_hat = softmax(z2) # Loss loss = -mean( y_onehot * log(y_hat) ) # Backward pass (chain rule — PyTorch कर देता है) loss.backward() # Update optimizer.step() optimizer.zero_grad()
A. Network types:
| Type | विवरण |
|---|---|
| Single-layer perceptron | Input → output, linear |
| Multi-Layer Perceptron (MLP) | Input → कई hidden → output |
| Deep Neural Network (DNN) | कई hidden layers; loosely used |
| Fully-connected network | हर neuron अगली layer के हर neuron से जुड़ा |
B. Backpropagation variants: Full-batch, stochastic (SGD), mini-batch, और momentum, Nesterov, RMSProp, Adam, AdamW वाले variants।
C. Loss functions: MSE (regression), Binary cross-entropy (binary classification), Categorical cross-entropy (multi-class), Focal loss (class imbalance)।
Forward: X → [W1] → z1 → ReLU → [W2] → z2 → softmax → ŷ
│
▼
Loss
│
▼
Backward: ◀── ∂L/∂W2 ◀── ∂L/∂a1 ◀── ∂L/∂z1
(chain rule)
│
▼
W2 ← W2 − η·∂L/∂W2
W1 ← W1 − η·∂L/∂W1
हर training step:
1. Forward pass → predictions
2. Loss compute
3. Backward pass → gradients
4. Optimizer step (weights update)
5. zero_grad() → next step के लिए reset
θ ← θ − η · ∇L(θ). The learning rate η controls
step size. Variants change how the gradient is estimated (batch size) and how updates are
computed (momentum, adaptive LR).
# PyTorch
import torch.optim as optim
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
# or: optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)
# or: optim.AdamW(model.parameters(), lr=1e-3)
for epoch in range(10):
optimizer.zero_grad()
out = model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
# Keras
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-3),
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Learning rate schedule
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50)
A. Gradient descent variants:
| Variant | Batch size | Notes |
|---|---|---|
| Batch GD | Full dataset | Stable, slow, high memory |
| Stochastic GD | 1 sample | Noisy, fast, escapes local minima |
| Mini-batch GD | 32–512 | Default in practice |
B. Optimizers:
| Optimizer | Idea |
|---|---|
| SGD | θ ← θ − η·∇L |
| Momentum | Accumulate velocity to smooth updates |
| Nesterov | Look-ahead momentum |
| AdaGrad | Per-parameter LR, good for sparse |
| RMSProp | Exponential average of squared grads |
| Adam | Momentum + RMSProp; most popular |
| AdamW | Adam with decoupled weight decay |
| LAMB | Layer-wise adaptive LR for very large batches |
C. LR schedules: Step decay, exponential, cosine annealing, warmup + cosine, one-cycle, ReduceLROnPlateau.
Loss surface (2D slice):
▲ Loss
│ ╭──╮ local min
│ ╱ ╲
│ ╱ ╲
│ ╱ ╲ saddle
│╱ ╲ ────────
│ ╲___╱
│ ╲ global min
└────────────────────────────────▶ θ
Learning rate effect:
Too high: ╱╲╱╲╱╲ bounces, diverges
Too low: ──────── slow crawl
Just right: ───────╲ smooth descent
Momentum:
v ← β·v − η·∇L
θ ← θ + v
Accumulates direction → faster, smoother
clip_grad_norm_.θ ← θ − η · ∇L(θ). Learning rate η step size तय करता है।
Variants बदलते हैं कि gradient कैसे estimate होता है (batch size) और updates कैसे compute
होती हैं (momentum, adaptive LR).
# PyTorch
import torch.optim as optim
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
# या: optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)
# या: optim.AdamW(model.parameters(), lr=1e-3)
for epoch in range(10):
optimizer.zero_grad()
out = model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
# Keras
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-3),
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Learning rate schedule
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50)
A. Gradient descent variants:
| Variant | Batch size | Notes |
|---|---|---|
| Batch GD | पूरा dataset | Stable, slow, high memory |
| Stochastic GD | 1 sample | Noisy, fast, local minima से escape |
| Mini-batch GD | 32–512 | Practice में default |
B. Optimizers:
| Optimizer | Idea |
|---|---|
| SGD | θ ← θ − η·∇L |
| Momentum | Velocity accumulate → smooth updates |
| Nesterov | Look-ahead momentum |
| AdaGrad | Per-parameter LR, sparse data के लिए |
| RMSProp | Squared grads का exponential average |
| Adam | Momentum + RMSProp; सबसे popular |
| AdamW | Adam + decoupled weight decay |
| LAMB | बहुत बड़े batches के लिए layer-wise LR |
C. LR schedules: Step decay, exponential, cosine annealing, warmup + cosine, one-cycle, ReduceLROnPlateau।
Loss surface (2D slice):
▲ Loss
│ ╭──╮ local min
│ ╱ ╲
│ ╱ ╲
│ ╱ ╲ saddle
│╱ ╲ ────────
│ ╲___╱
│ ╲ global min
└────────────────────────────────▶ θ
Learning rate effect:
बहुत high: ╱╲╱╲╱╲ bounce, diverge
बहुत low: ──────── slow crawl
बिल्कुल सही: ───────╲ smooth descent
Momentum:
v ← β·v − η·∇L
θ ← θ + v
Direction accumulate → faster, smoother
clip_grad_norm_ से gradient clipping दिखाइए।
# Keras
from tensorflow.keras import layers
model = tf.keras.Sequential([
layers.Dense(256),
layers.BatchNormalization(),
layers.Activation('relu'),
layers.Dropout(0.3),
layers.Dense(128, activation='relu'),
layers.Dropout(0.3),
layers.Dense(10, activation='softmax')
])
# PyTorch
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.bn1 = nn.BatchNorm1d(256)
self.drop = nn.Dropout(0.3)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
x = self.drop(F.relu(self.bn1(self.fc1(x))))
return self.fc2(x)
A. Regularization techniques:
| Technique | Idea |
|---|---|
| L2 (weight decay) | Penalise large weights (λ·Σw²) |
| L1 | Penalise |w|; encourages sparsity |
| Dropout | Randomly drop activations during training |
| Data augmentation | More diverse training data |
| Early stopping | Stop when val loss starts increasing |
| Label smoothing | Soften one-hot targets |
| Ensembling | Combine multiple models |
| Dropout variants | Spatial Dropout, DropBlock, Stochastic Depth |
B. Normalization layers: Batch Norm, Layer Norm, Group Norm, Instance Norm, RMS Norm.
C. Where to place:
Dropout (p = 0.5):
Train: Eval:
a1 ──✗ (dropped) a1' = a1 * (1 − p)
a2 ──✓ a2' = a2 * (1 − p)
a3 ──✗ a3' = a3 * (1 − p)
a4 ──✓
(each node dropped independently)
BatchNorm:
For each mini-batch:
μ = mean(x)
σ² = var(x)
x̂ = (x − μ) / √(σ² + ε)
y = γ·x̂ + β (γ, β learnable)
Training:
uses batch statistics
Inference:
uses running mean/var stored during training
# Keras
from tensorflow.keras import layers
model = tf.keras.Sequential([
layers.Dense(256),
layers.BatchNormalization(),
layers.Activation('relu'),
layers.Dropout(0.3),
layers.Dense(128, activation='relu'),
layers.Dropout(0.3),
layers.Dense(10, activation='softmax')
])
# PyTorch
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.bn1 = nn.BatchNorm1d(256)
self.drop = nn.Dropout(0.3)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
x = self.drop(F.relu(self.bn1(self.fc1(x))))
return self.fc2(x)
A. Regularization techniques:
| Technique | Idea |
|---|---|
| L2 (weight decay) | बड़े weights पर penalty (λ·Σw²) |
| L1 | |w| पर penalty; sparsity encourage |
| Dropout | Training में activations random drop |
| Data augmentation | ज़्यादा diverse training data |
| Early stopping | Val loss बढ़ने पर रोक दें |
| Label smoothing | One-hot targets soften |
| Ensembling | कई models combine |
| Dropout variants | Spatial Dropout, DropBlock, Stochastic Depth |
B. Normalization layers: Batch Norm, Layer Norm, Group Norm, Instance Norm, RMS Norm।
C. कहाँ लगाएँ:
Dropout (p = 0.5):
Train: Eval:
a1 ──✗ (dropped) a1' = a1 * (1 − p)
a2 ──✓ a2' = a2 * (1 − p)
a3 ──✗ a3' = a3 * (1 − p)
a4 ──✓
(हर node independently drop)
BatchNorm:
हर mini-batch के लिए:
μ = mean(x)
σ² = var(x)
x̂ = (x − μ) / √(σ² + ε)
y = γ·x̂ + β (γ, β learnable)
Training:
batch statistics use
Inference:
training में stored running mean/var use
import torch, torch.nn as nn, torch.nn.functional as F
class SmallCNN(nn.Module):
def __init__(self, n_classes=10):
super().__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.pool = nn.MaxPool2d(2)
self.fc1 = nn.Linear(64 * 8 * 8, 128)
self.fc2 = nn.Linear(128, n_classes)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x))) # 32×32 → 16×16
x = self.pool(F.relu(self.conv2(x))) # 16×16 → 8×8
x = x.flatten(1)
x = F.relu(self.fc1(x))
return self.fc2(x)
# model = SmallCNN()
# print(model)
A. Core layers:
| Layer | Purpose |
|---|---|
| Convolution | Learn local features; weights shared across space |
| Activation (ReLU) | Non-linearity |
| Pooling (max/avg) | Downsample; translation invariance |
| Global Average Pooling | Reduce spatial dims to 1×1 |
| Fully connected | Classification / regression head |
| Batch Norm | Stabilise and accelerate |
| Dropout | Regularize classification head |
B. Convolution variants: 1×1, 3×3, 5×5, 7×7; stride; dilated (atrous); transposed (deconvolution); depthwise separable.
C. Padding modes: 'valid' (no padding), 'same' (output = input size).
Input (5×5) Filter (3×3) Output (3×3)
1 0 1 0 0 1 0 1 5 4 4
0 1 1 1 0 * 0 1 0 = 4 4 5
1 0 1 0 1 1 0 1 4 5 5
0 1 1 1 0
1 0 1 0 0
Filter slides over input; at each position:
output[i,j] = Σ input[i+m, j+n] * filter[m,n] + bias
Pooling (2×2 max):
1 3 | 2 4
5 6 | 7 8 → 6 8
----+----
1 2 | 3 4
5 7 | 8 9 → 7 9
Typical CNN block:
Input → Conv → BN → ReLU → Pool → ... → Flatten → FC → Softmax
import torch, torch.nn as nn, torch.nn.functional as F
class SmallCNN(nn.Module):
def __init__(self, n_classes=10):
super().__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.pool = nn.MaxPool2d(2)
self.fc1 = nn.Linear(64 * 8 * 8, 128)
self.fc2 = nn.Linear(128, n_classes)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x))) # 32×32 → 16×16
x = self.pool(F.relu(self.conv2(x))) # 16×16 → 8×8
x = x.flatten(1)
x = F.relu(self.fc1(x))
return self.fc2(x)
# model = SmallCNN()
# print(model)
A. Core layers:
| Layer | उद्देश्य |
|---|---|
| Convolution | Local features सीखें; weights space पर shared |
| Activation (ReLU) | Non-linearity |
| Pooling (max/avg) | Downsample; translation invariance |
| Global Average Pooling | Spatial dims को 1×1 तक |
| Fully connected | Classification / regression head |
| Batch Norm | Stabilise और accelerate |
| Dropout | Classification head regularize |
B. Convolution variants: 1×1, 3×3, 5×5, 7×7; stride; dilated (atrous); transposed (deconvolution); depthwise separable।
C. Padding modes: 'valid' (कोई padding नहीं), 'same' (output = input size)।
Input (5×5) Filter (3×3) Output (3×3)
1 0 1 0 0 1 0 1 5 4 4
0 1 1 1 0 * 0 1 0 = 4 4 5
1 0 1 0 1 1 0 1 4 5 5
0 1 1 1 0
1 0 1 0 0
Filter input पर slide करता है; हर position पर:
output[i,j] = Σ input[i+m, j+n] * filter[m,n] + bias
Pooling (2×2 max):
1 3 | 2 4
5 6 | 7 8 → 6 8
----+----
1 2 | 3 4
5 7 | 8 9 → 7 9
Typical CNN block:
Input → Conv → BN → ReLU → Pool → ... → Flatten → FC → Softmax
import torchvision.models as models import torch.nn as nn # Load a pretrained ResNet-50 model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT) # Replace the classifier head for 10 classes model.fc = nn.Linear(model.fc.in_features, 10) # Now train just the head (transfer learning)
| Architecture | Year | Key Idea | Depth |
|---|---|---|---|
| LeNet-5 | 1998 | First successful CNN for digits | 7 |
| AlexNet | 2012 | ReLU, dropout, GPU training | 8 |
| VGG-16/19 | 2014 | Uniform 3×3 conv stacks | 16/19 |
| GoogLeNet/Inception | 2014 | Multi-scale Inception blocks, 1×1 bottlenecks | 22 |
| ResNet-50/101/152 | 2015 | Residual (skip) connections | 50–152 |
| DenseNet | 2016 | Dense connections (concat) | 121–264 |
| MobileNet | 2017 | Depthwise separable convs for mobile | ~28 |
| EfficientNet | 2019 | Compound scaling (depth × width × resolution) | B0–B7 |
| ConvNeXt | 2022 | Modernise ResNet with transformer tricks | ~50–200 |
Residual (skip) block:
x
│
┌────┴────┐
│ Conv │
│ BN │
│ ReLU │
│ Conv │
│ BN │
└────┬────┘
│
▼
x + F(x) → ReLU → output
▲
│ (identity shortcut)
Depth vs error (conceptually):
Plain net ── deeper after ~20 layers, error rises
ResNet ── deeper helps → 50, 101, 152, ...
Parameter comparison:
VGG-16 138M parameters
ResNet-50 25M parameters
MobileNet 4M parameters
import torchvision.models as models import torch.nn as nn # Pretrained ResNet-50 load model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT) # 10 classes के लिए classifier head बदलें model.fc = nn.Linear(model.fc.in_features, 10) # अब सिर्फ head train करें (transfer learning)
| Architecture | Year | Key Idea | Depth |
|---|---|---|---|
| LeNet-5 | 1998 | पहला successful CNN for digits | 7 |
| AlexNet | 2012 | ReLU, dropout, GPU training | 8 |
| VGG-16/19 | 2014 | Uniform 3×3 conv stacks | 16/19 |
| GoogLeNet/Inception | 2014 | Multi-scale Inception, 1×1 bottlenecks | 22 |
| ResNet-50/101/152 | 2015 | Residual (skip) connections | 50–152 |
| DenseNet | 2016 | Dense connections (concat) | 121–264 |
| MobileNet | 2017 | Depthwise separable convs for mobile | ~28 |
| EfficientNet | 2019 | Compound scaling (depth × width × resolution) | B0–B7 |
| ConvNeXt | 2022 | Transformer tricks से ResNet modernise | ~50–200 |
Residual (skip) block:
x
│
┌────┴────┐
│ Conv │
│ BN │
│ ReLU │
│ Conv │
│ BN │
└────┬────┘
│
▼
x + F(x) → ReLU → output
▲
│ (identity shortcut)
Depth vs error (conceptually):
Plain net ── ~20 layers के बाद deeper, error बढ़
ResNet ── deeper helps → 50, 101, 152, ...
Parameter comparison:
VGG-16 138M parameters
ResNet-50 25M parameters
MobileNet 4M parameters
xₜ and its
own previous hidden state hₜ₋₁, and produces a new hidden state
hₜ = f(Wx·xₜ + Wh·hₜ₋₁ + b). The same weights are reused at every step, so the
network handles variable-length sequences.
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, vocab_size, embed=64, hidden=128, n_classes=2):
super().__init__()
self.embed = nn.Embedding(vocab_size, embed)
self.rnn = nn.RNN(embed, hidden, batch_first=True)
self.fc = nn.Linear(hidden, n_classes)
def forward(self, x):
# x: (batch, seq_len) → embeddings
e = self.embed(x)
out, h_n = self.rnn(e) # h_n = last hidden state
return self.fc(h_n.squeeze(0))
A. Sequence tasks:
| Task | Input → Output | Example |
|---|---|---|
| One-to-one | Fixed → Fixed | Image classification |
| One-to-many | Fixed → Sequence | Image captioning |
| Many-to-one | Sequence → Fixed | Sentiment analysis |
| Many-to-many (aligned) | Sequence → Sequence | POS tagging |
| Many-to-many (encoder-decoder) | Sequence → Sequence | Machine translation |
B. RNN variants: Vanilla RNN, Bidirectional RNN, Deep (stacked) RNN, LSTM, GRU, and sequence-to-sequence with attention.
C. Problems: Vanishing gradients (long-term dependencies lost), exploding gradients, sequential computation (slow), no direct long-range skip.
Folded: Unrolled:
┌──┐ ┌──┐ ┌──┐ ┌──┐ ┌──┐
│h │──▶ h │h₀│──▶ │h₁│──▶ │h₂│──▶ │h₃│
└──┘ └──┘ └──┘ └──┘ └──┘
▲ ▲ ▲ ▲ ▲
│ │ │ │ │
x x₀ x₁ x₂ x₃
Same weights Wx, Wh, b at every step.
Vanishing gradient:
Gradient of loss wrt h₀ involves product of
Wh at each step → repeated multiplication
shrinks or explodes.
xₜ और अपना पिछला hidden state
hₜ₋₁ लेता है, और नया hidden state बनाता है
hₜ = f(Wx·xₜ + Wh·hₜ₋₁ + b)। वही weights हर step पर reuse होते हैं, जिससे network
variable-length sequences handle करता है।
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, vocab_size, embed=64, hidden=128, n_classes=2):
super().__init__()
self.embed = nn.Embedding(vocab_size, embed)
self.rnn = nn.RNN(embed, hidden, batch_first=True)
self.fc = nn.Linear(hidden, n_classes)
def forward(self, x):
# x: (batch, seq_len) → embeddings
e = self.embed(x)
out, h_n = self.rnn(e) # h_n = last hidden state
return self.fc(h_n.squeeze(0))
A. Sequence tasks:
| Task | Input → Output | Example |
|---|---|---|
| One-to-one | Fixed → Fixed | Image classification |
| One-to-many | Fixed → Sequence | Image captioning |
| Many-to-one | Sequence → Fixed | Sentiment analysis |
| Many-to-many (aligned) | Sequence → Sequence | POS tagging |
| Many-to-many (encoder-decoder) | Sequence → Sequence | Machine translation |
B. RNN variants: Vanilla RNN, Bidirectional RNN, Deep (stacked) RNN, LSTM, GRU, और attention वाला sequence-to-sequence।
C. Problems: Vanishing gradients (long-term dependencies खो), exploding gradients, sequential computation (slow), कोई direct long-range skip नहीं।
Folded: Unrolled:
┌──┐ ┌──┐ ┌──┐ ┌──┐ ┌──┐
│h │──▶ h │h₀│──▶ │h₁│──▶ │h₂│──▶ │h₃│
└──┘ └──┘ └──┘ └──┘ └──┘
▲ ▲ ▲ ▲ ▲
│ │ │ │ │
x x₀ x₁ x₂ x₃
Same weights Wx, Wh, b हर step पर।
Vanishing gradient:
h₀ के सापेक्ष loss का gradient में हर step
पर Wh का product → repeated multiplication
छोटा या बड़ा हो जाता है।
import torch.nn as nn
class SentimentLSTM(nn.Module):
def __init__(self, vocab_size, embed=128, hidden=256, n_classes=2):
super().__init__()
self.embed = nn.Embedding(vocab_size, embed)
self.lstm = nn.LSTM(embed, hidden, num_layers=2,
batch_first=True, bidirectional=True,
dropout=0.3)
self.fc = nn.Linear(hidden * 2, n_classes)
def forward(self, x):
e = self.embed(x)
out, (h, c) = self.lstm(e)
# take last timestep output (both directions concatenated)
return self.fc(out[:, -1, :])
# Replace LSTM with nn.GRU for GRU variant.
A. LSTM gates:
| Gate | Role |
|---|---|
| Forget gate (f) | Decide what to discard from cell state |
| Input gate (i) | Decide what new info to write |
| Output gate (o) | Decide what to expose as hidden state |
| Cell state (C) | Long-term memory; changes slowly |
| Hidden state (h) | Short-term memory; output |
B. GRU gates:
C. Variants: BiLSTM, BiGRU, stacked LSTM/GRU, peephole LSTM, ConvLSTM (for video), attention-augmented LSTM.
LSTM cell (simplified):
C_{t-1} ──────────────────────► C_t
│ │ ▲
│ │ ┌────┐ │
│ └─▶│ f │───┐ │
│ └────┘ │ │
│ ┌────┐ │ ┌───┐ │
│ ┌─▶│ i │───┼─▶│ × │ │
│ │ └────┘ │ └───┘ │
│ │ ┌────┐ │ │
│ └─▶│ c̃ │───┘ │
│ └────┘ │
│ │
│ ┌────┐ ┌───┐ │
│ ┌─▶│ o │──▶│ × │────┘
│ │ └────┘ └───┘
│ │ │
│ │ ▼
│ │ h_t
│ │
x_t, h_{t-1} ────┘
GRU cell (simplified):
z = σ(Wz·[h_{t-1}, x_t]) update
r = σ(Wr·[h_{t-1}, x_t]) reset
h̃ = tanh(W·[r * h_{t-1}, x_t])
h_t = (1 − z)*h_{t-1} + z*h̃
import torch.nn as nn
class SentimentLSTM(nn.Module):
def __init__(self, vocab_size, embed=128, hidden=256, n_classes=2):
super().__init__()
self.embed = nn.Embedding(vocab_size, embed)
self.lstm = nn.LSTM(embed, hidden, num_layers=2,
batch_first=True, bidirectional=True,
dropout=0.3)
self.fc = nn.Linear(hidden * 2, n_classes)
def forward(self, x):
e = self.embed(x)
out, (h, c) = self.lstm(e)
# last timestep output (दोनों directions concatenated)
return self.fc(out[:, -1, :])
# GRU variant के लिए nn.LSTM को nn.GRU से बदलें।
A. LSTM gates:
| Gate | Role |
|---|---|
| Forget gate (f) | Cell state से क्या हटाएँ |
| Input gate (i) | क्या नई info लिखें |
| Output gate (o) | Hidden state में क्या expose करें |
| Cell state (C) | Long-term memory; धीरे बदलती है |
| Hidden state (h) | Short-term memory; output |
B. GRU gates:
C. Variants: BiLSTM, BiGRU, stacked LSTM/GRU, peephole LSTM, ConvLSTM (video के लिए), attention-augmented LSTM।
LSTM cell (सरलीकृत):
C_{t-1} ──────────────────────► C_t
│ │ ▲
│ │ ┌────┐ │
│ └─▶│ f │───┐ │
│ └────┘ │ │
│ ┌────┐ │ ┌───┐ │
│ ┌─▶│ i │───┼─▶│ × │ │
│ │ └────┘ │ └───┘ │
│ │ ┌────┐ │ │
│ └─▶│ c̃ │───┘ │
│ └────┘ │
│ │
│ ┌────┐ ┌───┐ │
│ ┌─▶│ o │──▶│ × │────┘
│ │ └────┘ └───┘
│ │ │
│ │ ▼
│ │ h_t
│ │
x_t, h_{t-1} ────┘
GRU cell (सरलीकृत):
z = σ(Wz·[h_{t-1}, x_t]) update
r = σ(Wr·[h_{t-1}, x_t]) reset
h̃ = tanh(W·[r * h_{t-1}, x_t])
h_t = (1 − z)*h_{t-1} + z*h̃
import torch, math
import torch.nn as nn
class SelfAttention(nn.Module):
def __init__(self, dim, heads=8):
super().__init__()
self.heads = heads
self.to_qkv = nn.Linear(dim, dim * 3)
self.out = nn.Linear(dim, dim)
def forward(self, x):
B, T, C = x.shape
qkv = self.to_qkv(x).chunk(3, dim=-1)
q, k, v = [t.view(B, T, self.heads, C // self.heads)
.transpose(1, 2) for t in qkv]
# Scaled dot-product attention
scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
attn = scores.softmax(dim=-1)
out = (attn @ v).transpose(1, 2).reshape(B, T, C)
return self.out(out)
A. Attention variants:
| Type | Idea |
|---|---|
| Dot-product attention | Score = q · k |
| Scaled dot-product | Divide by √d to stabilise |
| Additive (Bahdanau) | Neural network to compute score |
| Multi-head | Parallel attention with different projections |
| Self-attention | Q, K, V from the same sequence |
| Cross-attention | Q from one sequence, K/V from another |
| Causal (masked) | Future positions masked; used in GPT |
| Flash attention | IO-aware exact attention; faster, less memory |
B. Transformer block:
C. Transformer families: Encoder-only (BERT, RoBERTa), Decoder-only (GPT, LLaMA), Encoder-decoder (T5, BART), Vision (ViT, Swin), Multimodal (CLIP, GPT-4V).
Self-attention:
Input X (T × d)
│
├─▶ Q = X·Wq
├─▶ K = X·Wk
└─▶ V = X·Wv
Scores = Q·Kᵀ / √d (T × T)
Attn = softmax(Scores)
Output = Attn · V (T × d)
Transformer encoder block:
x ──▶ MultiHeadSelfAttn ──▶ Add & LayerNorm
│
└── (residual)
│
▼
FeedForward (2 layers)
│
▼
Add & LayerNorm
│
▼
y
Decoder adds masked self-attention + cross-attention.
import torch, math
import torch.nn as nn
class SelfAttention(nn.Module):
def __init__(self, dim, heads=8):
super().__init__()
self.heads = heads
self.to_qkv = nn.Linear(dim, dim * 3)
self.out = nn.Linear(dim, dim)
def forward(self, x):
B, T, C = x.shape
qkv = self.to_qkv(x).chunk(3, dim=-1)
q, k, v = [t.view(B, T, self.heads, C // self.heads)
.transpose(1, 2) for t in qkv]
# Scaled dot-product attention
scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))
attn = scores.softmax(dim=-1)
out = (attn @ v).transpose(1, 2).reshape(B, T, C)
return self.out(out)
A. Attention variants:
| Type | Idea |
|---|---|
| Dot-product attention | Score = q · k |
| Scaled dot-product | √d से divide, stabilise |
| Additive (Bahdanau) | Neural network से score |
| Multi-head | Parallel attention with different projections |
| Self-attention | Q, K, V एक ही sequence से |
| Cross-attention | Q एक sequence से, K/V दूसरे से |
| Causal (masked) | Future positions mask; GPT में use |
| Flash attention | IO-aware exact attention; तेज़, कम memory |
B. Transformer block:
C. Transformer families: Encoder-only (BERT, RoBERTa), Decoder-only (GPT, LLaMA), Encoder-decoder (T5, BART), Vision (ViT, Swin), Multimodal (CLIP, GPT-4V)।
Self-attention:
Input X (T × d)
│
├─▶ Q = X·Wq
├─▶ K = X·Wk
└─▶ V = X·Wv
Scores = Q·Kᵀ / √d (T × T)
Attn = softmax(Scores)
Output = Attn · V (T × d)
Transformer encoder block:
x ──▶ MultiHeadSelfAttn ──▶ Add & LayerNorm
│
└── (residual)
│
▼
FeedForward (2 layers)
│
▼
Add & LayerNorm
│
▼
y
Decoder adds masked self-attention + cross-attention।
import torch.nn as nn, torch.nn.functional as F
class Autoencoder(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 32) # bottleneck
)
self.decoder = nn.Sequential(
nn.Linear(32, 128),
nn.ReLU(),
nn.Linear(128, 784),
nn.Sigmoid()
)
def forward(self, x):
z = self.encoder(x)
return self.decoder(z)
# loss = F.mse_loss(output, x)
A. Autoencoder variants:
| Variant | Key Idea |
|---|---|
| Vanilla AE | Reconstruction loss (MSE) |
| Denoising AE | Add noise, reconstruct clean |
| Sparse AE | Penalty on code activations |
| Contractive AE | Penalty on encoder Jacobian |
| Variational AE (VAE) | Probabilistic latent space, KL loss |
| Convolutional AE | Convs for images |
B. Generative models:
| Model | Idea |
|---|---|
| GAN | Generator vs discriminator minimax |
| DCGAN | Convolutional GAN |
| WGAN | Wasserstein loss — stable training |
| StyleGAN | Style-based generator, photorealistic faces |
| Conditional GAN | Condition on label / text |
| VAE | Latent variable model with encoder-decoder |
| Diffusion | Denoise random noise step-by-step |
Autoencoder:
Input x ──▶ [Encoder] ──▶ z (bottleneck) ──▶ [Decoder] ──▶ x̂
│
▼
Loss = |x − x̂|
GAN:
Random noise z ──▶ [Generator] ──▶ fake x̂
│
▼
┌──────────────────────┐
Real x ─────────────────▶ │ Discriminator D(x) │ ──▶ real/fake
└──────────────────────┘
│
▼
Generator loss: fool D
Discriminator: distinguish real vs fake
import torch.nn as nn, torch.nn.functional as F
class Autoencoder(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 32) # bottleneck
)
self.decoder = nn.Sequential(
nn.Linear(32, 128),
nn.ReLU(),
nn.Linear(128, 784),
nn.Sigmoid()
)
def forward(self, x):
z = self.encoder(x)
return self.decoder(z)
# loss = F.mse_loss(output, x)
A. Autoencoder variants:
| Variant | Key Idea |
|---|---|
| Vanilla AE | Reconstruction loss (MSE) |
| Denoising AE | Noise add, clean reconstruct |
| Sparse AE | Code activations पर penalty |
| Contractive AE | Encoder Jacobian पर penalty |
| Variational AE (VAE) | Probabilistic latent space, KL loss |
| Convolutional AE | Images के लिए Convs |
B. Generative models:
| Model | Idea |
|---|---|
| GAN | Generator vs discriminator minimax |
| DCGAN | Convolutional GAN |
| WGAN | Wasserstein loss — stable training |
| StyleGAN | Style-based generator, photorealistic faces |
| Conditional GAN | Label / text पर condition |
| VAE | Latent variable model encoder-decoder के साथ |
| Diffusion | Random noise step-by-step denoise |
Autoencoder:
Input x ──▶ [Encoder] ──▶ z (bottleneck) ──▶ [Decoder] ──▶ x̂
│
▼
Loss = |x − x̂|
GAN:
Random noise z ──▶ [Generator] ──▶ fake x̂
│
▼
┌──────────────────────┐
Real x ─────────────────▶ │ Discriminator D(x) │ ──▶ real/fake
└──────────────────────┘
│
▼
Generator loss: D को fool करो
Discriminator: real vs fake distinguish
import tensorflow as tf
from tensorflow.keras import layers, models
# Load data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
# Build model
model = models.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dropout(0.3),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(x_train, y_train,
epochs=5, batch_size=128,
validation_split=0.1)
model.evaluate(x_test, y_test)
A. TensorFlow APIs:
| API | Level | Use |
|---|---|---|
| Keras (tf.keras) | High | Standard model building |
| tf.Module / tf.function | Mid | Custom training loops |
| tf.GradientTape | Low | Manual gradient computation |
| TensorFlow Lite | Deployment | Mobile & edge inference |
| TensorFlow.js | Deployment | Browser / Node |
| TensorFlow Serving | Deployment | Production REST/gRPC |
| TFX | Pipelines | End-to-end ML pipelines |
| tf.data | Data | Efficient input pipelines |
B. Execution models: Eager (default, Pythonic) and Graph (tf.function, faster, deployable).
C. Distribution strategies: MirroredStrategy (single node multi-GPU), MultiWorkerMirroredStrategy (multi-node), TPUStrategy.
┌────────────────────────────────────────────┐
│ User Code (Python) │
├────────────────────────────────────────────┤
│ tf.keras (Sequential/Functional) │
├────────────────────────────────────────────┤
│ tf.Module / tf.function │
├────────────────────────────────────────────┤
│ tf.GradientTape (autograd) │
├────────────────────────────────────────────┤
│ TensorFlow Runtime (eager / graph) │
├────────────────────────────────────────────┤
│ CPU GPU TPU Distributed │
└────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
TFLite TF.js TF Serving
(mobile) (browser) (prod)
import tensorflow as tf
from tensorflow.keras import layers, models
# Data load
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
# Model बनाएँ
model = models.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dropout(0.3),
layers.Dense(64, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(x_train, y_train,
epochs=5, batch_size=128,
validation_split=0.1)
model.evaluate(x_test, y_test)
A. TensorFlow APIs:
| API | Level | Use |
|---|---|---|
| Keras (tf.keras) | High | Standard model building |
| tf.Module / tf.function | Mid | Custom training loops |
| tf.GradientTape | Low | Manual gradient computation |
| TensorFlow Lite | Deployment | Mobile और edge inference |
| TensorFlow.js | Deployment | Browser / Node |
| TensorFlow Serving | Deployment | Production REST/gRPC |
| TFX | Pipelines | End-to-end ML pipelines |
| tf.data | Data | Efficient input pipelines |
B. Execution models: Eager (default, Pythonic) और Graph (tf.function, तेज़, deployable)।
C. Distribution strategies: MirroredStrategy (single node multi-GPU), MultiWorkerMirroredStrategy (multi-node), TPUStrategy।
┌────────────────────────────────────────────┐
│ User Code (Python) │
├────────────────────────────────────────────┤
│ tf.keras (Sequential/Functional) │
├────────────────────────────────────────────┤
│ tf.Module / tf.function │
├────────────────────────────────────────────┤
│ tf.GradientTape (autograd) │
├────────────────────────────────────────────┤
│ TensorFlow Runtime (eager / graph) │
├────────────────────────────────────────────┤
│ CPU GPU TPU Distributed │
└────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
TFLite TF.js TF Serving
(mobile) (browser) (prod)
autograd, a neural network
module (torch.nn), optimizers (torch.optim), data utilities
(torch.utils.data), and a rich ecosystem (torchvision, torchaudio, Hugging
Face, Lightning).
import torch, torch.nn as nn, torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# Data
X = torch.randn(1000, 784)
y = torch.randint(0, 10, (1000,))
loader = DataLoader(TensorDataset(X, y), batch_size=64, shuffle=True)
# Model
model = nn.Sequential(
nn.Linear(784, 128), nn.ReLU(), nn.Dropout(0.3),
nn.Linear(128, 64), nn.ReLU(),
nn.Linear(64, 10)
)
# Training
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(5):
for xb, yb in loader:
xb, yb = xb.to(device), yb.to(device)
optimizer.zero_grad()
out = model(xb)
loss = criterion(out, yb)
loss.backward()
optimizer.step()
print(f"epoch {epoch} done")
A. Core components:
| Component | Purpose |
|---|---|
| torch.Tensor | Multi-dim array with GPU support |
| torch.autograd | Automatic differentiation |
| torch.nn | Layers, losses, containers |
| torch.optim | Optimizers and LR schedulers |
| torch.utils.data | Dataset, DataLoader |
| torchvision | Pretrained vision models, transforms |
| torchaudio / torchtext | Audio and text utilities |
| torch.compile (2.0+) | JIT compile for speed |
| TorchScript | Export for deployment |
| PyTorch Lightning | High-level training loop wrapper |
B. Model APIs: Sequential, Module (custom class), Functional.
C. Deployment: TorchScript, ONNX export, TorchServe, quantization.
loss.backward().
Canonical training loop:
for epoch in epochs:
for xb, yb in loader:
optimizer.zero_grad() # reset grads
pred = model(xb) # forward
loss = criterion(pred, yb)
loss.backward() # backward
optimizer.step() # update
Ecosystem:
torch.nn → layers, losses
torch.optim → SGD, Adam, AdamW
torch.utils.data→ Dataset, DataLoader
torchvision → ResNet, transforms
Hugging Face → transformers, datasets
Lightning → high-level Trainer
autograd से automatic differentiation, torch.nn neural network
module, torch.optim optimizers, torch.utils.data data utilities
और rich ecosystem (torchvision, torchaudio, Hugging Face, Lightning) देता है।
import torch, torch.nn as nn, torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# Data
X = torch.randn(1000, 784)
y = torch.randint(0, 10, (1000,))
loader = DataLoader(TensorDataset(X, y), batch_size=64, shuffle=True)
# Model
model = nn.Sequential(
nn.Linear(784, 128), nn.ReLU(), nn.Dropout(0.3),
nn.Linear(128, 64), nn.ReLU(),
nn.Linear(64, 10)
)
# Training
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(5):
for xb, yb in loader:
xb, yb = xb.to(device), yb.to(device)
optimizer.zero_grad()
out = model(xb)
loss = criterion(out, yb)
loss.backward()
optimizer.step()
print(f"epoch {epoch} done")
A. Core components:
| Component | उद्देश्य |
|---|---|
| torch.Tensor | GPU support वाला multi-dim array |
| torch.autograd | Automatic differentiation |
| torch.nn | Layers, losses, containers |
| torch.optim | Optimizers और LR schedulers |
| torch.utils.data | Dataset, DataLoader |
| torchvision | Pretrained vision models, transforms |
| torchaudio / torchtext | Audio और text utilities |
| torch.compile (2.0+) | Speed के लिए JIT compile |
| TorchScript | Deployment के लिए export |
| PyTorch Lightning | High-level training loop wrapper |
B. Model APIs: Sequential, Module (custom class), Functional।
C. Deployment: TorchScript, ONNX export, TorchServe, quantization।
loss.backward()।
Canonical training loop:
for epoch in epochs:
for xb, yb in loader:
optimizer.zero_grad() # grads reset
pred = model(xb) # forward
loss = criterion(pred, yb)
loss.backward() # backward
optimizer.step() # update
Ecosystem:
torch.nn → layers, losses
torch.optim → SGD, Adam, AdamW
torch.utils.data→ Dataset, DataLoader
torchvision → ResNet, transforms
Hugging Face → transformers, datasets
Lightning → high-level Trainer
import torch, torch.nn as nn, torch.optim as optim
import torchvision.models as models
# Load pretrained ResNet-18
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
# Replace the classifier for 5 classes
model.fc = nn.Linear(model.fc.in_features, 5)
# Freeze backbone (feature extraction)
for p in model.parameters():
p.requires_grad = False
for p in model.fc.parameters():
p.requires_grad = True
# Train only the head first
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3)
# Later: unfreeze more layers and fine-tune with smaller LR
# for p in model.parameters():
# p.requires_grad = True
# optimizer = optim.Adam(model.parameters(), lr=1e-5)
A. Strategies:
| Strategy | Frozen Layers | Data Needed |
|---|---|---|
| Feature extraction | All backbone | Small (hundreds) |
| Partial fine-tuning | Early layers | Medium (thousands) |
| Full fine-tuning | None | Large (tens of thousands) |
| Domain adaptation | Depends | Unsupervised or semi-supervised |
| Adapter tuning | Backbone frozen, small adapters trained | Small |
| LoRA | Backbone frozen, low-rank updates | Small; efficient for LLMs |
| Prompt tuning | Model frozen; learn prompts | Very small |
B. Popular pretrained models:
C. Sources: torchvision, Hugging Face Hub, TensorFlow Hub, TIMM.
Pretrained backbone (e.g., ResNet-50 on ImageNet):
[ Conv1 ] → [ Conv2 ] → ... → [ Conv5 ] → [ FC-1000 ]
Feature extraction:
[ Conv1 ... Conv5 ] (frozen) → [ New FC-n ] ← train only this
Partial fine-tuning:
[ Conv1 ] (frozen) → [ Conv2 ... Conv5 ] → [ New FC-n ]
↑ train with small LR
Full fine-tuning:
[ Conv1 ... Conv5 ] → [ New FC-n ] ← all train with small LR
LoRA / adapters (for large models):
[ Backbone frozen ] + [ small adapters trained ]
import torch, torch.nn as nn, torch.optim as optim
import torchvision.models as models
# Pretrained ResNet-18 load
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
# 5 classes के लिए classifier बदलें
model.fc = nn.Linear(model.fc.in_features, 5)
# Backbone freeze (feature extraction)
for p in model.parameters():
p.requires_grad = False
for p in model.fc.parameters():
p.requires_grad = True
# पहले सिर्फ head train करें
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3)
# बाद में: और layers unfreeze करके छोटी LR से fine-tune
# for p in model.parameters():
# p.requires_grad = True
# optimizer = optim.Adam(model.parameters(), lr=1e-5)
A. Strategies:
| Strategy | Frozen Layers | Data Needed |
|---|---|---|
| Feature extraction | पूरा backbone | छोटा (सैकड़ों) |
| Partial fine-tuning | Early layers | मध्यम (हजारों) |
| Full fine-tuning | कोई नहीं | बड़ा (दसियों हज़ार) |
| Domain adaptation | Depends | Unsupervised / semi-supervised |
| Adapter tuning | Backbone frozen, छोटे adapters train | छोटा |
| LoRA | Backbone frozen, low-rank updates | छोटा; LLMs के लिए efficient |
| Prompt tuning | Model frozen; prompts सीखें | बहुत छोटा |
B. Popular pretrained models:
C. Sources: torchvision, Hugging Face Hub, TensorFlow Hub, TIMM।
Pretrained backbone (जैसे ResNet-50 on ImageNet):
[ Conv1 ] → [ Conv2 ] → ... → [ Conv5 ] → [ FC-1000 ]
Feature extraction:
[ Conv1 ... Conv5 ] (frozen) → [ New FC-n ] ← सिर्फ यह train
Partial fine-tuning:
[ Conv1 ] (frozen) → [ Conv2 ... Conv5 ] → [ New FC-n ]
↑ छोटी LR से train
Full fine-tuning:
[ Conv1 ... Conv5 ] → [ New FC-n ] ← सब छोटी LR से train
LoRA / adapters (बड़े models के लिए):
[ Backbone frozen ] + [ छोटे adapters train ]
from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix # Splits X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.15, stratify=y) X_tr, X_val, y_tr, y_val = train_test_split(X_tr, y_tr, test_size=0.15, stratify=y_tr) # Train on X_tr with early stopping on X_val # ... # Final evaluation on X_te (ONLY once) preds = model.predict(X_te) print(classification_report(y_te, preds)) print(confusion_matrix(y_te, preds))
A. Data splits:
| Split | Purpose |
|---|---|
| Training | Learn weights |
| Validation | Model selection, early stopping, hyperparameter tuning |
| Test | Final unbiased estimate (used once) |
| K-fold cross-validation | Small datasets; average across folds |
| Stratified split | Preserves class proportions |
| Time-series split | Respects temporal order |
B. Metrics:
| Task | Metrics |
|---|---|
| Binary classification | Precision, Recall, F1, ROC-AUC, PR-AUC |
| Multi-class | Accuracy, macro F1, confusion matrix, top-k accuracy |
| Regression | MSE, MAE, RMSE, R², MAPE |
| Ranking / detection | mAP, IoU, NDCG |
| Generation | BLEU, ROUGE, FID, IS, perplexity |
| Calibration | Reliability diagrams, ECE |
C. Tuning methods: Grid search, random search, Bayesian optimization (Optuna, Hyperopt, Ax), population-based training, ASHA.
Data splits:
Total Data
├── Train (70%) ── learn weights
├── Validation (15%) ── tune hyperparams, early stop
└── Test (15%) ── final unbiased estimate
Workflow:
1. Split data
2. Train on train, monitor on val
3. Tune hyperparameters using val
4. Retrain with best config (optional)
5. Evaluate once on test
6. Report + compare baseline
Confusion matrix (binary):
Pred + Pred -
Actual + TP FN
Actual - FP TN
Precision = TP/(TP+FP) Recall = TP/(TP+FN)
F1 = 2·P·R/(P+R) Accuracy = (TP+TN)/All
from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix # Splits X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.15, stratify=y) X_tr, X_val, y_tr, y_val = train_test_split(X_tr, y_tr, test_size=0.15, stratify=y_tr) # X_tr पर train करें, X_val पर early stopping # ... # Final evaluation X_te पर (सिर्फ एक बार) preds = model.predict(X_te) print(classification_report(y_te, preds)) print(confusion_matrix(y_te, preds))
A. Data splits:
| Split | उद्देश्य |
|---|---|
| Training | Weights सीखें |
| Validation | Model selection, early stopping, hyperparameter tuning |
| Test | Final unbiased estimate (एक बार) |
| K-fold cross-validation | छोटे datasets; folds का average |
| Stratified split | Class proportions preserve |
| Time-series split | Temporal order respect |
B. Metrics:
| Task | Metrics |
|---|---|
| Binary classification | Precision, Recall, F1, ROC-AUC, PR-AUC |
| Multi-class | Accuracy, macro F1, confusion matrix, top-k accuracy |
| Regression | MSE, MAE, RMSE, R², MAPE |
| Ranking / detection | mAP, IoU, NDCG |
| Generation | BLEU, ROUGE, FID, IS, perplexity |
| Calibration | Reliability diagrams, ECE |
C. Tuning methods: Grid search, random search, Bayesian optimization (Optuna, Hyperopt, Ax), population-based training, ASHA।
Data splits:
Total Data
├── Train (70%) ── weights सीखें
├── Validation (15%) ── hyperparams tune, early stop
└── Test (15%) ── final unbiased estimate
Workflow:
1. Data split करें
2. Train पर train, val पर monitor
3. Val से hyperparameters tune करें
4. Best config से retrain (optional)
5. Test पर एक बार evaluate
6. Report + baseline compare
Confusion matrix (binary):
Pred + Pred -
Actual + TP FN
Actual - FP TN
Precision = TP/(TP+FP) Recall = TP/(TP+FN)
F1 = 2·P·R/(P+R) Accuracy = (TP+TN)/All
# FastAPI microservice
from fastapi import FastAPI
import torch
from torchvision import transforms
app = FastAPI()
model = torch.jit.load("model.pt").eval()
@app.post("/predict")
def predict(payload: dict):
x = preprocess(payload["image"])
with torch.no_grad():
y = model(x).softmax(-1)
return {"class": int(y.argmax()), "confidence": float(y.max())}
# Run: uvicorn app:app --host 0.0.0.0 --port 8000
# Or TorchServe / TF Serving for scalable production serving.
# Optimisation: quantize to int8
quantized = torch.quantization.quantize_dynamic(
model, {torch.nn.Linear}, dtype=torch.qint8
)
A. Deployment patterns:
| Pattern | Description |
|---|---|
| Batch inference | Run on data dumps; cheap, offline |
| Online / real-time | REST/gRPC API; low latency |
| Streaming | Kafka + inference workers |
| Edge / on-device | TFLite, Core ML, ONNX Runtime, NCNN |
| Serverless | Cloud Functions, AWS Lambda + model files |
| GPU inference servers | TorchServe, TF Serving, Triton, vLLM |
B. Optimisation techniques:
C. Ethical AI pillars: Fairness, Explainability, Privacy, Safety, Accountability, Transparency.
MLOps lifecycle:
Data → Train → Evaluate → Deploy → Monitor → Retrain
▲ │
└─────────── drift detected ─────────────────┘
Serving options:
Client ─▶ API Gateway ─▶ Inference Service ─▶ Model
(REST/gRPC) (TorchServe,
TF Serving,
Triton, vLLM)
Ethical pillars:
┌────────────────────────────────┐
│ Fairness · Explainability │
│ Privacy · Safety │
│ Accountability · Transparency │
└────────────────────────────────┘
Real-world uses:
Vision : medical imaging, autonomous vehicles, retail
Language : chat, translation, code, search
Speech : assistants, transcription, voice cloning
Science : drug discovery, climate, protein folding
# FastAPI microservice
from fastapi import FastAPI
import torch
from torchvision import transforms
app = FastAPI()
model = torch.jit.load("model.pt").eval()
@app.post("/predict")
def predict(payload: dict):
x = preprocess(payload["image"])
with torch.no_grad():
y = model(x).softmax(-1)
return {"class": int(y.argmax()), "confidence": float(y.max())}
# Run: uvicorn app:app --host 0.0.0.0 --port 8000
# या scalable production serving के लिए TorchServe / TF Serving।
# Optimisation: int8 पर quantize
quantized = torch.quantization.quantize_dynamic(
model, {torch.nn.Linear}, dtype=torch.qint8
)
A. Deployment patterns:
| Pattern | विवरण |
|---|---|
| Batch inference | Data dumps पर चलाएँ; सस्ता, offline |
| Online / real-time | REST/gRPC API; low latency |
| Streaming | Kafka + inference workers |
| Edge / on-device | TFLite, Core ML, ONNX Runtime, NCNN |
| Serverless | Cloud Functions, AWS Lambda + model files |
| GPU inference servers | TorchServe, TF Serving, Triton, vLLM |
B. Optimisation techniques:
C. Ethical AI pillars: Fairness, Explainability, Privacy, Safety, Accountability, Transparency।
MLOps lifecycle:
Data → Train → Evaluate → Deploy → Monitor → Retrain
▲ │
└─────────── drift detected ─────────────────┘
Serving options:
Client ─▶ API Gateway ─▶ Inference Service ─▶ Model
(REST/gRPC) (TorchServe,
TF Serving,
Triton, vLLM)
Ethical pillars:
┌────────────────────────────────┐
│ Fairness · Explainability │
│ Privacy · Safety │
│ Accountability · Transparency │
└────────────────────────────────┘
Real-world uses:
Vision : medical imaging, autonomous vehicles, retail
Language : chat, translation, code, search
Speech : assistants, transcription, voice cloning
Science : drug discovery, climate, protein folding