Phase 2 • Flagship Practical Curriculum • 2026 Edition

Stage 2: Machine Learning & Deep Learning Core

Transform foundational mathematics into real-world predictive models and neural network architectures. Master Scikit-Learn pipelines, XGBoost, PyTorch from scratch, backpropagation, CNNs, ResNets, Sequence Modeling, and Attention mechanics with production-ready code.

8–12 Weeks Comprehensive Study 7 Core Modules • 4 Interactive Simulators 2 Complete End-to-End PyTorch Projects 100% Free Stanford, MIT & Open-Source Textbooks

Is Stage 1 Really Enough? Why You Must Take Stage 2

Stage 1 (AI Foundations & Applied Math) gave you the mathematical bedrock: Linear Algebra (dot products, eigenvalues, SVD), Multivariate Calculus (gradients, Jacobians, Hessians), Probability (Bayes, MLE, Gaussian distributions), and Information Theory. Without Stage 1, neural networks are black boxes.

However, math on paper cannot classify images or predict churn. In Stage 2, you cross the bridge into practical execution: how to turn dot products into matrix layers ($Wx + b$), how vector gradients become backpropagation in PyTorch, how inductive bias produces Convolutional Networks (CNNs) for vision and Attention mechanisms for language, and how to avoid the deadly traps of data leakage and vanishing gradients. Stage 1 is the fuel; Stage 2 is the engine.

← Review Stage 1 Math Course • Start Module 1 Below ↓
Module 01

The Machine Learning Pipeline & Data Rigor

Weeks 1–2 • Foundations

Before training any model, 80% of real-world machine learning engineering happens in the data formulation, validation splits, and metric design. A model trained on leaky data or evaluated with the wrong metric will fail catastrophically in production.

1.1 The Machine Learning Paradigm

In traditional software engineering, developers write explicit rules: Rules + Data = Answers. In Machine Learning, the system inverts this paradigm: Data + Answers = Rules (Model Parameters $\theta$).

  • Supervised Learning: Learning an approximation function $f_\theta(x) \approx y$ from labeled pairs $\{(x_i, y_i)\}_{i=1}^N$. Used for Regression (continuous targets) and Classification (discrete categorical targets).
  • Unsupervised Learning: Discovering latent patterns, clusters, and low-dimensional manifolds in unlabeled data $\{x_i\}_{i=1}^N$ (e.g., K-Means, PCA, Autoencoders).
  • Self-Supervised Learning (SSL): The engine of modern LLMs and Foundation Models. Automatically generating training targets directly from raw data (e.g., masked token prediction, next-word prediction).
  • Reinforcement Learning (RL): An agent learns a policy $\pi_\theta(a|s)$ by interacting with an environment, maximizing cumulative scalar reward via trial and error.

1.2 The Bias-Variance Tradeoff & Generalization

The fundamental goal of machine learning is generalization: performing well on unseen test data, not just memorizing the training set. For any estimator, the expected test error decomposes mathematically into three distinct terms:

Bias-Variance Decomposition $$\mathbb{E}[(y - \hat{f}(x))^2] = \underbrace{\text{Bias}[\hat{f}(x)]^2}_{\text{Underfitting}} + \underbrace{\text{Var}[\hat{f}(x)]}_{\text{Overfitting}} + \underbrace{\sigma^2}_{\text{Irreducible Noise}}$$
  • High Bias (Underfitting): The model is too simple to capture the underlying structure (e.g., fitting a straight line to quadratic data). Training error is high, and test error is high. Solution: Increase model capacity, add polynomial features, or reduce regularization.
  • High Variance (Overfitting): The model has too much capacity and memorizes random statistical noise in the training set. Training error is near zero, but test error skyrockets. Solution: Gather more data, apply L1/L2 regularization, apply dropout, or use ensemble bagging (Random Forests).

1.3 Data Leakage & Validation Rigor

Data Leakage is the #1 silent killer in production ML. It occurs when information from the target or test distribution accidentally contaminates the training set before modeling.

  • Preprocessing Leakage: Fitting a StandardScaler or imputation transformer on the entire dataset before splitting into train/test. Rule: Always fit transformers strictly on the training fold, then transform test folds!
  • Temporal Leakage: Using future events to predict past events in time-series data. Rule: Always use expanding or rolling window splits (TimeSeriesSplit), never random shuffle!
  • Group Leakage: Samples from the same patient, user, or device appearing in both train and validation sets. Rule: Use GroupKFold so user IDs are strictly partition-isolated!

1.4 Production Evaluation Metrics

Why Accuracy is a trap: In fraud detection with 99.9% legitimate transactions, a naive model that predicts "Not Fraud" for everything achieves 99.9% accuracy while catching 0 frauds.

Metric Formula When to Use It
Precision $\frac{TP}{TP + FP}$ When False Positives are expensive (e.g., spam filter, stock purchase recommendation).
Recall (Sensitivity) $\frac{TP}{TP + FN}$ When False Negatives are dangerous (e.g., cancer diagnosis, fraud detection).
F1-Score $2 \times \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}$ Harmonic mean of Precision and Recall. Balances both on imbalanced datasets.
ROC-AUC Area under TPR vs FPR curve Measures ranking capability across all classification probability thresholds.
PR-AUC Area under Precision-Recall curve The gold standard for heavily imbalanced classes (e.g., positive class < 1%).
RMSE / MAE $\sqrt{\frac{1}{N}\sum(y-\hat{y})^2}$ / $\frac{1}{N}\sum|y-\hat{y}|$ RMSE penalizes large outliers severely; MAE is robust against outliers in regression.
Module 02

Classical Machine Learning & Tree Ensembles

Weeks 3–4 • Tabular Mastery

Deep learning does not beat tree-based models on tabular data. For structured databases, Kaggle competitions, and business predictive analytics, Gradient Boosted Decision Trees (GBDTs like XGBoost and LightGBM) remain the reigning champions.

2.1 Linear & Logistic Regression

Linear models are the building blocks of neural layers. In Linear Regression, we minimize the Ordinary Least Squares (OLS) objective:

Linear Regression Normal Equation & Cost $$J(\theta) = \frac{1}{2m}\sum_{i=1}^m \left(h_\theta(x^{(i)}) - y^{(i)}\right)^2 \quad \implies \quad \theta^* = (X^T X)^{-1} X^T y$$

In Logistic Regression for binary classification, we pass the linear combination through the Sigmoid function $\sigma(z) = \frac{1}{1 + e^{-z}}$ to map raw logits into valid probabilities $\in (0, 1)$, optimizing Binary Cross-Entropy loss:

Binary Cross-Entropy Loss (Log-Loss) $$\mathcal{L}_{\text{BCE}}(\theta) = -\frac{1}{m} \sum_{i=1}^m \left[ y^{(i)} \log(\sigma(w^T x^{(i)} + b)) + (1 - y^{(i)}) \log(1 - \sigma(w^T x^{(i)} + b)) \right]$$

2.2 Regularization: Ridge (L2), Lasso (L1) & ElasticNet

To constrain model complexity and shrink parameters toward zero, we add a penalty term to the loss function:

  • Ridge Regression ($L_2$ Penalty): Adds $\lambda \sum_{j=1}^p \theta_j^2$. Shrinks weights smoothly toward zero, mitigating multicollinearity. In deep learning, this is known as Weight Decay.
  • Lasso Regression ($L_1$ Penalty): Adds $\lambda \sum_{j=1}^p |\theta_j|$. Because the $L_1$ contour has sharp diamond corners on coordinate axes, it drives unimportant weights to exactly zero, performing automatic feature selection and producing sparse models.
  • ElasticNet: Convex combination of both $L_1$ and $L_2$ penalties, combining feature sparsity with stability among correlated predictors.

2.3 Decision Trees, Random Forests & Boosting

Decision trees recursively partition feature space into axis-aligned rectangular regions using greedy splitting criteria:

  • Gini Impurity: $I_G(p) = 1 - \sum_{k=1}^K p_k^2$ (fast to compute; preferred in CART).
  • Information Gain / Entropy: $H(S) = -\sum_{k=1}^K p_k \log_2(p_k)$ (maximizes information entropy reduction).

Ensemble Learning Paradigms:

  • Bagging (Bootstrap Aggregation - Random Forests): Train $B$ deep, high-variance decision trees in parallel on bootstrap sample subsets of data. For each split, randomly sample a subset of $m \approx \sqrt{p}$ features. Averaging predictions reduces variance by factor $\approx 1/B$ without increasing bias.
  • Boosting (Sequential Residual Learning - XGBoost, LightGBM): Train $M$ shallow, high-bias decision trees sequentially. Each new tree $t$ fits directly to the negative gradient (residuals) of the previous ensemble's errors: $$\hat{y}_i^{(t)} = \hat{y}_i^{(t-1)} + \eta f_t(x_i)$$ where $\eta$ is the learning rate (shrinkage factor).
  • Why XGBoost is so fast: Uses a 2nd-order Taylor expansion of the loss function (gradient $g_i$ and Hessian $h_i$), exact greedy or histogram-based quantile sketch splits, and hardware cache-aware block structure.

2.4 Unsupervised Learning: Clustering & Dimensionality Reduction

When labels are absent, unsupervised algorithms identify natural manifold geometries:

  • K-Means Clustering: Alternates between (1) assigning each point to nearest centroid $\mu_k$, and (2) updating $\mu_k = \frac{1}{|C_k|}\sum_{x \in C_k} x$. Sensitive to initialization; always use k-means++ which spaces initial seeds proportional to squared distance. Select $k$ via the Elbow Method or Silhouette Score.
  • DBSCAN: Density-Based Spatial Clustering. Finds clusters of arbitrary shapes and isolates outliers as noise without pre-specifying $k$.
  • Principal Component Analysis (PCA): Projects $d$-dimensional data onto $k$ orthogonal principal directions maximizing variance. Computed via the eigendecomposition of the empirical covariance matrix $\Sigma = \frac{1}{n} X^T X$ or Singular Value Decomposition (SVD).
Module 03

Neural Network Foundations & Backpropagation

Weeks 5–6 • Deep Learning Core

A neural network is a parameterized, differentiable computational graph that implements function composition: $f(x) = f_L(f_{L-1}(\dots f_1(x)))$. By the Universal Approximation Theorem, a feedforward network with a single non-linear hidden layer can approximate any continuous function to arbitrary precision.

3.1 The Forward Pass & Activation Functions

In each dense layer $l$, the input vector $a^{[l-1]}$ undergoes an affine linear transformation followed by an element-wise non-linear activation $\phi$:

Layer Forward Equations $$z^{[l]} = W^{[l]} a^{[l-1]} + b^{[l]}, \qquad a^{[l]} = \phi(z^{[l]})$$

Why Non-Linearity is Mandatory: Without non-linear activations, composing $L$ linear layers is mathematically equivalent to a single linear layer: $W_2(W_1 x + b_1) + b_2 = (W_2 W_1)x + (W_2 b_1 + b_2) = W'x + b'$. Depth provides zero representational benefit without non-linear activations!

Modern Activation Taxonomy:

  • ReLU (Rectified Linear Unit): $\phi(z) = \max(0, z)$. Derivative is $1$ for $z > 0$ and $0$ for $z < 0$. Eliminates vanishing gradients in positive regime and computes fast. Can suffer from "Dying ReLU" if neurons receive large negative updates.
  • Leaky ReLU / PReLU: $\phi(z) = \max(\alpha z, z)$ (with $\alpha \approx 0.01$). Ensures non-zero gradient flow in negative regime.
  • GELU (Gaussian Error Linear Unit): $\phi(z) = z \cdot \Phi(z) \approx 0.5z(1 + \tanh(\sqrt{2/\pi}(z + 0.044715z^3)))$. Weights inputs by their value according to Gaussian CDF. The default activation in modern Transformers (BERT, GPT-2/3/4, Llama)!
  • Softmax: $\sigma(z)_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}$. Converts raw output logits into a normalized probability distribution over $K$ mutually exclusive classes.

3.2 The Exact Mathematics of Backpropagation

Backpropagation is simply the recursive application of the Multivariate Chain Rule in reverse order (Reverse-Mode Automatic Differentiation). Given scalar loss $\mathcal{L}$, we compute partial derivatives $\frac{\partial \mathcal{L}}{\partial W^{[l]}}$ and $\frac{\partial \mathcal{L}}{\partial b^{[l]}}$ by propagating downstream error signals $\delta^{[l]} = \frac{\partial \mathcal{L}}{\partial z^{[l]}}$:

Backprop Matrix Equations (Batch of size $m$) $$\delta^{[L]} = \nabla_{a^{[L]}}\mathcal{L} \odot \phi'(z^{[L]}) \quad (\text{For Softmax + Cross-Entropy: } \delta^{[L]} = \hat{y} - y)$$ $$\delta^{[l]} = \left( (W^{[l+1]})^T \delta^{[l+1]} \right) \odot \phi'(z^{[l]})$$ $$\frac{\partial \mathcal{L}}{\partial W^{[l]}} = \frac{1}{m} \delta^{[l]} (a^{[l-1]})^T, \qquad \frac{\partial \mathcal{L}}{\partial b^{[l]}} = \frac{1}{m} \sum_{i=1}^m \delta^{[l](i)}$$

3.3 Weight Initialization & Vanishing/Exploding Gradients

If all weights are initialized to 0, every neuron in a layer computes the exact same gradient and activations: the symmetry problem prevents distinct feature learning.

  • If weights are initialized too large ($\text{std} \gg 1$), activations and gradients explode exponentially with depth $L$.
  • If weights are initialized too small ($\text{std} \ll 1$), activations shrink to 0 and gradients vanish completely.
  • Xavier / Glorot Initialization (for Tanh / Sigmoid): $\text{Var}(W) = \frac{2}{n_{\text{in}} + n_{\text{out}}}$. Preserves variance of activations across layers for symmetric activations.
  • He / Kaiming Initialization (for ReLU / GELU): $\text{Var}(W) = \frac{2}{n_{\text{in}}}$. Corrects for the fact that ReLU zeroes out roughly half the activations. Crucial for deep ResNets!
Module 04

Deep Learning Optimization & Regularization

Weeks 7–8 • Training Dynamics

Loss landscapes of deep neural networks are non-convex, featuring ravines, saddle points, and noisy stochastic mini-batches. Advanced adaptive optimizers and normalization techniques make stable training of billion-parameter models possible.

4.1 The Gradient Descent Family & AdamW

Standard Mini-batch SGD oscillates wildly in steep ravines. Modern optimizers incorporate momentum and adaptive learning rates:

  • SGD with Momentum: Maintains an exponentially decaying moving average of past gradients: $v_t = \beta v_{t-1} + (1-\beta)g_t$. Parameters update via $\theta_t = \theta_{t-1} - \eta v_t$. Acts like a heavy ball rolling down a hill, dampening oscillations.
  • RMSprop: Normalizes gradient by dividing by root of moving average of squared gradients: $s_t = \gamma s_{t-1} + (1-\gamma)g_t^2$, updating $\theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{s_t + \epsilon}} g_t$.
  • Adam (Adaptive Moment Estimation): Combines 1st moment (momentum $m_t$) and 2nd moment (uncentered variance $v_t$) with bias correction: $$\hat{m}_t = \frac{m_t}{1 - \beta_1^t}, \quad \hat{v}_t = \frac{v_t}{1 - \beta_2^t} \quad \implies \quad \theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon} \hat{m}_t$$
  • AdamW (Loshchilov & Hutter, 2017): Discovered that standard Adam erroneously couples $L_2$ regularization inside the adaptive gradient denominator, causing weights with large historical gradients to be under-regularized. AdamW decouples weight decay directly from gradient updates: $$\theta_t = \theta_{t-1} - \eta \lambda \theta_{t-1} - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon} \hat{m}_t$$ AdamW is the undisputed industry standard for training LLMs and Vision models!

4.2 Normalization: BatchNorm vs. LayerNorm

Normalization stabilizes intermediate activation distributions, smoothing the optimization landscape and allowing significantly higher learning rates:

Feature Batch Normalization (BatchNorm) Layer Normalization (LayerNorm)
Normalization Axis Normalizes across the batch dimension for each feature channel independently. Normalizes across all features / channels for each sample independently.
Batch Size Dependency Requires large batch sizes ($N \ge 32$) to estimate stable mean/variance. Breaks with $N=1$. Completely independent of batch size! Works perfectly on batch size 1.
Train vs Eval Behavior Computes mini-batch stats during train; uses running running averages during inference. Identical computation during both training and inference.
Where it Dominates Computer Vision & Convolutional Networks (ResNet, EfficientNet). Transformers, LLMs (GPT, Llama), and Sequence/RNN models.

4.3 Regularization: Dropout & Learning Rate Schedulers

  • Dropout (Srivastava et al., 2014): During training, randomly zero out each neuron's activation with probability $p$ (typically $p=0.2$ to $0.5$). Uses inverted dropout during forward pass ($\frac{a}{1-p}$) so no scaling is needed at test time. Prevents neurons from co-adapting and approximates training an ensemble of $2^N$ sub-networks.
  • Cosine Annealing with Warmup: Starts with small learning rate to avoid destabilizing randomly initialized weights, increases linearly over $W$ warmup steps, then decays following a cosine curve: $$\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\left(\frac{t}{T}\pi\right)\right)$$
  • Gradient Clipping: Rescales gradients if $\|\mathbf{g}\|_2 > \tau$ to prevent gradient explosions in recurrent models: $\mathbf{g} \leftarrow \tau \frac{\mathbf{g}}{\|\mathbf{g}\|_2}$.
Module 05

Computer Vision Architectures: CNNs & ResNets

Weeks 9–10 • Spatial Deep Learning

Why dense linear layers fail for images: A $1024 \times 1024 \times 3$ RGB image fed into a dense hidden layer of 1000 units requires over 3 billion parameters for a single layer! Convolutions solve this by exploiting two fundamental physical priors: Locality (pixels close to each other are correlated) and Translation Invariance (a cat is a cat whether it appears in top-left or bottom-right).

5.1 Mechanics of 2D Convolution & Pooling

A 2D convolutional layer slides a parameterized $K \times K$ kernel across an input feature map $X \in \mathbb{R}^{H \times W \times C_{\text{in}}}$, computing local dot products:

Feature Map Output Dimensions $$H_{\text{out}} = \left\lfloor \frac{H_{\text{in}} - K + 2P}{S} \right\rfloor + 1, \qquad W_{\text{out}} = \left\lfloor \frac{W_{\text{in}} - K + 2P}{S} \right\rfloor + 1$$
  • Kernel Size ($K$): Typically $3 \times 3$ or $1 \times 1$ (VGG proved stacking two $3 \times 3$ kernels has the same effective receptive field as one $5 \times 5$ kernel with $28\%$ fewer parameters and an extra non-linearity).
  • Padding ($P$): Adding border zeros. "Same" padding ($P = \frac{K-1}{2}$ for odd $K$) preserves spatial dimensions; "Valid" padding ($P=0$) shrinks them.
  • Stride ($S$): Step size across the grid. Stride 2 halves spatial resolution, acting as learnable pooling.
  • Pooling Layers: Max Pooling ($2 \times 2$, stride 2) extracts the most salient feature activation while discarding spatial translation noise. Modern networks frequently replace pooling with strided convolutions.

5.2 The ResNet Revolution & Skip Connections

Prior to 2015, stacking more layers beyond ~20 caused the Degradation Problem: both training and test error increased because gradients could not propagate backward through dozens of non-linearities.

Kaiming He et al. (CVPR 2016) introduced Deep Residual Learning (ResNet). Instead of forcing stacked layers to fit a desired mapping $\mathcal{H}(x)$, they explicitly let layers fit a residual mapping:

Residual Skip Connection Equation $$\mathcal{F}(x) := \mathcal{H}(x) - x \quad \implies \quad \mathcal{H}(x) = \mathcal{F}(x) + x$$

By adding an identity shortcut $+x$, the gradient during backprop expands to: $$\frac{\partial \mathcal{E}}{\partial x} = \frac{\partial \mathcal{E}}{\partial \mathcal{H}} \left( \frac{\partial \mathcal{F}}{\partial x} + 1 \right)$$ The $+1$ term forms a "gradient highway" that flows directly backward without vanishing, enabling the training of networks with 50, 101, and 152 layers!

Module 06

Sequence Modeling: Word2Vec to Self-Attention

Weeks 11–12 • Bridge to GenAI

Natural language is sequential, context-dependent, and discrete. Moving from static vector embeddings (Word2Vec) through Recurrent Neural Networks (LSTMs) leads directly to the core breakthrough that made modern Large Language Models possible: the Self-Attention mechanism.

6.1 Vector Embeddings & Subword Tokenization

Computers cannot process strings directly. Early NLP used One-Hot encodings, but vectors were sparse, high-dimensional ($|V| \approx 50,000$), and orthogonal (distance between "cat" and "kitten" was the same as "cat" and "airplane").

  • Word2Vec (Mikolov et al., 2013): Grounded in the Distributional Hypothesis ("You shall know a word by the company it keeps"). Skip-Gram predicts context given target word; Continuous Bag of Words (CBOW) predicts target word given context. Learns dense vector representations where linear algebraic relationships emerge: $\vec{v}_{\text{King}} - \vec{v}_{\text{Man}} + \vec{v}_{\text{Woman}} \approx \vec{v}_{\text{Queen}}$.
  • Byte-Pair Encoding (BPE) & SentencePiece: Instead of word-level or character-level vocabularies, modern tokenizers iteratively merge the most frequent byte pairs in a corpus. This solves Out-of-Vocabulary (OOV) words by decomposing unknown words into known subwords (e.g., "unbreakable" → ["un", "break", "able"]).

6.2 Recurrent Networks, LSTMs & The Sequential Bottleneck

Standard RNNs maintain an internal hidden state $h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t)$. However, computing gradients over long sequences involves repeated multiplication by $W_{hh}^T$, causing gradients to either explode or vanish exponentially to zero.

LSTM (Hochreiter & Schmidhuber, 1997) solved this by introducing an explicit constant error carousel: the Cell State ($C_t$) regulated by 3 gates:

  • Forget Gate: $f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f)$ (what percentage of past memory to discard).
  • Input Gate: $i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i)$ and candidate $\tilde{C}_t = \tanh(W_c \cdot [h_{t-1}, x_t] + b_c)$.
  • Output Gate: $o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + b_o)$ producing hidden state $h_t = o_t \odot \tanh(C_t)$.

The Fundamental Bottleneck: RNNs and LSTMs process text sequentially step-by-step ($t_1 \to t_2 \to t_3$). They cannot be parallelized across GPUs during training, and information still degrades over contexts longer than a few hundred tokens.

6.3 The Breakthrough: Scaled Dot-Product Self-Attention

In 2017, Vaswani et al. published "Attention Is All You Need". Instead of sequential recurrence, Self-Attention allows every token to directly inspect and attend to every other token in the sequence simultaneously, achieving $\mathcal{O}(1)$ path length between any two words and full GPU parallelization!

Given input sequence embedding matrix $X \in \mathbb{R}^{N \times d_{\text{model}}}$, we project it into three distinct matrices using learnable weights:

Query, Key, Value Projections $$Q = X W_Q, \quad K = X W_K, \quad V = X W_V \quad (W_Q, W_K \in \mathbb{R}^{d_{\text{model}} \times d_k}, \; W_V \in \mathbb{R}^{d_{\text{model}} \times d_v})$$

The attention weights represent how much attention token $i$ should pay to token $j$. The formulation scales the dot products by $\sqrt{d_k}$ so that large dimensionalities do not push the Softmax into flat regions with tiny gradients:

Scaled Dot-Product Attention Equation $$\text{Attention}(Q, K, V) = \text{softmax}\left( \frac{Q K^T}{\sqrt{d_k}} \right) V$$

This single mathematical equation is the universal architectural engine powering GPT-4, Claude, Gemini, Llama, and modern generative AI.

Module 07

Hands-On PyTorch Masterclass: Production Code

Executable Projects • Code From Scratch

Theory without code is incomplete. Below are two production-grade, self-contained implementations written in idiomatic PyTorch: a complete custom neural network with residual connections, and an end-to-end training and evaluation pipeline.

Project 1: Deep Residual ConvNet in Idiomatic PyTorch

resnet_classifier.py
import torch
import torch.nn as nn
import torch.nn.functional as F

class ResidualBlock(nn.Module):
    """
    Standard ResNet building block with 2 Conv layers and skip connection.
    Implements y = F(x) + x with Kaiming normal initialization.
    """
    def __init__(self, in_channels: int, out_channels: int, stride: int = 1):
        super().__init__()
        self.conv1 = nn.Conv2d(
            in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False
        )
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.conv2 = nn.Conv2d(
            out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False
        )
        self.bn2 = nn.BatchNorm2d(out_channels)

        # Shortcut projection if dimension changes
        self.shortcut = nn.Sequential()
        if stride != 1 or in_channels != out_channels:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(out_channels)
            )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        identity = self.shortcut(x)
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += identity  # Gradient highway
        return F.relu(out)

class MiniResNet(nn.Module):
    """Production ConvNet with Global Average Pooling for 10-class classification."""
    def __init__(self, num_classes: int = 10):
        super().__init__()
        self.stem = nn.Sequential(
            nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True)
        )
        self.layer1 = ResidualBlock(32, 64, stride=2)   # 32x32 -> 16x16
        self.layer2 = ResidualBlock(64, 128, stride=2)  # 16x16 -> 8x8
        self.layer3 = ResidualBlock(128, 256, stride=2) # 8x8 -> 4x4
        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        self.classifier = nn.Linear(256, num_classes)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.stem(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.avg_pool(x)
        x = torch.flatten(x, 1)
        return self.classifier(x)

# Verification test
if __name__ == "__main__":
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = MiniResNet(num_classes=10).to(device)
    dummy_input = torch.randn(4, 3, 32, 32).to(device)
    output = model(dummy_input)
    print(f"Model parameters: {sum(p.numel() for p in model.parameters()):,}")
    print(f"Output shape: {output.shape} -> Expected [4, 10]")

Project 2: Robust PyTorch Training Loop with AdamW & LR Warmup

train_pipeline.py
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset

def train_epoch(model, loader, criterion, optimizer, scaler, device):
    """Executes a single training epoch with mixed precision & gradient clipping."""
    model.train()
    total_loss, correct, total = 0.0, 0, 0

    for x, y in loader:
        x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
        optimizer.zero_grad(set_to_none=True) # More efficient than zero_grad()

        # Automatic Mixed Precision (AMP) for 2x faster GPU training
        with torch.amp.autocast(device_type="cuda" if torch.cuda.is_available() else "cpu"):
            logits = model(x)
            loss = criterion(logits, y)

        scaler.scale(loss).backward()
        
        # Unscale before clipping to prevent NaN overflow
        scaler.unscale_(optimizer)
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        
        scaler.step(optimizer)
        scaler.update()

        total_loss += loss.item() * x.size(0)
        preds = logits.argmax(dim=-1)
        correct += (preds == y).sum().item()
        total += y.size(0)

    return total_loss / total, correct / total

@torch.no_grad()
def evaluate(model, loader, criterion, device):
    """Evaluates the model on validation or test set."""
    model.eval()
    total_loss, correct, total = 0.0, 0, 0
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        logits = model(x)
        loss = criterion(logits, y)
        total_loss += loss.item() * x.size(0)
        correct += (logits.argmax(dim=-1) == y).sum().item()
        total += y.size(0)
    return total_loss / total, correct / total
Interactive Tools

In-Browser Deep Learning Simulators

Run Live in Browser

Test your conceptual understanding in real-time. Adjust sliders, select activation functions, modify convolution kernels, and inspect matrix mathematics computed directly in your browser.

1. Activation Function & Gradient Evaluator Interactive Calculator
Evaluating activation...
2. 2D Convolution Feature Extractor Simulator Vision Kernel Visualizer
Computing 2D convolution...
3. Scaled Dot-Product Self-Attention Calculator Transformer Engine
Current: 6.0
Computing attention weights...
Free Catalog

Top 100% Free Machine Learning & DL Resources

Zero Paywalls • Verified

You do not need to spend thousands of dollars on proprietary bootcamps. The world's greatest computer science universities and AI researchers have published world-class courses, books, and lecture series completely free to the public.

Stanford University

CS229: Machine Learning

Prof. Andrew Ng

The definitive university course on statistical learning theory, OLS, Logistic Regression, SVMs, and EM algorithm with full lecture notes and homework sets.

Access Free Course →
Stanford University

CS231n: Deep Learning for Computer Vision

Fei-Fei Li, Andrej Karpathy, Justin Johnson

Legendary course detailing CNNs, backprop derivations from scratch, optimization, Batch Normalization, and image classification.

Access Free Course →
Stanford University

CS224N: NLP with Deep Learning

Prof. Christopher Manning

The industry gold standard for NLP: Word2Vec embeddings, sequence-to-sequence LSTMs, attention mechanisms, and Transformer architectures.

Access Free Course →
YouTube Flagship

Neural Networks: Zero to Hero

Andrej Karpathy (Ex-Director of AI at Tesla / OpenAI)

Build micrograd (autograd from scratch), makemore, Bigram/MLP, WaveNet, and a full GPT decoder model line-by-line in pure Python and PyTorch.

Watch Video Series →
Interactive Free Book

Dive into Deep Learning (D2L.ai)

Aston Zhang, Zack Lipton, Mu Li, Alex Smola

An entire interactive multi-volume textbook with complete, executable PyTorch code for every single concept, model, and dataset.

Read Free Book →
MIT Press Book

Understanding Deep Learning

Simon J.D. Prince (2023)

Brand-new comprehensive textbook covering MLPs, CNNs, Transformers, Diffusion models, and Reinforcement Learning with stunning full-color geometric diagrams.

Download Free PDF →
MIT Press Classic

Deep Learning (The MIT Press)

Ian Goodfellow, Yoshua Bengio, Aaron Courville

The definitive foundational reference book cited across thousands of AI research papers. Fully readable online for free.

Read Online →
fast.ai

Practical Deep Learning for Coders

Jeremy Howard (fast.ai)

Top-down practical approach teaching how to train state-of-the-art vision, tabular, and NLP models in PyTorch within the first two hours.

Start fast.ai →
Study Tracks

Structured Study Schedules: Choose Your Track

Paced Learning

Whether you are an experienced software engineer looking to upskill rapidly or a student building deep mastery from scratch, choose the timeline that fits your weekly bandwidth.

Week 4-Week Fast Track (20+ hrs/wk) 8-Week Recommended Track (10–12 hrs/wk) 12-Week Zero-to-Mastery (6–8 hrs/wk)
Weeks 1–2 Modules 1 & 2: Data Leakage, Scikit-Learn Pipelines & XGBoost. Module 1: ML Problem Formulation, Cross-Validation, Bias-Variance. Module 1: Data Preprocessing, Imputation, Leakage Prevention.
Weeks 3–4 Modules 3 & 4: Neural Networks, Backpropagation & AdamW in PyTorch. Module 2: Ridge/Lasso, Decision Trees, Random Forests, XGBoost. Module 2: OLS, Logistic Regression, Feature Selection with Lasso.
Weeks 5–6 Modules 5 & 6: CNNs, ResNets, NLP Embeddings & Self-Attention. Module 3: Computational Graphs, Forward/Backprop, Activation Functions. Module 2 Part 2: Ensembles, Bagging vs Boosting, XGBoost tuning.
Weeks 7–8 Capstones: Train ResNet on GPU & Implement Self-Attention. Module 4: Optimizers (SGD, AdamW), LayerNorm, Cosine LR Schedulers. Module 3: Neural Networks from scratch, Backprop derivation.
Weeks 9–10 Ready for Stage 3 (LLMs, GenAI & RAG). Modules 5 & 6: CNNs, ResNets, and Word2Vec embeddings. Module 4: Training Dynamics, AdamW, Regularization & Dropout.
Weeks 11–12 — Modules 6 & 7: Self-Attention Mechanics & Full PyTorch Capstones. Modules 5, 6 & 7: ResNets, Attention & Kaggle Competition.
Self-Assessment

Stage 2 Concept Mastery Quiz

5 Concept Checks

Verify your mental models. Click an answer below to receive immediate diagnostic feedback and mathematical explanation.

1. Why does AdamW decouple weight decay instead of using standard L2 regularization?
A) Because weight decay is mathematically identical to L1 Lasso sparsity.
B) In standard Adam, L2 regularization is divided by the moving average of squared gradients, under-regularizing weights that receive frequent large updates.
C) Because AdamW does not use momentum, so it needs a separate decay parameter.
D) Decoupling weight decay increases GPU memory bandwidth by avoiding matrix inversion.
2. What primary architectural breakthrough allows 152-layer ResNets to train without suffering from vanishing gradients?
A) Replacing all convolutions with max pooling layers.
B) Setting learning rate to zero during the first 10 epochs.
C) Identity skip connections ($y = \mathcal{F}(x) + x$), which create a "+1" gradient highway allowing error signals to flow back directly.
D) Removing all non-linear activation functions from the network.
3. Why is Layer Normalization (LayerNorm) universally preferred over Batch Normalization (BatchNorm) in Transformers?
A) LayerNorm normalizes across feature dimensions independently for each sample, meaning it does not depend on batch size or suffer from sequence padding artifacts.
B) LayerNorm uses 4x fewer parameters than BatchNorm.
C) BatchNorm is illegal to use in autoregressive language models due to copyright.
D) LayerNorm requires zero floating-point operations.
4. In the Scaled Dot-Product Attention formula $\text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$, why do we divide by $\sqrt{d_k}$?
A) To convert the attention matrix into a binary mask.
B) For large $d_k$, dot products grow large in magnitude, pushing the Softmax into regions with vanishingly small gradients. Scaling by $1/\sqrt{d_k}$ preserves unit variance.
C) To satisfy Mercer's condition for support vector kernels.
D) To ensure that the Value matrix $V$ has zero mean.
5. Which evaluation metric should you prioritize when training a fraud detection model where only 0.05% of transactions are fraudulent?
A) Accuracy (percentage of total correct predictions).
B) Mean Squared Error (MSE).
C) Precision-Recall AUC (PR-AUC) or Recall at strict precision thresholds.
D) R-Squared ($R^2$).
Previous: Stage 1 (AI Foundations & Math) Stage 2 of 4 • Machine Learning & Deep Learning Next: Stage 3 (GenAI, LLMs & RAG) →