4.1 · The artificial neuron
A neuron computes a weighted sum of inputs, adds a bias, and squashes through a non-linearity:
$a = \sigma\!\left(\sum_{i=1}^{n} w_i x_i + b\right)$
The whole field of deep learning is: stack these, train the weights.
4.2 · The Multi-Layer Perceptron (MLP)
Stack neurons in layers; each layer is a matrix multiply + activation:
$\mathbf{h}^{(\ell)} = \sigma\!\left(\mathbf{W}^{(\ell)} \mathbf{h}^{(\ell-1)} + \mathbf{b}^{(\ell)}\right)$
Universal approximation theorem: a single hidden layer with enough neurons can approximate any continuous function. In practice depth works better than width — fewer parameters per quality unit.
4.3 · Activation functions — what each one actually does
Why we need them. A stack of linear layers without activations collapses algebraically to a single linear layer. Activations introduce the bends the network needs to model curves, edges, language — anything non-trivial.
The four most-used activations, drawn
Sigmoid — $\sigma(z) = \dfrac{1}{1+e^{-z}}$
What it does: squashes any real number into $(0, 1)$.
Example: binary-classification output, e.g. "spam vs not spam" probability.
Watch out: saturates for large $|z|$ → tiny gradients ("vanishing gradient").
Tanh — $\tanh(z)$
What it does: like sigmoid but centred at 0, range $(-1, 1)$.
Example: classic RNN hidden states; smoother than sigmoid for symmetric data.
ReLU — $\max(0, z)$
What it does: kills negatives, keeps positives as-is.
Example: the default hidden activation since 2012 — every ResNet, every CNN layer.
Watch out: "dying ReLU" — neurons stuck at 0 forever. Fix: Leaky ReLU, $\max(0.01z, z)$.
GELU — $z \cdot \Phi(z)$
What it does: a smooth, probabilistic version of ReLU.
Example: the activation inside every transformer block of BERT and GPT.
SwiGLU — $\text{Swish}(xW) \odot xV$
What it does: a gated activation; one branch decides "how much" of the other to let through.
Example: feed-forward layers of LLaMA, modern open LLMs.
Softmax — $p_i = \dfrac{e^{z_i}}{\sum_j e^{z_j}}$
What it does: turns a vector of scores into a probability distribution that sums to 1.
Example: final layer of any multi-class classifier; attention weights; LLM next-token distribution.
4.4 · Loss functions
| Task | Loss |
|---|---|
| Regression | MSE: $\frac{1}{n}\sum(y - \hat{y})^2$ |
| Binary classification | Binary cross-entropy: $-y\log\hat{p} - (1-y)\log(1-\hat{p})$ |
| Multi-class | Categorical cross-entropy |
| Embeddings / metric learning | Contrastive / triplet loss |
| LLM pre-training | Next-token cross-entropy |
4.5 · The forward pass — worked example
# 2 → 3 → 1 network on a single sample
x = [1.0, 2.0] # input
W1 = [[0.1, 0.2],
[-0.1, 0.3],
[0.4, -0.5]] # shape (3, 2)
b1 = [0.0, 0.0, 0.1]
z1 = [W1[i][0]*x[0] + W1[i][1]*x[1] + b1[i] for i in range(3)]
h1 = [max(0, v) for v in z1] # ReLU
# final layer (3 → 1) ... weighted sum → sigmoid → prediction
4.6 · Backpropagation — the chain rule, organised
Given loss $\mathcal{L}$ and weight $w$ deep in the network, backprop computes $\partial \mathcal{L}/\partial w$ by chaining derivatives layer-by-layer from output back to input.
For a single hidden neuron with output $a = \sigma(z)$, $z = w \cdot x + b$:
$\dfrac{\partial \mathcal{L}}{\partial w} = \underbrace{\dfrac{\partial \mathcal{L}}{\partial a}}_{\text{from above}} \cdot \underbrace{\sigma'(z)}_{\text{local}} \cdot \underbrace{x}_{\text{input}}$
Modern libraries (PyTorch, JAX, TensorFlow) implement autograd: you write the forward pass; the framework builds a computation graph and back-propagates automatically.
4.7 · Optimizers — what each one really does
Every optimizer answers the same question: given the gradient, how big a step should I take and in what direction?
SGD (Stochastic Gradient Descent)
Rule: $w \leftarrow w - \eta \nabla \mathcal{L}$.
Intuition: walk downhill, one mini-batch at a time. Pure and simple.
Example: training a ResNet on ImageNet, often with momentum + cosine schedule.
SGD + Momentum
Rule: $v \leftarrow \beta v + \nabla \mathcal{L};\; w \leftarrow w - \eta v$.
Intuition: a ball rolling down a valley keeps moving past flat spots — fewer oscillations, faster convergence.
RMSProp
What it adds: divides the learning rate by a moving average of recent gradient magnitudes, so each parameter gets its own effective step size.
Example: RNN training, where some parameters get rare but huge gradients.
Adam / AdamW
What it adds: Momentum (first moment) + RMSProp (second moment) + bias correction. AdamW decouples weight decay correctly.
Example: the default optimizer for nearly every transformer trained since 2018.
Lion
What it adds: uses only the sign of the moving-average gradient — half Adam's memory, often matches it.
Example: large-scale pretraining where saving GPU memory matters.
Learning-rate schedules
- Warmup: ramp from 0 → $\eta$ over the first few hundred steps (avoids instability).
- Cosine decay: gradually anneal $\eta$ toward zero. Standard for LLM pretraining.
- One-cycle: small → big → small. Pop-classic for vision fine-tunes.
4.8 · Regularization that actually helps
- Dropout — randomly zero a fraction (e.g. 0.1) of activations each step.
- Weight decay — L2 penalty on weights, baked into AdamW.
- Label smoothing — soften one-hot targets to prevent over-confidence.
- Early stopping — track validation loss; stop when it stops improving.
- Data augmentation — cheap data multiplier (flips, crops, paraphrases).
4.9 · Initialization & normalization — small details, huge impact
| Trick | Why |
|---|---|
| Xavier / Glorot init | Keeps variance stable across layers for tanh/sigmoid. |
| Kaiming / He init | Tuned for ReLU. |
| BatchNorm | Normalizes activations across the batch. Smoother training in vision. |
| LayerNorm | Normalizes across features per sample. Standard in transformers. |
| RMSNorm | Lighter LayerNorm variant used in LLaMA. |
| Residual connections | $y = x + f(x)$. Lets gradients flow through deep networks. |
4.10 · Evaluating a neural network
A neural network is just a function. We evaluate it like any other ML model — but with two extras to watch: the loss curves (which expose under/overfitting visually) and the head-specific metrics (classification head ≠ regression head ≠ embedding head).
The four loss-curve shapes you must recognise
Train / validation / test — the three splits
| Split | Used for | Touched how often? |
|---|---|---|
| Train (~70–80%) | Update weights via backprop. | Every batch. |
| Validation (~10–15%) | Tune hyperparameters, early stopping, model selection. | Once per epoch. |
| Test (~10–15%) | Final, unbiased estimate of generalisation. | Exactly once, at the very end. |
K-fold cross-validation is the small-data alternative: split into $K$ folds and rotate validation through each, averaging scores.
Metrics by head — match the metric to the output
| Metric | What it tells you |
|---|---|
| Accuracy, Top-1 / Top-5 | Fraction correct; for many-class problems, allow the true label to be in top-k predictions. |
| Cross-entropy (val loss) | Same loss used for training; track per-epoch. |
| Precision / Recall / F1 / ROC-AUC / PR-AUC | Full classification suite from Ch 3. Macro-average for multi-class. |
| Calibration / ECE | Are predicted probabilities trustworthy? Reliability diagram. |
| Confusion matrix | Diagnose which classes the model confuses. |
| Metric | What it tells you |
|---|---|
| MAE, MSE, RMSE | Average error magnitude. |
| R² / Adjusted R² | Variance explained. |
| MAPE / SMAPE | Percentage error for cross-scale comparison. |
| Quantile / Pinball loss | For prediction-interval models. |
| Metric | What it tells you |
|---|---|
| Hamming loss | Fraction of wrong labels across all classes per sample. |
| Subset accuracy (exact match) | 1 only if every label is correct — strict. |
| Label-wise Precision / Recall / F1 | Compute per label, average (macro / micro / weighted). |
| mAP (mean Average Precision) | Mean of per-label AP — standard for object detection. |
| Metric | What it tells you |
|---|---|
| Cosine similarity / distance | Geometric quality of learned embeddings. |
| Recall@k / MRR | Does the right neighbour appear in the top-k of an anchor? |
| Triplet / contrastive loss | Training loss that doubles as quality proxy on held-out triplets. |
| Alignment / Uniformity | Wang & Isola (2020) diagnostics for contrastive learning. |
4.11 · A training-loop checklist
- Start with a tiny model on a tiny subset — confirm it can overfit a few batches. If not, the loss or shape is wrong.
- Sanity-check input/output ranges; normalize inputs to roughly zero mean and unit variance.
- Print or log: loss, gradient norm, parameter norm — every step at first.
- Use a learning-rate finder to bracket a reasonable range.
- Hold out a validation set; monitor it; early stop.
- Fix all seeds you care about; document them.
- Save checkpoints often. Resume-friendly code earns you weeks of life back.