TExcelTAD

Deep Learning: Introduction

A logistic regression draws one straight boundary. A gradient-boosted forest carves the feature space into boxes. Both work on features someone chose. Deep learning stacks many simple differentiable layers and trains all of them together, so the model learns its own features: edges and strokes from pixels, word meanings from text, the role of a node from its neighbours in a graph. The price is that you have to understand the machinery: how a gradient reaches the first layer, why a network with the wrong initial weights never trains, how a convolution or an attention layer arranges its parameters, and how to run all of it in a framework without silent bugs.

This course builds that machinery twice. First in NumPy, where you write every forward and backward pass yourself and end with a small autograd engine. Then in PyTorch, where the same models take a few lines and you can check that the framework computes exactly what your code did. With those two in hand, each architecture (MLP, CNN, RNN, LSTM, transformer, ViT, autoencoder, VAE, GAN, diffusion, GNN) is a new arrangement of parts you already know.

The map

networks from scratchNumPy, a small autograd PyTorch essentialstensors to DDP making deep nets traininit, norms, residuals architectures: each one a NumPy core that runs here, then PyTorch MLP, embeddingstables, categories CNNimages, local patterns RNN, LSTM, GRUsequences, a state transformer, ViTtokens that look at tokens AE, VAE, GAN, diffusiongenerating data GNNnodes and edges choosing an architecture then: exercises and a mini project (MLP vs CNN vs ViT on digits)
Section What you build Labs
Neural networks from scratch neurons and layers, activations, output heads, backprop as layer modules, an autograd engine for arrays, an MLP trained with it decision-boundary
PyTorch essentials tensors, devices, autograd, nn.Module, custom layers and hooks, Dataset/DataLoader, a reusable training loop, checkpoints and seeds, memory, mixed precision and DDP, debugging early-stopping, gradient-descent
Making deep networks train initialisation, vanishing and exploding gradients, batch and layer normalisation, dropout, residual connections, each measured on a real network
MLPs and embeddings MLPs on tables compared honestly with boosting; embedding layers
Convolutional networks convolution in NumPy (loops and im2col), pooling, receptive fields, a CNN trained in NumPy and PyTorch, LeNet to ResNet convolution
Recurrent networks an RNN with backpropagation through time, LSTM and GRU matched to PyTorch, padding, packing and teacher forcing
Attention and transformers attention, a transformer block, a tiny character language model, a vision transformer attention-heatmap, lr-schedule
Generative models autoencoders, VAEs, GANs, diffusion (the noising process, then training and sampling)
Graph neural networks message passing and a GCN for node classification

One network, written twice

Here is the course in miniature. A network with one hidden layer of 32 ReLU units classifies the 8 ×\times 8 handwritten digits that ship with scikit-learn (1797 images, 10 classes). The forward pass is two matrix products; the backward pass, written by hand, sends the error back through the same two products. Training is mini-batch SGD for 30 epochs. Every choice is watched on a validation set, and the test set is used once at the end.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = X / 16.0                                            # 8 x 8 pixels in [0, 1]
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)

rng = np.random.default_rng(0)
W1 = rng.normal(0, np.sqrt(2 / 64), (64, 32)); b1 = np.zeros(32)    # He initialisation
W2 = rng.normal(0, np.sqrt(1 / 32), (32, 10)); b2 = np.zeros(10)

def forward(X):
    A = X @ W1 + b1
    H = np.maximum(A, 0)                                # ReLU
    Z = H @ W2 + b2                                     # logits
    Z = Z - Z.max(axis=1, keepdims=True)
    P = np.exp(Z) / np.exp(Z).sum(axis=1, keepdims=True)   # softmax
    return A, H, P

def loss_acc(X, y):
    P = forward(X)[2]
    return -np.mean(np.log(P[np.arange(len(y)), y])), np.mean(P.argmax(axis=1) == y)

lr = 0.2
for epoch in range(1, 31):
    order = rng.permutation(len(y_tr))
    for s in range(0, len(order), 32):
        idx = order[s:s + 32]
        xb, yb = X_tr[idx], y_tr[idx]
        A, H, P = forward(xb)
        dZ = P.copy(); dZ[np.arange(len(yb)), yb] -= 1; dZ /= len(yb)   # softmax + cross-entropy
        dH = dZ @ W2.T
        dA = dH * (A > 0)                               # ReLU passes gradient where it was active
        W2 -= lr * H.T @ dZ;  b2 -= lr * dZ.sum(axis=0)
        W1 -= lr * xb.T @ dA; b1 -= lr * dA.sum(axis=0)
    if epoch in (1, 5, 10, 30):
        tl, ta = loss_acc(X_tr, y_tr); vl, va = loss_acc(X_va, y_va)
        print(f"epoch {epoch:2d}  train loss {tl:.3f} acc {ta:.3f}   val loss {vl:.3f} acc {va:.3f}")
print("parameters:", W1.size + b1.size + W2.size + b2.size)
print("test accuracy, measured once:", round(float(loss_acc(X_te, y_te)[1]), 3))
epoch  1  train loss 1.211 acc 0.787   val loss 1.215 acc 0.811
epoch  5  train loss 0.254 acc 0.939   val loss 0.290 acc 0.917
epoch 10  train loss 0.135 acc 0.965   val loss 0.178 acc 0.956
epoch 30  train loss 0.044 acc 0.996   val loss 0.140 acc 0.969
parameters: 2410
test accuracy, measured once: 0.961

The split is 1077 training, 360 validation and 360 test images, and it is the same in every Digits example of the course, so numbers from different lessons can be compared. After 30 epochs the network gets 99.6 % of the training images and 96.9 % of the validation images right, and 96.1 % of the test images. The gap between a training loss of 0.044 and a validation loss of 0.140 is the first sign of overfitting, the subject of dropout and other regularisers.

Now the same network in PyTorch. Only the forward pass is written; loss.backward() replaces the four lines of hand-written gradients.

python · try it yourself
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

torch.manual_seed(0)
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
t = lambda a, dt=torch.float32: torch.tensor(a, dtype=dt)
X_tr, X_va, X_te = t(X_tr), t(X_va), t(X_te)
y_tr, y_va, y_te = t(y_tr, torch.long), t(y_va, torch.long), t(y_te, torch.long)

model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))   # the same 2410 parameters
loss_fn = nn.CrossEntropyLoss()                                           # softmax + cross-entropy on logits
opt = torch.optim.SGD(model.parameters(), lr=0.2)
loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=32, shuffle=True)

@torch.no_grad()
def loss_acc(X, y):
    model.eval()
    logits = model(X)
    return loss_fn(logits, y).item(), (logits.argmax(1) == y).float().mean().item()

for epoch in range(1, 31):
    model.train()
    for xb, yb in loader:
        loss = loss_fn(model(xb), yb)
        opt.zero_grad()
        loss.backward()                                 # autograd writes the backward pass
        opt.step()
    if epoch in (1, 5, 10, 30):
        tl, ta = loss_acc(X_tr, y_tr); vl, va = loss_acc(X_va, y_va)
        print(f"epoch {epoch:2d}  train loss {tl:.3f} acc {ta:.3f}   val loss {vl:.3f} acc {va:.3f}")
print("parameters:", sum(p.numel() for p in model.parameters()))
print("test accuracy, measured once:", round(loss_acc(X_te, y_te)[1], 3))
epoch  1  train loss 1.857 acc 0.666   val loss 1.870 acc 0.675
epoch  5  train loss 0.282 acc 0.938   val loss 0.306 acc 0.931
epoch 10  train loss 0.153 acc 0.961   val loss 0.186 acc 0.958
epoch 30  train loss 0.058 acc 0.988   val loss 0.150 acc 0.961
parameters: 2410
test accuracy, measured once: 0.958

The two runs agree in what matters (about 96 % on validation and test) but not digit for digit: PyTorch draws its initial weights from its own uniform distribution, smaller than the He-scaled normal of the NumPy version, so it starts slower (validation accuracy 0.675 after one epoch instead of 0.811), and it shuffles with its own generator. When the start and the batch order are matched, the numbers agree to many decimals; Training an MLP with Your Autograd shows it. Each part of the program is a topic of the course:

What you should know first

The course follows Training Mechanics, Evaluation & Model Improvement: the training loop (in NumPy and in PyTorch), losses, the optimizers from SGD to AdamW, learning-rate schedules, early stopping, gradient clipping, mixed precision, metrics and validation. Those are used here and linked, not taught again. Distributed training, transfer learning and fine-tuning are in Training Strategies (DDP and checkpointing, transfer learning). The mathematics (the chain rule on graphs, why Xavier and He scale as they do, the gradients of convolution, attention and LSTM gates) is derived in Math for Deep Learning & LLMs; each lesson links to the exact page, for example backpropagation for an MLP and a tiny scalar autodiff engine.

After this course, Computer Vision applies CNNs and ViTs to detection and segmentation, and NLP, Transformers & LLM Fine-Tuning scales the transformer up to language models.

How examples run here

Every NumPy example runs in your browser (Python in WebAssembly with NumPy, SciPy, scikit-learn, NetworkX and Matplotlib), with fixed seeds and rounded printing, so the output you get is the output shown, and you can edit and rerun it. Examples that import PyTorch cannot run in a browser: they are marked Recorded and show the output of a real run on a CPU (PyTorch 2.14.1, 4 threads, no GPU). Because every idea is first written in NumPy, nothing in the course depends only on a recorded output. The data comes from generators and from the small data sets bundled with scikit-learn and NetworkX, so nothing is downloaded while you learn; the models are tiny on purpose, and each example takes seconds. Real projects use the same code with larger data, larger models and a GPU.

Test yourself

The network maps 64 inputs to 32 hidden units and then to 10 outputs, with a bias on each unit. How many parameters does it have?

  1. 106
  2. 2368
  3. 2410
  4. 4096

In the NumPy version, what does the line dA = dH * (A > 0) do?

  1. Applies the ReLU in the forward pass
  2. Passes the gradient back through the ReLU: unchanged where the unit was active, zero where it was not
  3. Normalises the gradient
  4. Drops half of the units at random

Why do the NumPy and PyTorch runs give different numbers after the first epoch?

  1. PyTorch computes gradients incorrectly
  2. They start from different random weights (and PyTorch's default initialisation is different) and shuffle the batches differently
  3. PyTorch uses a different loss
  4. The NumPy version has fewer parameters

Which set is used to compare epochs and settings in this course, and which is used once at the end?

  1. Test for choices, validation once
  2. Validation for choices, test once at the end
  3. Training for both
  4. Test for both