\( \newcommand{\vw}{\mathbf{w}} \newcommand{\vx}{\mathbf{x}} \newcommand{\vt}{\mathbf{t}} \newcommand{\vy}{\mathbf{y}} \newcommand{\vz}{\mathbf{z}} \newcommand{\vq}{\mathbf{q}} \newcommand{\vk}{\mathbf{k}} \newcommand{\vv}{\mathbf{v}} \newcommand{\vc}{\mathbf{c}} \newcommand{\vp}{\mathbf{p}} \newcommand{\vh}{\mathbf{h}} \newcommand{\vmu}{\boldsymbol{\mu}} \newcommand{\vsigma}{\boldsymbol{\sigma}} \newcommand{\vepsilon}{\boldsymbol{\epsilon}} \newcommand{\R}{\mathbb{R}} \newcommand{\E}{\mathbb{E}} \newcommand{\norm}[1]{\lVert #1 \rVert} \newcommand{\given}{\,\vert\,} \)

Lecture 8 — Regularization

Deep Learning · Session 8

Kasemsit Teeyapan

Department of Computer Engineering, Chiang Mai University

Today

  1. Regularization = injecting prior knowledge to control effective capacity
  2. Weight decay (L2) — and L1 sparsity
  3. Early stopping — read it off the validation curve
  4. Dropout & data augmentation
  5. Normalization and residual connections — make very deep nets trainable

Reference: Bishop & Bishop (2024), Chapter 9Regularization

Recap → why regularize

  • L4: high capacity → variance / overfitting
  • deep nets have more parameters than data
  • yet we want big models (they generalize well — if controlled)

Regularization = anything that reduces the gap \(R(f)-R_{\text{emp}}(f)\) without just shrinking the model:

  • a prior on weights, noise, invariances, ensembling…

We don’t make the model smaller — we constrain how it fits, so capacity is spent on signal, not noise

Part 1 · Inductive Bias

No free lunch — you must assume something

No free lunch theorem: averaged over all possible problems, every learner is equally (un)good. Generalization is only possible because real problems have structure.

Regularization = the assumptions we build in:

  • functions are smooth (small weights) → weight decay
  • predictions are invariant to small changes (shift, rotation) → augmentation, conv
  • simpler explanations are preferred → Occam’s razor (L4)

Every regularizer encodes a belief about the world — choosing it well is machine-learning expertise

Part 2 · Weight Decay

A two-point fit

One weight, no bias: predict \(t \approx w\,x\) from two points \((x,t)=(1,2)\) and \((2,2)\).

  • plain least squares minimizes \(E(w)=\tfrac12\sum_n (t_n-w x_n)^2\)
  • its solution is \(w^\star=\dfrac{\sum_n x_n t_n}{\sum_n x_n^2}=\dfrac{6}{5}=1.2\)

Now add a penalty \(\tfrac{\lambda}{2}w^2\) that dislikes large weights.

Before any algebra: when we switch on the penalty \(\lambda>0\), does the fitted \(w\) move toward 0, away from 0, or stay at 1.2? Why?

L2 = a Gaussian prior on weights

\[ \widetilde E(\vw) = E(\vw) + \frac{\lambda}{2}\,\norm{\vw}^2 \]

  • shrinks weights toward 0 → smoother functions
  • exactly the ridge / MAP view from Lecture 2 (\(\lambda=\alpha/\beta\))
  • \(\lambda\) trades fit vs simplicity — tune on validation
  • L1 (\(\lambda\sum|w_i|\)) instead → drives weights to exactly 0 (sparsity)

Source: Bishop & Bishop (2024), Deep Learning, Fig 9.3 — error contours (red) meet the regularizer

Where weight decay comes from (MAP)

Maximum a posteriori: maximize \(p(\vw\given\mathcal D)\propto p(\mathcal D\given\vw)\,p(\vw)\).

  • Gaussian prior \(p(\vw)=\mathcal N(0,\alpha^{-1}I)\propto e^{-\frac{\alpha}{2}\norm{\vw}^2}\)
  • Gaussian likelihood \(\propto e^{-\frac{\beta}{2}\sum_n (y_n-t_n)^2}\)

Take \(-\ln\) of the posterior:

\[-\ln p(\vw\given\mathcal D) = \tfrac{\beta}{2}\sum_n(y_n-t_n)^2 + \tfrac{\alpha}{2}\norm{\vw}^2 + \text{const}\]

\[\propto\; E(\vw) + \tfrac{\lambda}{2}\norm{\vw}^2,\quad \lambda=\tfrac{\alpha}{\beta}\]

Pillar: weight decay is MAP estimation with a Gaussian prior. A stronger belief that weights are small (larger \(\alpha\)) = larger \(\lambda\) = more shrinkage. The regularizer is a prior (L2).

Solving the two-point fit

Setting \(\dfrac{d}{dw}\!\left[E(w)+\tfrac{\lambda}{2}w^2\right]=0\) gives the ridge solution \[ w^\star=\frac{\sum_n x_n t_n}{\sum_n x_n^2 + \lambda}=\frac{6}{5+\lambda}. \]

With \(\sum x_n t_n = 6\) and \(\sum x_n^2 = 5\):

  • \(\lambda=0\)\(w^\star = 6/5 = \mathbf{1.2}\) (plain least squares)
  • \(\lambda=1\)\(w^\star = 6/6 = \mathbf{1.0}\)
  • \(\lambda=5\)\(w^\star = 6/10 = \mathbf{0.6}\)

The penalty adds to the denominator, so \(w^\star\) shrinks toward 0 — never past it. Did your prediction match?

Same two points, but crank the penalty to \(\lambda=7\). Compute \(w^\star\). How much of the unregularized \(1.2\) is left?

Part 3 · Early Stopping

Stop at the validation minimum

Training error keeps dropping; validation error turns back up when the model starts fitting noise.

We fit 15 Gaussian bumps to 15 noisy points by gradient descent for 700 epochs. Training MSE will fall the whole way. What does the validation MSE do — fall too, flatten, or fall-then-rise? Where would you stop?

import numpy as np, matplotlib.pyplot as plt
rng = np.random.default_rng(0)
xt = np.linspace(0, 1, 15); tt = np.sin(2*np.pi*xt) + 0.35*rng.standard_normal(15)
xv = np.linspace(0, 1, 200); tv = np.sin(2*np.pi*xv)             # clean held-out truth
mu = np.linspace(0, 1, 15); s = 0.12
feat = lambda x: np.exp(-0.5*((x[:, None]-mu)/s)**2)
P, Pv = feat(xt), feat(xv); w = np.zeros(15); tr, va = [], []
for _ in range(700):                                            # gradient descent
    w -= 0.01 * P.T @ (P @ w - tt) / len(xt)
    tr.append(np.mean((P@w-tt)**2)); va.append(np.mean((Pv@w-tv)**2))
best = int(np.argmin(va))
plt.figure(figsize=(5.5, 2.3))
plt.plot(tr, label="train"); plt.plot(va, label="validation")
plt.axvline(best, color="g", ls="--"); plt.text(best, va[best]*4, f" stop @ epoch {best}", color="g", fontsize=8)
plt.yscale("log"); plt.xlabel("epoch"); plt.ylabel("MSE"); plt.legend(fontsize=8); plt.tight_layout(); plt.show()

Train MSE → 0, but validation bottoms out then rises. Early stopping = keep the weights at that minimum.

Part 4 · Dropout & Augmentation

Dropout: train an ensemble for free

  • each step, keep each unit with prob \(p\) (drop it with prob \(1-p\))
  • every mini-batch trains a different thinned network
  • units can’t co-adapt → robust features
  • at test: keep all units, scale by \(p\) ≈ averaging the ensemble

A unit normally outputs \(a=4\). During training it is kept only \(p=\tfrac14\) of the time. At test time we leave it always on (output \(4\)). To keep the next layer seeing the same average input as during training, what should we multiply the test output by?

Dropout ≈ training & averaging exponentially many sub-networks — strong, cheap regularization

Source: Bishop & Bishop (2024), Deep Learning, Fig 9.17 · Srivastava, Hinton, Krizhevsky, Sutskever & Salakhutdinov (2014), JMLR

Why scale by \(p\) at test

During training a unit is on with prob \(p\), off otherwise, so the next layer sees it with expected value \[ \E[\text{output}] = p\cdot a + (1-p)\cdot 0 = p\,a. \]

Unit value \(a=4\), keep prob \(p=\tfrac14\).

  • Train (averaged over masks): \(\E[\text{output}] = \tfrac14 \cdot 4 = \mathbf{1}\)
  • Test, naively always on: output \(=4\)4× too big!
  • Fix: multiply by \(p\)\(4\times\tfrac14 = \mathbf{1}\) ✓ matches training

So the test-time scale factor is exactly \(p\). Did your prediction match?

A unit outputs \(a=5\) and is kept with prob \(p=0.4\). (a) What expected value does the next layer see during training? (b) What must we multiply the always-on test output by, and what value does it give?

Data augmentation encodes invariance

  • expand the data with label-preserving transforms (flip, crop, color, rotate)
  • teaches the model what to be invariant to
  • a free way to inject domain knowledge — often the single biggest win in vision

The cat is still a cat after a flip — augmentation builds that invariance into the training set.

Source: Bishop & Bishop (2024), Deep Learning, Fig 9.1

Part 5 · Making Deep Nets Trainable

Normalization stabilizes training

Normalize each layer’s activations to zero mean / unit variance (then rescale with learned \(\gamma,\beta\)):

  • Batch norm: normalize across the mini-batch — speeds up training, mild regularizer
  • Layer norm: normalize across features of one example — used in Transformers
  • keeps activations in a good range → larger learning rates, less sensitivity to init
  • reduces internal “moving target” between layers

Normalization is why we deferred it from Lecture 6 — it’s a practical lever for both optimization and regularization.

Bishop §7.4 (batch / layer normalization)

Normalizing a mini-batch

For activations \(\{a_1,\dots,a_N\}\): subtract the mean, divide by the std, then rescale: \[ \hat a_i = \frac{a_i-\mu}{\sigma},\qquad y_i = \gamma\,\hat a_i + \beta. \]

A batch of activations is \(\{3,3,7,7\}\). After subtracting the mean and dividing by the standard deviation, what is the mean and variance of the \(\hat a_i\)? (No calculator needed for the answer.)

Batch \(\{3,3,7,7\}\), with learned \(\gamma=2,\ \beta=1\):

  • mean \(\mu = \tfrac{3+3+7+7}{4}=5\)
  • variance \(\sigma^2 = \tfrac{(-2)^2+(-2)^2+2^2+2^2}{4}=4,\quad \sigma=2\)
  • normalized \(\hat a = \bigl[\tfrac{3-5}{2},\dots\bigr]=[-1,-1,1,1]\) → mean \(0\), var \(1\)
  • rescaled \(y=\gamma\hat a+\beta = [-1,-1,3,3]\)

Batch \(\{2,2,8,8\}\) with \(\gamma=4,\ \beta=2\). Find \(\mu,\sigma\), the normalized \(\hat a\), and the output \(y\).

Residual connections fix vanishing gradients

\[ \mathbf z = \vx + F(\vx) \]

  • a layer learns a residual, not the whole map
  • the skip path lets gradients flow straight back → no vanishing (L7!)
  • enables networks hundreds of layers deep (ResNet)

The simplest fix to L7’s vanishing-gradient problem — and the reason modern nets can be so deep

Source: Bishop & Bishop (2024), Deep Learning, Fig 9.13 · He et al., ResNet (2016)

How the skip path saves the gradient

Backprop multiplies one local factor per layer (L7). Say every layer scales the gradient by 0.5.

Through a plain 10-layer stack, the gradient reaching layer 1 is multiplied by \(0.5\) ten times. A residual block is \(z=x+F(x)\), so its local factor is \(1+F'\) instead of just \(F'\). Which gradient survives — and roughly how big is each?

Plain: factor \(= 0.5^{10} = 0.00098\) — the gradient is ~1000× smaller at layer 1 → it vanishes.

Residual: the skip adds 1 to each factor, so each layer multiplies by \(1+0.5=1.5\): \[ 1.5^{10} \approx 57. \] Even ignoring \(F\), the skip alone gives a factor of \(1^{10}=1\) — the gradient can’t vanish. That’s why ResNets train at hundreds of layers.

Make the stack 20 layers deep, same \(0.5\) per layer. (a) Plain factor \(0.5^{20}=?\) (order of magnitude). (b) What is the skip-path-only factor? Which network is still trainable?

Summary

  1. Regularization = inject prior knowledge to spend capacity on signal, not noise (no free lunch)
  2. Weight decay (= L2 / Gaussian prior, L2 lecture); L1 → sparsity
  3. Early stopping (validation minimum); dropout (ensemble); augmentation (invariance)
  4. Normalization + residual connections make very deep nets trainable (residuals fix vanishing gradients)

Something to think about: “inverted dropout” skips the test-time scaling and instead divides by \(p\) during training. Show this leaves the test network unchanged — and explain why frameworks prefer it. (Hint: compare the expected input to the next layer in both schemes.)

📌 Read before next class

Bishop & Bishop (2024), Chapter 10Convolutional Networks

Our first specialized architecture: parameter sharing and convolution bake image invariances right into the network.

Figures from Bishop & Bishop, Deep Learning: Foundations and Concepts (2024), Chapter 9 — https://www.bishopbook.com/

⌂ Home