CS6910 · Deep Learning · IIT Madras

Regularization: from bias and variance to dropout

Deep networks have more parameters than training points, so they can drive the training error to zero and still do badly on new data. This lecture shows that the training error underestimates the true error by a term that grows with model complexity, then studies the methods that keep that term in check: L2 weight decay, data augmentation, parameter sharing, noise at the inputs and outputs, early stopping, ensembles and dropout.

Lecture 6 Instructor Prof. Mitesh M. Khapra About 197 min of video 12 modules

At a glance

  • Deep networks are over-parameterized and overfit easily. Over repeated training samples, a simple model has high bias \(E[\hat f(x)] - f(x)\) and low variance; a complex model has the reverse. The expected test error is \(\text{bias}^2 + \text{variance} + \sigma^2\).
  • The error on held-out data equals the true error up to the constant \(\sigma^2\). The training error misses a term \(2E[\varepsilon(\hat f - f)]\), which by Stein's lemma is \(\frac{2\sigma^2}{n}\sum_i \partial\hat f(x_i)/\partial y_i\): large for models that are sensitive to their data. So minimize \(\mathscr L_{train}(\theta) + \Omega(\theta)\).
  • L2 adds \(\alpha\mathbf w\) to the gradient. Near the optimum, \(\tilde{\mathbf w} = Q(\Lambda + \alpha I)^{-1}\Lambda Q^\top\mathbf w^*\): each eigen-direction of the Hessian is scaled by \(\lambda_i/(\lambda_i + \alpha)\), so flat directions shrink the most.
  • Early stopping (patience \(p\), return the model from step \(k - p\)) gives \(\mathbf w_t = Q[I - (I - \eta\Lambda)^t]Q^\top\mathbf w^*\), the same shape as L2. Gaussian input noise on a linear model adds \(\sigma^2\sum_i w_i^2\) to the loss. Soft targets replace 1 and 0 by \(1 - \varepsilon\) and \(\varepsilon/9\).
  • Averaging \(k\) models gives \(\text{mse} = \frac1kV + \frac{k-1}{k}C\), which helps unless their errors are perfectly correlated. Dropout trains \(2^n\) weight-sharing thinned networks (keep \(p = 0.5\) for hidden units, 0.8 for inputs) and scales weights by \(p\) at test time.
  • Augmentation, parameter sharing and tying, and an explicit/implicit taxonomy complete the list. Random-label experiments suggest regularizers alone do not explain why deep networks generalize.

Until now (Lecture 5) the focus was on minimizing the objective quickly and reliably. The new problem is what a well-minimized objective can hide. Deep learning models often have far more parameters than the training data has samples; the slide's picture is billions of parameters against millions of samples. Such over-parameterized models are prone to overfitting: they can drive the training error to zero on the points they were given and still predict badly on points they have not seen. To understand why, the lecture looks at the bias and variance of a model as its capacity changes.

The curve-fitting experiment

The data points were drawn from a sinusoid, so for once the true relation \(f(x)\) is known. We pretend not to know it and fit two models to the 500 training points:

\[ \text{Simple (degree 1):}\quad y = \hat f(x) = w_1x + w_0 \qquad\qquad \text{Complex (degree 25):}\quad y = \hat f(x) = \sum_{i=1}^{25} w_ix^i + w_0 \]

The simple model has 2 parameters and the complex one 26, so the complex one has much more capacity. Both make an assumption about how \(y\) depends on \(x\), and neither knows the true \(f\). Each is trained by minimizing the squared error \(\sum_i (y_i - \hat f(x_i))^2\) with gradient descent. The experiment is repeated \(k\) times, each time on a different random sample of the training data (in the video, about 400 of the 500 points, 30 times). Each repetition gives one line and one degree-25 curve.

The plots show two things 13:21.

  • Simple models trained on different samples barely differ from each other, but all of them are far from the sinusoid. They underfit: even their training error is large.
  • Complex models trained on different samples are very different from each other, but on average they follow the sinusoid, and many of them reach close to zero training error.

Definitions

The randomness comes from which sample of the training data a model happened to see. Averaging the 30 fitted curves at each \(x\) estimates \(E[\hat f(x)]\), the expected (average) model. On the slide the green line is this average for the simple model, the blue curve the average for the complex model, and the red curve the true \(f\).

\[ \text{Bias}\big(\hat f(x)\big) = E\big[\hat f(x)\big] - f(x), \qquad \text{Variance}\big(\hat f(x)\big) = E\Big[\big(\hat f(x) - E[\hat f(x)]\big)^2\Big] \]

Bias measures how far the average model is from the truth. Variance is the standard statistical variance of the random variable \(\hat f(x)\): roughly, how much models trained on different samples differ from each other. The simple model's average line is far from the sinusoid, so its bias is high; the complex model's average is close, so its bias is low. The simple lines all hug their average (low variance), while some complex curves sit far from theirs (high variance).

ModelBiasVarianceTypical failure
Simple (degree 1)HighLowUnderfits: wrong even on the training data
Complex (degree 25)LowHighOverfits: depends heavily on the sample it saw

There is always a trade-off between the two 24:32. High variance is bad because the model you end up with depends on the training sample you happened to get, so a test point that resembles a different sample can be predicted badly. Low variance is no use if it comes with high bias, because then all the models agree with each other and are all far from the truth. The aim is a moderate amount of each. Both contribute to the mean squared error, as the next module shows.

1
Bias² (avg over x)–
Variance (avg over x)–
Train MSE–
Test MSE–
Synthetic: 30 fits from 30 training samples. A pool of 500 points from \(y = \sin 2\pi x + \varepsilon\) with \(\sigma = 0.3\), generated for these notes. Each fit sees 20 points of the pool (one from each twentieth of the \(x\)-range), fewer than the lecture's 400 so that variance shows up at modest degrees. Top: the 30 fits (grey), their average, which estimates \(E[\hat f(x)]\) (violet), and the true \(f\) (dashed). Bottom: bias², variance, training MSE and test MSE (on 300 fresh points) at every degree for the same samples, on a log scale. Training error only falls; test error falls and then rises, and it stays close to bias² + variance + σ².

Test error = bias² + variance + σ²

Take a new point \((x, y)\) that was not seen during training. If \(\hat f\) predicts \(y\), its mean squared error is \(E[(y - \hat f(x))^2]\), the average squared error over many such unseen points (think of every image uploaded after an image classifier was trained). It can be shown to split into three parts.

Bias–variance decomposition \[ E\big[(y - \hat f(x))^2\big] = \text{Bias}^2 + \text{Variance} + \sigma^2 \]

\(\sigma^2\) is the irreducible error, the variance of the noise in \(y\) itself. No model can remove it.

The slide links to a proof elsewhere. Not in the lecture, but short: write \(y = f + \varepsilon\) with \(E[\varepsilon] = 0\), \(E[\varepsilon^2] = \sigma^2\), and let \(\bar f = E[\hat f(x)]\). For an unseen point the noise \(\varepsilon\) is independent of \(\hat f\), and \(f - \bar f\) is a constant, so in each expansion the cross term has expectation zero:

\[ E\big[(f + \varepsilon - \hat f)^2\big] = E\big[(f - \hat f)^2\big] + \sigma^2, \qquad E\big[(f - \bar f + \bar f - \hat f)^2\big] = \underbrace{(\bar f - f)^2}_{\text{Bias}^2} + \underbrace{E\big[(\hat f - \bar f)^2\big]}_{\text{Variance}} \]

So the error on unseen data depends on both bias and variance. A high-bias model like the line has a high test error; so does a high-variance model like the degree-25 polynomial. For the test error to be small both must be small, and the experiment showed that they pull against each other. The minimum sits somewhere in the middle, at medium bias and medium variance.

Training error and test error M2 · 7:42

The parameters of \(\hat f\) (all the \(w_i\)) are estimated from a training set of \(n\) points. What we care about is performance on a validation (unseen) set of \(m\) points that was not used for training. That gives two quantities:

\[ \text{train}_{err} = \frac1n\sum_{i=1}^{n}\big(y_i - \hat f(x_i)\big)^2, \qquad \text{test}_{err} = \frac1m\sum_{i=n+1}^{n+m}\big(y_i - \hat f(x_i)\big)^2 \]

Typically, as model complexity grows the training error keeps falling toward zero, while the test error falls at first and then rises. The left end of the curve is the high-bias region: the simple line is bad even on its own training data. The right end is the high-variance region: fits that are excellent on their own sample and poor on new points. Between them lies the sweet spot, the ideal model complexity. The lower panel of the interactive figure above shows this shape on synthetic data.

As model complexity increases, the training error becomes overly optimistic. The validation error gives the real picture of how close \(\hat f\) is to \(f\).

The next two modules make this intuition precise and show how to account for the optimism in the training error.

Let \(D = \{x_i, y_i\}_{i=1}^{m+n}\). Some true function relates \(y\) to \(x\), with noise:

\[ y = f(x) + \varepsilon, \qquad \varepsilon \sim \mathcal N(0, \sigma^2) \]

We do not know \(f\). We approximate it by \(\hat f\), estimate its parameters from a training set \(T \subset D\), and predict \(\hat y = \hat f(x)\). The quantity we want is the true error \(E[(\hat f(x) - f(x))^2]\), but it contains the unknown \(f\), so it cannot be computed directly. What we do have are observations \(y_i\) and predictions \(\hat y_i\). Rewrite their squared difference using \(y = f(x) + \varepsilon\), and expand it as \((a - b)^2\) with \(a = \hat f(x) - f(x)\) and \(b = \varepsilon\):

\[ \begin{aligned} E\big[(\hat y - y)^2\big] &= E\big[(\hat f(x) - f(x) - \varepsilon)^2\big] \\ &= E\big[(\hat f(x) - f(x))^2 - 2\varepsilon(\hat f(x) - f(x)) + \varepsilon^2\big] \\ &= E\big[(\hat f(x) - f(x))^2\big] - 2E\big[\varepsilon(\hat f(x) - f(x))\big] + E[\varepsilon^2] \end{aligned} \]
\[ \therefore\quad E\big[(\hat f(x) - f(x))^2\big] = E\big[(\hat y - y)^2\big] - E[\varepsilon^2] + 2E\big[\varepsilon(\hat f(x) - f(x))\big] \]

The quantity we want is now written with three terms. The first can be estimated from data, the second is \(\sigma^2\), and the third still contains \(f\) and needs an argument.

Detour: estimating an expectation M3 · 6:13

Suppose a team scored \(z_1 = 2\), \(z_2 = 1\), \(z_3 = 0\), …, \(z_k = 2\) goals in \(k\) matches. The empirical estimate of the expected number of goals is the average, \(E[z] \approx \frac1k\sum_{i=1}^k z_i\). In the same way, from \(m\) observations and predictions,

\[ E\big[(\hat y - y)^2\big] \approx \frac1m\sum_{i=1}^{m}(\hat y_i - y_i)^2 \]

The right-hand side of the true-error equation can be evaluated with test observations or with training observations, and the two behave very differently.

Case 1: test observations

\[ \underbrace{E\big[(\hat f(x) - f(x))^2\big]}_{\text{true error}} = \underbrace{\frac1m\sum_{i=n+1}^{n+m}(\hat y_i - y_i)^2}_{\text{empirical estimate of error}} - \underbrace{\sigma^2}_{\text{small constant}} + \underbrace{2E\big[\varepsilon(\hat f(x) - f(x))\big]}_{=\ 2\,\text{covariance}(\varepsilon,\ \hat f(x) - f(x))} \]

The last expectation is a covariance because \(\varepsilon\) has mean zero 11:17. For any \(X\) with \(\mu_X = E[X] = 0\):

\[ \text{cov}(X, Y) = E[(X - \mu_X)(Y - \mu_Y)] = E[X(Y - \mu_Y)] = E[XY] - E[X\mu_Y] = E[XY] - \mu_YE[X] = E[XY] \]

None of the test observations took part in estimating \(\hat f\); its parameters came from the training data only 14:23. So at a test point, \(\varepsilon = y - f(x)\) is independent of \(\hat f(x) - f(x)\), and the expectation of the product splits into a product of expectations:

\[ E\big[\varepsilon\,(\hat f(x) - f(x))\big] = E[\varepsilon]\cdot E\big[\hat f(x) - f(x)\big] = 0\cdot E\big[\hat f(x) - f(x)\big] = 0 \]
Case 1 result

True error = empirical test error − σ². Up to a small constant, the error measured on held-out data is the true error. So always estimate a model's error on a validation set that is independent of the training set.

Case 2: training observations

\[ \underbrace{E\big[(\hat f(x) - f(x))^2\big]}_{\text{true error}} = \underbrace{\frac1n\sum_{i=1}^{n}(\hat y_i - y_i)^2}_{\text{empirical train error}} - \underbrace{\sigma^2}_{\text{small constant}} + 2E\big[\varepsilon(\hat f(x) - f(x))\big] \]

Now the argument fails. The training observations were used to estimate the parameters of \(\hat f\), so \(y - f(x)\) is not independent of \(\hat f(x) - f(x)\). The expectation no longer splits into \(E[\varepsilon]\cdot E[\hat f(x) - f(x)]\), and the covariance term is not zero. Reporting the training error alone leaves this term out, so the empirical training error is smaller than the true error and gives a false picture of it. How does this term depend on model complexity?

The extra term measures sensitivity, which grows with complexity

Estimate the troublesome expectation empirically over the \(n\) training points. Using Stein's lemma (and, as the slide says, some trickery) one can show

\[ \frac1n\sum_{i=1}^{n}\varepsilon_i\big(\hat f(x_i) - f(x_i)\big) = \frac{\sigma^2}{n}\sum_{i=1}^{n}\frac{\partial\hat f(x_i)}{\partial y_i} \]

The lecture takes the lemma on trust, and so can we. When is \(\partial\hat f(x_i)/\partial y_i\) high? When a small change in one observation causes a large change in the estimate. Say \(x_i = 10\) and \(y_i\) changes from 20 to 20.1: ideally the fitted parameters should barely move. A complex model is more sensitive to such changes than a simple one, which is what the 30 repeated fits already showed. Linking the two:

True error and model complexity \[ \text{true error} = \text{empirical train error} + \text{small constant} + \Omega(\text{model complexity}) \]

The more complex the model, the further its training error lies from its true error. A training error near zero means little until this term is accounted for.

The slides then check the claim directly: fit a simple and a complex model to some data, change one data point, and refit. The simple model hardly changes compared with the complex one.

Simple: degree 1 (2 parameters) Complex: degree 9 (10 parameters) 0 2 −2 prediction at the moved point rises 0.07 · ∂f̂/∂y ≈ 0.09 prediction at the moved point rises 0.59 · ∂f̂/∂y ≈ 0.74 fit before fit after the hollow point moves up by 0.8 (to the filled one)
One point moved, two models refitted. Synthetic data generated for these notes: 12 noisy points from a sinusoid. The line hardly notices the change. The degree-9 polynomial bends to follow the moved point, and its shape also changes near \(x = 0\), far from the change. That is a large \(\partial\hat f(x_i)/\partial y_i\).

Not in the lecture: for a least-squares fit the predictions are linear in the observations, \(\hat{\mathbf y} = S\mathbf y\) with \(S = X(X^\top X)^{-1}X^\top\). Then \(\partial\hat f(x_i)/\partial y_i = S_{ii}\) (the 0.09 and 0.74 above), and \(\sum_i\partial\hat f(x_i)/\partial y_i = \operatorname{tr}(S)\) equals the number of parameters: 2 for the line, 10 for the degree-9 polynomial. In this simple case the complexity term literally counts parameters.

Driving \(\mathscr L_{train}(\theta)\) to zero can raise the complexity term so much that the true error goes up. So while training, instead of the training error alone, minimize

\[ \min_{\text{w.r.t. }\theta}\ \mathscr L_{train}(\theta) + \Omega(\theta) = \mathscr L(\theta) \]

where \(\Omega(\theta)\) is high for complex models and small for simple ones. \(\Omega\) acts as an approximation of \(\frac{\sigma^2}{n}\sum_i\partial\hat f(x_i)/\partial y_i\), which cannot be handled directly. If minimizing \(\Omega\) reduces model complexity, it also reduces the term that made the training error optimistic.

This is the basis for all regularization methods. L1 regularization, L2 regularization, early stopping and injecting noise at the input can all be shown to be instances of it.

model complexity error high bias (underfitting) high variance (overfitting) sweet spot true error training error Ω(model complexity)
Where Ω sits. Illustrative curves. As complexity grows, the training error falls toward zero while the true (test) error falls and then rises. The gap between them is the complexity term, and it widens with complexity. \(\Omega(\theta)\) should keep the model at a reasonable complexity, near the sweet spot.

Why deep learning needs this

Deep neural networks are highly complex models, with many parameters and many non-linearities. By the representation-power results of Lecture 3, adding layers or neurons lets a network get arbitrarily close to its training data. So it is easy for a deep network to overfit and drive the training error to 0, and some form of regularization is needed. The lecture covers these forms:

  1. \(l_2\) regularization
  2. Dataset augmentation
  3. Parameter sharing and tying
  4. Adding noise to the inputs
  5. Adding noise to the outputs
  6. Early stopping
  7. Ensemble methods
  8. Dropout

For \(l_2\) regularization the regularizer is the squared norm of the weights:

\[ \tilde{\mathscr L}(\mathbf w) = \mathscr L(\mathbf w) + \frac{\alpha}{2}\lVert\mathbf w\rVert^2 \]

\(\alpha\) decides how much weight the penalty gets in the total loss. With \(\alpha = 0\) there is no regularization and we are back to the unregularized loss.

Why does a penalty on the size of the weights control model complexity? Without it, any point of weight space is open to the optimizer. With it, moving far from the origin makes \(\lVert\mathbf w\rVert^2\), and so the total loss, large. You may add as many parameters as you like, a million or a billion, but none of them is given the freedom to take very large values. The model keeps its capacity but cannot use all of it.

For SGD and its variants we need the gradient. The derivative of \(\frac\alpha2\mathbf w^\top\mathbf w\) is \(\alpha\mathbf w\), so

\[ \nabla\tilde{\mathscr L}(\mathbf w) = \nabla\mathscr L(\mathbf w) + \alpha\mathbf w, \qquad \mathbf w_{t+1} = \mathbf w_t - \eta\nabla\mathscr L(\mathbf w_t) - \eta\alpha\mathbf w_t \]

This requires a very small modification to gradient descent code: subtract one extra term. (The lecture notes that the change is more involved for optimizers like Adam, and does not go into it.) Grouping the \(\mathbf w_t\) terms gives \(\mathbf w_{t+1} = (1 - \eta\alpha)\mathbf w_t - \eta\nabla\mathscr L(\mathbf w_t)\): every step first shrinks the weights by a constant factor, which is why the L2 penalty is also called weight decay.

Let \(\mathbf w^*\) be the optimal solution of \(\mathscr L(\mathbf w)\), the loss without regularization (not of \(\tilde{\mathscr L}\)). Because it is optimal, \(\nabla\mathscr L(\mathbf w^*) = \mathbf 0\). For a point near it write \(\mathbf u = \mathbf w - \mathbf w^*\) and use the Taylor series up to second order 10:01 (gradient descent in Lecture 3 used only the first-order term). \(H\) is the Hessian, the matrix of second-order partial derivatives:

\[ \begin{aligned} \mathscr L(\mathbf w^* + \mathbf u) &= \mathscr L(\mathbf w^*) + \mathbf u^\top\nabla\mathscr L(\mathbf w^*) + \tfrac12\mathbf u^\top H\mathbf u \\ \mathscr L(\mathbf w) &= \mathscr L(\mathbf w^*) + (\mathbf w - \mathbf w^*)^\top\nabla\mathscr L(\mathbf w^*) + \tfrac12(\mathbf w - \mathbf w^*)^\top H(\mathbf w - \mathbf w^*) \\ &= \mathscr L(\mathbf w^*) + \tfrac12(\mathbf w - \mathbf w^*)^\top H(\mathbf w - \mathbf w^*) && (\because \nabla\mathscr L(\mathbf w^*) = \mathbf 0) \\ \nabla\mathscr L(\mathbf w) &= \nabla\mathscr L(\mathbf w^*) + H(\mathbf w - \mathbf w^*) = H(\mathbf w - \mathbf w^*) \end{aligned} \]

Adding the gradient of the penalty, \(\nabla\tilde{\mathscr L}(\mathbf w) = \nabla\mathscr L(\mathbf w) + \alpha\mathbf w\), which here is \(H(\mathbf w - \mathbf w^*) + \alpha\mathbf w\). Let \(\tilde{\mathbf w}\) be the optimal solution of the regularized loss. Its gradient is zero:

\[ H(\tilde{\mathbf w} - \mathbf w^*) + \alpha\tilde{\mathbf w} = \mathbf 0 \;\;\therefore\;\; (H + \alpha I)\tilde{\mathbf w} = H\mathbf w^* \;\;\therefore\;\; \tilde{\mathbf w} = (H + \alpha I)^{-1}H\mathbf w^* \]

\(H\) is symmetric positive semi-definite, so for \(\alpha > 0\) the matrix \(H + \alpha I\) is positive definite and the inverse exists. If \(\alpha \to 0\) then \(\tilde{\mathbf w} \to \mathbf w^*\), as it should with no regularization. The case of interest is \(\alpha \ne 0\).

Since \(H\) is symmetric PSD, it has an eigendecomposition \(H = Q\Lambda Q^\top\) with \(Q\) orthogonal (\(QQ^\top = Q^\top Q = I\)) and the eigenvalues \(\lambda_i \ge 0\) on the diagonal of \(\Lambda\). Substitute it, write \(\alpha I = Q(\alpha I)Q^\top\), and use the rule \((ABC)^{-1} = C^{-1}B^{-1}A^{-1}\):

\[ \begin{aligned} \tilde{\mathbf w} &= (Q\Lambda Q^\top + \alpha I)^{-1}Q\Lambda Q^\top\mathbf w^* = (Q\Lambda Q^\top + \alpha QIQ^\top)^{-1}Q\Lambda Q^\top\mathbf w^* \\ &= \big[Q(\Lambda + \alpha I)Q^\top\big]^{-1}Q\Lambda Q^\top\mathbf w^* = (Q^\top)^{-1}(\Lambda + \alpha I)^{-1}Q^{-1}\,Q\Lambda Q^\top\mathbf w^* \\ &= Q(\Lambda + \alpha I)^{-1}\Lambda Q^\top\mathbf w^* && (\because (Q^\top)^{-1} = Q,\ Q^{-1}Q = I) \end{aligned} \]
L2-regularized optimum \[ \tilde{\mathbf w} = QDQ^\top\mathbf w^*, \qquad D = (\Lambda + \alpha I)^{-1}\Lambda = \begin{bmatrix} \frac{\lambda_1}{\lambda_1 + \alpha} & & \\ & \ddots & \\ & & \frac{\lambda_n}{\lambda_n + \alpha} \end{bmatrix} \]

\(D\) is diagonal: \(\Lambda + \alpha I\) has \(\lambda_i + \alpha\) on its diagonal, its inverse has \(1/(\lambda_i + \alpha)\), and multiplying by \(\Lambda\) multiplies each entry by \(\lambda_i\).

Read the product from right to left 21:57:

  1. \(Q^\top\) rotates \(\mathbf w^*\) into the eigenbasis of \(H\), giving \(Q^\top\mathbf w^*\).
  2. \(D\) scales element \(i\) of \(Q^\top\mathbf w^*\) by \(\lambda_i/(\lambda_i + \alpha)\).
  3. \(Q\) rotates the result back.

If \(\alpha = 0\), \(D = I\) and \(Q\) simply rotates \(Q^\top\mathbf w^*\) back to \(\mathbf w^*\). If \(\alpha \ne 0\) 27:29:

  • if \(\lambda_i \gg \alpha\), then \(\frac{\lambda_i}{\lambda_i + \alpha} \approx 1\) and that component is kept;
  • if \(\lambda_i \ll \alpha\), then \(\frac{\lambda_i}{\lambda_i + \alpha} \approx 0\) and that component is driven toward zero.

Only the significant directions, those with larger eigenvalues, are retained. Counting each direction by the fraction of it that survives gives the effective number of parameters 30:16:

\[ \text{effective parameters} = \sum_{i=1}^{n}\frac{\lambda_i}{\lambda_i + \alpha} \lt n \]

The network still has \(n\) parameters, but because many are scaled down, fewer of them are fully effective. That is how L2 regularization reduces model complexity.

The picture: all weights shrink, some more than others

Draw the contours of the unregularized loss \(\mathscr L(\mathbf w)\), ellipses around \(\mathbf w^*\), and the contours of the penalty \(\lVert\mathbf w\rVert^2\), circles around the origin. The regularized optimum \(\tilde{\mathbf w}\) lies where the two families touch: a compromise between a small loss and small weights.

w₁ w₂ 1 2 3 2 1.5 1 w₁: 3 → 1 w₂: 2 → 1.5 w* w̃ Shrink factor λᵢ / (λᵢ + α), α = 2 w₁ direction: flat, λ₁ = 1 1 / (1 + 2) = 1/3, so 3 becomes 1 w₂ direction: steep, λ₂ = 6 6 / (6 + 2) = 3/4, so 2 becomes 1.5 contours of 𝓛(w) contours of ‖w‖² w̃ as α goes from 0 to ∞ effective parameters: 1/3 + 3/4 ≈ 1.08 of 2
L2 regularization, drawn to scale. Values chosen for illustration: \(H = \operatorname{diag}(1, 6)\), so \(Q = I\) and the eigen-directions are the axes; \(\mathbf w^* = (3, 2)\); \(\alpha = 2\). The factors \(\lambda_i/(\lambda_i + \alpha)\) are \(1/3\) and \(3/4\), so \(\tilde{\mathbf w} = (1, 1.5)\): the flat direction \(w_1\) loses two thirds of its value, the steep direction \(w_2\) only a quarter. At \(\tilde{\mathbf w}\) a loss ellipse touches the circle \(\lVert\mathbf w\rVert \approx 1.80\). The dotted curve traces \(\tilde{\mathbf w}\) for every \(\alpha\), from \(\mathbf w^*\) at \(\alpha = 0\) to the origin as \(\alpha \to \infty\).

Two things happen as \(\mathbf w^*\) moves to \(\tilde{\mathbf w}\). First, the weights shrink. Second, they do not shrink uniformly: each shrinks by its own factor, set by the eigenvalues. Along \(w_1\) the loss contours are far apart, so the loss changes slowly in that direction; shrinking \(w_1\) costs little loss, so it is shrunk a lot. Along \(w_2\) the contours are close together, so even a small shrink raises the loss quickly, and \(w_2\) is shrunk only a little. The spacing of the contours is the curvature, which the Hessian's eigenvalues measure. Directions in which the loss is sensitive count as important and keep most of their weight; the others are suppressed. This ensures that only important features are given high weights.

Dataset augmentation

This method changes the data instead of the loss. Take an MNIST training image of the digit 2. Some transformations of the image do not change its label, so each of them yields a new labelled training example at no labelling cost. The slide's examples: the image rotated by 20° or by 65°, shifted vertically, shifted horizontally, blurred, or with some pixels changed. Every one of them still has label 2.

The augmented data is created using knowledge of the task: we know these transformations leave the label alone. Not every transformation is safe for every class; rotating a 6 by 180° gives a 9.

Why it regularizes: the network must now map many variants of the same digit to the same label, so memorizing one particular combination of pixels no longer works. There is more to learn, and overfitting becomes harder, although modern networks can still overfit. Typically, more data means better learning.

  • Works well for image classification and object recognition, and has also been shown to work well for speech.
  • For some tasks it is not clear how to generate such data. The lecturer's example is text: words are discrete, unlike the continuous signals of images and speech, so meaningful augmentations are harder to design, although libraries for it now exist.

Parameter sharing and tying

Parameter sharing is used in convolutional neural networks (Lecture 8). A convolutional filter is a small matrix of weights, and the same filter is applied at different positions of the image instead of a separate matrix for each part. Put another way, the same weight matrix acts on different input neurons.

Parameter tying is typically used in autoencoders, which map an input \(\mathbf x \in \mathbb R^n\) to a code \(\mathbf h(\mathbf x) \in \mathbb R^d\) and then to a reconstruction \(\hat{\mathbf x} \in \mathbb R^n\) (autoencoders come up again in Lecture 7). The encoder needs a \(d \times n\) weight matrix and the decoder an \(n \times d\) one. Tying the encoder and decoder weights means the decoder uses the transpose of the encoder's matrix, so one matrix does both jobs. The lecturer adds that some transformer-based models (Lecture 14) similarly reuse one set of weights across layers.

In both cases the regularization effect is plain: fewer separate weights means a smaller model, and a smaller model has lower complexity.

Parameter sharing (CNN) K K input 6 × 6 output 4 × 4 the same 9 weights of K compute every output cell Parameter tying (autoencoder) W Wᵀ x ∈ ℝⁿ h(x) ∈ ℝᵈ x̂ ∈ ℝⁿ decoder reuses Wᵀ: one matrix instead of two
Fewer separate weights. Left: one 3 × 3 filter \(K\) slides over a 6 × 6 input, and every cell of the 4 × 4 output is computed with the same 9 weights (two positions shown). Right: an autoencoder with tied weights, where the decoder uses \(W^\top\), the transpose of the encoder's \(W\), instead of a second matrix.

Pass each input through a noise process \(P(\tilde{\mathbf x} \mid \mathbf x)\) and train the network to map the corrupted \(\tilde{\mathbf x}\) to the original target. (The slide draws this on an autoencoder, where the same idea appears.) For binary inputs, a simple noise process keeps each bit with probability 0.8 and flips it with probability 0.2, so about 20% of every input is corrupted. Each epoch sees a different corruption of the same example, and all of them must be mapped to the same \(y\). Memorizing the inputs becomes harder, much as with augmentation, and the slide notes it can be viewed as data augmentation.

For a simple input–output network, with no hidden layer and no non-linearity, adding Gaussian noise to the input can be shown to be equivalent to weight decay. Let the model be \(\hat y = \sum_{i=1}^{n}w_ix_i\) and corrupt each input independently 4:38:

\[ \tilde x_i = x_i + \varepsilon_i,\quad \varepsilon_i \sim \mathcal N(0, \sigma^2), \qquad \tilde y = \sum_{i=1}^{n}w_i\tilde x_i = \sum_{i=1}^{n}w_ix_i + \sum_{i=1}^{n}w_i\varepsilon_i = \hat y + \sum_{i=1}^{n}w_i\varepsilon_i \]

We are interested in the expected squared error of the noisy prediction \(\tilde y\) against the true target \(y\). Group it as \((\hat y - y) + \sum_i w_i\varepsilon_i\) and expand the square:

\[ \begin{aligned} E\big[(\tilde y - y)^2\big] &= E\Big[\Big(\hat y + \sum_{i=1}^{n}w_i\varepsilon_i - y\Big)^2\Big] = E\Big[\Big((\hat y - y) + \sum_{i=1}^{n}w_i\varepsilon_i\Big)^2\Big] \\ &= E\big[(\hat y - y)^2\big] + E\Big[2(\hat y - y)\sum_{i=1}^{n}w_i\varepsilon_i\Big] + E\Big[\Big(\sum_{i=1}^{n}w_i\varepsilon_i\Big)^2\Big] \\ &= E\big[(\hat y - y)^2\big] + 0 + E\Big[\sum_{i=1}^{n}w_i^2\varepsilon_i^2\Big] \\ &= E\big[(\hat y - y)^2\big] + \sigma^2\sum_{i=1}^{n}w_i^2 \end{aligned} \]

Two independence facts remove terms. The noise is independent of the clean error \(\hat y - y\) and has mean zero, so the middle term vanishes. Expanding \((\sum_i w_i\varepsilon_i)^2\) gives squares \(w_i^2\varepsilon_i^2\) and cross terms \(w_iw_j\varepsilon_i\varepsilon_j\); since \(\varepsilon_i\) is independent of \(\varepsilon_j\), each cross term has expectation \(w_iw_jE[\varepsilon_i]E[\varepsilon_j] = 0\). Finally \(E[\varepsilon_i^2] = \sigma^2\).

Input noise = weight decay (linear model)

Training on noisy inputs minimizes \(\mathscr L(\theta) + \Omega(\theta)\) with \(\Omega(\theta) = \sigma^2\sum_i w_i^2\), the same as the L2 norm penalty (\(\alpha = 2\sigma^2\) in the form \(\frac\alpha2\lVert\mathbf w\rVert^2\)) 11:26. More noise means stronger weight decay.

Noise can also go into the targets. In 10-class digit classification, the true distribution for an image of a 2 puts all its mass on class 2: \(\mathbf p = (0, 0, 1, 0, 0, 0, 0, 0, 0, 0)\). These are hard targets. Training minimizes the cross-entropy between \(\mathbf p\) and the estimated distribution \(\mathbf q\) (Lecture 4), \(-\sum_{i=0}^{9}p_i\log q_i\); the slide writes the sum without its minus sign. With many parameters this loss can be driven to zero, mapping each input exactly to its label, which is what overfitting is.

The intuition: do not trust the true labels, as they may be noisy. Take a small probability mass \(\varepsilon\) (a small positive constant) away from the correct class and share it equally among the other nine. These are soft targets:

\[ \mathbf p = \Big(\frac{\varepsilon}{9},\ \frac{\varepsilon}{9},\ 1 - \varepsilon,\ \frac{\varepsilon}{9},\ \dots,\ \frac{\varepsilon}{9}\Big) \]
Class0123…9
Hard target0010…0
Soft target, \(\varepsilon = 0.1\)0.0110.0110.90.011…0.011

With hard targets only one term of the sum survives, the one with \(p_i = 1\). With soft targets every class contributes, and the loss becomes a weighted version of the original loss plus an extra term (\(\varepsilon = 0.1\) above is only an example value):

\[ -\sum_{i=0}^{9}p_i\log q_i = (1 - \varepsilon)\underbrace{\big(-\log q_2\big)}_{\mathscr L(\theta)} + \varepsilon\underbrace{\Big(-\frac19\sum_{i \ne 2}\log q_i\Big)}_{\Omega(\theta)} \]

The outputs have been corrupted a little, the majority of the mass is still on the correct label, and the objective again has the form loss plus regularizer, which helps avoid overfitting. Standard name: label smoothing.

Put training steps on the \(x\)-axis instead of model complexity and the familiar picture returns. The longer training runs, the more the parameters adapt to the training data: the training error heads toward zero, while the validation error falls, bottoms out and starts to rise. The goal is the sweet spot where both are low.

  1. Early stopping with patience p
  2. Train as usual and track the validation error.
  3. Fix a patience parameter \(p\), counted in steps or epochs.
  4. If at step \(k\) there was no improvement in validation error in the previous \(p\) steps, stop training.
  5. Return the model stored at step \(k - p\).

In short, stop training before it drives the training error to 0 and blows up the validation error.

training steps error k − p: return this model k: stop p = 20 steps no new best validation error training error 43 63
Early stopping with patience \(p = 20\). Illustrative curves. The validation error is lowest at step 43. Steps 44 to 63 bring no improvement, so at \(k = 63\) training stops and the model saved at \(k - p = 43\) is returned, even though the training error was still falling.

Early stopping is very effective and the most widely used form of regularization. It needs no change to the loss function, it is easy to automate, and it can be used together with other regularizers such as \(l_2\). How does it act as a regularizer? First an intuition, then a mathematical analysis.

Intuition: a limited number of steps limits how far the weights travel M9 · 5:09

Unroll the SGD update \(\mathbf w_{t+1} = \mathbf w_t - \eta\nabla\mathbf w_t\) (writing \(\nabla\mathbf w_t\) for the gradient at step \(t\)) back to the initial weights:

\[ \mathbf w_t = \mathbf w_0 - \eta\sum_{i=0}^{t-1}\nabla\mathbf w_i \]

Let \(\tau\) be the largest of these gradients. The sum has \(t\) terms, each no larger than \(\tau\), so

\[ \lvert\mathbf w_t - \mathbf w_0\rvert \le \eta\,t\,\lvert\tau\rvert \]

The number of steps \(t\) controls how far \(\mathbf w_t\) can go from the initial \(\mathbf w_0\); in other words, it controls the space of exploration 8:44. Stopping early caps that distance, much as the circles of the L2 penalty cap how far the weights may grow.

Use the same second-order Taylor approximation around the unregularized optimum \(\mathbf w^*\) as in the L2 analysis, which gave \(\nabla\mathscr L(\mathbf w) = H(\mathbf w - \mathbf w^*)\). The SGD update rule then becomes

\[ \mathbf w_t = \mathbf w_{t-1} - \eta\nabla\mathscr L(\mathbf w_{t-1}) = \mathbf w_{t-1} - \eta H(\mathbf w_{t-1} - \mathbf w^*) = (I - \eta H)\mathbf w_{t-1} + \eta H\mathbf w^* \]

Substitute the eigendecomposition \(H = Q\Lambda Q^\top\):

\[ \mathbf w_t = (I - \eta Q\Lambda Q^\top)\mathbf w_{t-1} + \eta Q\Lambda Q^\top\mathbf w^* \]

If we start with \(\mathbf w_0 = \mathbf 0\), this recursion has a closed form (proof below; the slides write \(\varepsilon\) for the learning rate here):

\[ \mathbf w_t = Q\big[I - (I - \eta\Lambda)^t\big]Q^\top\mathbf w^* \]

Compare it with the L2 optimum. Since

\[ (\Lambda + \alpha I)^{-1}\Lambda = (\Lambda + \alpha I)^{-1}(\Lambda + \alpha I - \alpha I) = I - (\Lambda + \alpha I)^{-1}\alpha, \]

the L2 solution can be written in the same shape:

\[ \tilde{\mathbf w} = Q\big[I - (\Lambda + \alpha I)^{-1}\alpha\big]Q^\top\mathbf w^* \]
Early stopping ≈ L2

Both have the form \(Q\,(\text{diagonal})\,Q^\top\mathbf w^*\). They coincide, \(\mathbf w_t = \tilde{\mathbf w}\), if \(\eta\), \(t\) and \(\alpha\) are chosen so that

\[ (I - \eta\Lambda)^t = (\Lambda + \alpha I)^{-1}\alpha, \quad\text{that is,}\quad (1 - \eta\lambda_i)^t = \frac{\alpha}{\lambda_i + \alpha}\ \text{ for each } i \]

Not in the lecture: matching every eigen-direction exactly is a strong condition. The standard reading (Deep Learning book, §7.8) is an approximate equivalence. Taking logs, \(t\log(1 - \eta\lambda_i) \approx -t\eta\lambda_i\) and \(\log\frac{\alpha}{\lambda_i + \alpha} \approx -\lambda_i/\alpha\) when \(\eta\lambda_i\) and \(\lambda_i/\alpha\) are small, so \(\alpha \approx 1/(\eta t)\). Training for longer is like using weaker L2.

w₁ w₂ 1 2 3 2 1 t = 2 t = 4 t = 10 t = 20 α = 8 α = 2 α = 0.5 w* gradient descent from w₀ = 0 with η = 0.1 wₜ = (3(1 − 0.9ᵗ), 2(1 − 0.4ᵗ)) L2 optimum w̃(α) w̃ = (3/(1 + α), 12/(6 + α)) stop at t = 4: (1.03, 1.95) use α = 2: (1, 1.5) both leave 0 along Hw* = (3, 12), reach the steep w₂ first and the flat w₁ last
Two routes to a shrunken solution, drawn to scale. The loss of the L2 figure: \(H = \operatorname{diag}(1, 6)\), \(\mathbf w^* = (3, 2)\). Violet: gradient descent from \(\mathbf w_0 = \mathbf 0\) with \(\eta = 0.1\), one dot per step, so stopping after \(t\) steps means taking the \(t\)-th dot. Dotted: the L2 optimum \(\tilde{\mathbf w}\) for every \(\alpha\). Both shrink the flat direction \(w_1\) much more than the steep \(w_2\): stopping at \(t = 4\) keeps 34% of \(w^*_1\) and 97% of \(w^*_2\), while \(\alpha = 2\) keeps 33% and 75%. No choice of \(t\) and \(\alpha\) makes the two curves meet exactly here, because the matching condition cannot hold for both eigenvalues at once.

Proof of the closed form (the slides' appendix)

By induction on \(t\), starting from \(\mathbf w_0 = \mathbf 0\). Base case, \(t = 1\): the recursion (first line) and the closed form (second line) agree.

\[ \begin{aligned} \mathbf w_1 &= (I - \eta Q\Lambda Q^\top)\mathbf w_0 + \eta Q\Lambda Q^\top\mathbf w^* = \eta Q\Lambda Q^\top\mathbf w^* \\ \mathbf w_1 &= Q\big[I - (I - \eta\Lambda)^1\big]Q^\top\mathbf w^* = \eta Q\Lambda Q^\top\mathbf w^* \end{aligned} \]

Induction step. Assume the closed form holds at step \(t\), substitute it into the recursion for step \(t + 1\), open the bracket, and use \(Q^\top Q = I\):

\[ \begin{aligned} \mathbf w_{t+1} &= (I - \eta Q\Lambda Q^\top)\,Q\big[I - (I - \eta\Lambda)^t\big]Q^\top\mathbf w^* + \eta Q\Lambda Q^\top\mathbf w^* \\ &= Q\big[I - (I - \eta\Lambda)^t\big]Q^\top\mathbf w^* - \eta Q\Lambda Q^\top Q\big[I - (I - \eta\Lambda)^t\big]Q^\top\mathbf w^* + \eta Q\Lambda Q^\top\mathbf w^* \\ &= Q\Big[\big(I - (I - \eta\Lambda)^t\big) - \eta\Lambda\big(I - (I - \eta\Lambda)^t\big) + \eta\Lambda\Big]Q^\top\mathbf w^* \\ &= Q\big[I - (I - \eta\Lambda)^t + \eta\Lambda(I - \eta\Lambda)^t\big]Q^\top\mathbf w^* \\ &= Q\big[I - (I - \eta\Lambda)^t(I - \eta\Lambda)\big]Q^\top\mathbf w^* = Q\big[I - (I - \eta\Lambda)^{t+1}\big]Q^\top\mathbf w^* \end{aligned} \]

Things to remember

Early stopping only allows \(t\) updates to the parameters. If a parameter \(w\) belongs to a direction that is important for the loss \(\mathscr L(\theta)\), then \(\partial\mathscr L(\theta)/\partial w\) is large and the parameter can grow a lot within \(t\) steps. If it is not important, \(\partial\mathscr L(\theta)/\partial w\) is small, its updates are small, and it cannot grow large in \(t\) steps. Early stopping therefore effectively shrinks the parameters of the less important directions, the same thing weight decay does.

An ensemble combines the outputs of different models to reduce generalization error, for example by voting, or by averaging the class distributions the models predict. The models can correspond to:

  • different classifiers trained on the same data (the slide's example: logistic regression, an SVM and naive Bayes);
  • different instances of the same classifier trained with different hyperparameters (say, networks with different numbers of layers or neurons per layer);
  • instances trained with different features (each on a different subset of \(m \lt n\) of the \(n\) input features);
  • instances trained on different samples of the training data.

Bagging is an ensemble of different instances of the same classifier. From the given dataset, construct training sets \(T_1, T_2, \dots, T_k\) by sampling with replacement: each sample is drawn from the full dataset, and the points taken for one set are put back before drawing the next. Train the \(i\)-th instance on \(T_i\). Each model overfits to a different sample, so their combination can generalize better.

When would bagging work? M10 · 6:36

Consider \(k\) logistic regression models. On a test example, model \(i\) makes an error \(\varepsilon_i\), so the average prediction of all the models makes the error \(\frac1k\sum_i\varepsilon_i\). Let the \(\varepsilon_i\) be drawn from a zero-mean multivariate normal distribution with

\[ \text{Variance} = E[\varepsilon_i^2] = V, \qquad \text{Covariance} = E[\varepsilon_i\varepsilon_j] = C \quad (i \ne j) \]

Expand the square of the sum into the \(k\) terms with \(i = j\) and the \(k(k-1)\) terms with \(i \ne j\), then use linearity of expectation:

\[ \begin{aligned} \text{mse} &= E\Big[\Big(\frac1k\sum_i\varepsilon_i\Big)^2\Big] = \frac1{k^2}E\Big[\sum_i\sum_{j = i}\varepsilon_i\varepsilon_j + \sum_i\sum_{j \ne i}\varepsilon_i\varepsilon_j\Big] = \frac1{k^2}E\Big[\sum_i\varepsilon_i^2 + \sum_i\sum_{j \ne i}\varepsilon_i\varepsilon_j\Big] \\ &= \frac1{k^2}\Big(\sum_i E[\varepsilon_i^2] + \sum_i\sum_{j \ne i}E[\varepsilon_i\varepsilon_j]\Big) = \frac1{k^2}\big(kV + k(k-1)C\big) = \frac1kV + \frac{k-1}{k}C \end{aligned} \]
Error of the averaged ensemble \[ \text{mse} = \frac1kV + \frac{k-1}{k}C \]
  • Perfectly correlated errors, \(V = C\): mse \(= V\). Bagging does not help; the ensemble is as bad as each individual model.
  • Independent or uncorrelated errors, \(C = 0\): mse \(= \frac1kV\).

On average, the ensemble performs at least as well as its individual members.

Real models sit between the extremes 10:42. The smaller the correlation between the models, the larger the benefit; a hundred models that make the same mistakes are no better than one.

D training set sample with replacement T₁ T₂ Tₖ model 1 model 2 model k train average y_final ensemble mse / V number of models k 0 0.5 1 1 5 10 15 20 C = V C = 0.5V C = 0.25V C = 0
Bagging and its payoff. Top: \(k\) training sets drawn with replacement from \(D\), one model per set, predictions averaged. Bottom, drawn to scale from the formula: ensemble mse as a fraction of one model's \(V\), for \(k = 1\) to 20 models and four levels of correlation. With \(C = 0\) the error falls as \(1/k\); with \(C = V\) it stays at 1; in between it levels off at \(C/V\).

Model averaging (a bagging ensemble) typically helps, but for large neural networks it is prohibitively expensive. Option 1, training several networks with different architectures, is obviously expensive. Option 2, training several instances of the same network on different samples of the data, is expensive too. Even if either could be done, combining several models at test time is infeasible in real-time applications, because every test input would have to pass through all of them.

Dropout addresses both issues. It effectively trains several neural networks without significant computational overhead, and it gives an efficient approximate way of combining exponentially many different networks.

  • Dropping units. Temporarily remove a node and all its incoming and outgoing connections, which gives a thinned network. Each node is retained with a fixed probability, typically \(p = 0.5\) for hidden nodes and \(p = 0.8\) for visible (input) nodes.
  • How many networks? With \(n\) nodes, each either retained or dropped, there are \(2^n\) thinned networks. That is far too many to train separately.

Two tricks make it workable 4:36:

  1. Share the weights across all the networks. There is one set of weight matrices, and each thinned network uses the part of it that survives.
  2. Sample a different network for each training instance (or mini-batch).
  1. Training with dropout
  2. Initialize all the parameters (weights) of the network.
  3. For the next training instance or mini-batch, apply dropout: keep each node with its probability \(p\). This gives a thinned network.
  4. Compute the loss with a forward pass through the thinned network.
  5. Backpropagate. Only the parameters that were active get updated; a weight attached to a dropped node took no part in the forward pass and receives no update.
  6. Repeat from step 2 with a fresh sample, so each mini-batch trains a different thinned network.

Because the weights are shared, a weight that was active for two mini-batches has received two updates by then, the second starting from the value the first left behind, while a weight active for only one of them has received one 10:15. Each thinned network gets trained rarely, or even never; with a million nodes there are \(2^{1{,}000{,}000}\) of them, far more than the number of training steps. But parameter sharing ensures that no model has untrained or poorly trained parameters. In the lecturer's example, with nodes kept with probability 0.8, a weight between two nodes is active only when both are kept, with probability \(0.8 \times 0.8 = 0.64\), so over 1,000 steps it receives about 640 updates.

In practice nodes are not visited one by one. A layer's output vector is multiplied element-wise by a random 0/1 mask vector (for example with 20% zeros), so the dropped units output zero and take no part in the computation.

At test time it is impossible to aggregate the outputs of \(2^n\) thinned networks. Instead, use the full network with every node present, and scale the output of each node by the fraction of times it was on during training. A node that was present with probability \(p\) during training, with outgoing weights \(w_1, w_2, w_3, w_4\), is always present at test time with weights \(pw_1, pw_2, pw_3, pw_4\). The lecturer's way of putting it: a node that took part in only 80% of the discussions has its say trusted only 80%.

Why the factor is p

A one-line check (not on the slides). During training a node with output \(h\) sends \(m\,w\,h\) along a weight \(w\), where the mask \(m\) is 1 with probability \(p\) and 0 otherwise. On average that is \(E[m]\,w\,h = p\,w\,h\). Using the weight \(pw\) at test time gives the next layer the input it received on average during training.

Not in the lecture: most libraries implement inverted dropout, which divides the kept outputs by \(p\) during training so that the test-time network needs no change. It is the same correction applied at the other end.

Why dropout regularizes

Dropout essentially applies a masking noise to the hidden units. This prevents hidden units from co-adapting. A unit cannot rely too much on other units, because they may be dropped at any time, so each hidden unit has to learn to be robust to these random dropouts.

An example of how this builds redundancy 15:53. Suppose \(h_i\) learns to detect a face by firing when it detects a nose. Dropping \(h_i\) then erases the information that a nose exists. The model must either learn another unit that redundantly encodes the presence of a nose, or learn to detect the face from other features, such as the eyes or eyebrows. Either way the network becomes more robust.

0.50
This thinned net's output–
Mean over sampled masks–
Full net, weights × p–
Full net, no scaling–
Synthetic network with weights generated for these notes. Four inputs, two hidden layers of five sigmoid units, one linear output, and a fixed input \(\mathbf x = (1, -0.5, 0.8, 1.5)\). Inputs are kept with probability 0.8 and hidden units with the chosen \(p\); the 14 droppable units give \(2^{14} = 16{,}384\) thinned networks, all sharing these weights. Each mini-batch samples one mask: dashed, crossed-out units are dropped, and only the solid weights are used and updated. The test-time network keeps every unit and multiplies each unit's outgoing weights by its keep probability. Its output lands close to the average over many masks, though not exactly on it because the sigmoid is not linear; without the scaling the output is too large whenever \(p \lt 1\).

There are computationally intensive techniques for visualizing the loss landscape of a deep network in 1-D or 2-D, and the slide points to an interactive explorer at losslandscape.com. Real landscapes are bumpy, with many plateaus, valleys and sharp slopes, unlike the smooth bowls used so far in the course. Researchers have correlated the local flatness (curvature) of the loss surface with the generalization of a model, using different measures of curvature:

  • flat surface → better generalization;
  • sharp surface → poor generalization.

The lecturer's reasoning: in a flat region a whole neighbourhood of weights gives about the same loss, so small changes do not matter. In a sharp valley surrounded by hills, a small change of the weights changes the loss a lot, and the model is very sensitive. It has been shown that explicit regularization techniques smooth the loss surface; the lecture's example is a paper that studies skip connections (a CNN technique) as a regularizer.

Grouping the techniques

Each technique acts on some part of the training objective \(\mathscr L(\theta) = \frac1N\sum_{i=1}^{N}l\big(f(x_i, \theta), y_i\big)\):

Acts onTechniques
Data \(x_i\)data augmentation, noise injection
Architecture choice \(f(\cdot)\)dropout, skip connections (CNN), weight sharing, pooling
Penalized cost \(\mathscr L(\cdot)\)\(L_1\), \(L_2\)
Optimizer \(\nabla\)SGD, early stopping

A second grouping splits them into explicit and implicit regularization:

KindTechniques
Explicitdata augmentation, noise injection, dropout, skip connections (CNN), weight sharing, pooling, \(L_1\) and \(L_2\)
ImplicitSGD, large initial learning rate, small initial learning rate, early stopping

Skip connections, weight sharing and pooling come with CNNs in Lecture 8; at least weight sharing and pooling regularize by reducing the number of parameters. On the implicit side, some papers show that gradient descent itself prefers less complex solutions 3:34, and the initial learning rate also shapes how training proceeds. The lecture mentions these without going into detail.

Do regularizers explain generalization?

The slides close with a question the videos do not cover: is regularization, a technique adopted from statistical learning theory, really the fundamental reason deep learning models generalize well? The test is random labelling, from a paper the slides cite (standard reference: Zhang et al., 2017, Understanding deep learning requires rethinking generalization).

  1. Take a deep network that performed well on some task, say classification, and fix its complexity (its size, and so its number of parameters), the optimizer used to train it, its initialization, and so on.
  2. Replace the true labels of the training data with random labels. This removes the relation (regularity) between the inputs and the corresponding outputs. The random labels are fixed and consistent across epochs.

A toy version first. Points are sampled from a noisy sinusoid, the example from the start of the lecture, and fitted with a model of complexity 19 (19 parameters). After training, the model fits the data points and closely represents the true function. Now randomly shuffle \(y\). With its fixed capacity the model cannot fit the shuffled data, and the training error remains high. This is expected: shuffling removed the regularity the model was exploiting.

Deep networks behave differently. Surprisingly, they drive the training error to zero even with random labels. What the slides conclude:

  • Observations on both explicit and implicit regularizers consistently suggest that regularizers, when properly tuned, can improve generalization. It is unlikely, though, that they are the fundamental reason for it, since the networks continue to perform well after all the regularizers are removed.
  • Experimental evidence suggests that the value of the objective may imply nothing about generalization (with respect to the Rademacher complexity measure).
  • This implies that vastly over-parameterized deep models regularize implicitly while their parameters are optimized with SGD or GD: the discrete steps of gradient descent themselves act as a regularizer.

The lecture's recap lists the explicit methods (\(l_2\) regularization, dataset augmentation, parameter sharing and tying, noise at the inputs, noise at the outputs, early stopping, ensembles, dropout) together with this implicit regularization by the optimizer. Lecture 7 moves on to pre-training, better activation functions, weight initialization and batch normalization.

Key terms

Over-parameterized model
More parameters than training samples; can drive the training error to zero and overfit.
Bias
\(E[\hat f(x)] - f(x)\): how far the average model over training samples is from the truth. High for simple models.
Variance
\(E[(\hat f(x) - E[\hat f(x)])^2]\): how much models trained on different samples disagree. High for complex models.
Irreducible error \(\sigma^2\)
The noise variance in \(y\); part of every model's expected test error, bias² + variance + σ².
True error
\(E[(\hat f(x) - f(x))^2]\). Equals the test error minus σ², but exceeds what the training error suggests by a complexity term.
Regularizer \(\Omega(\theta)\)
Term added to the training loss that is large for complex models; a stand-in for \(\frac{\sigma^2}{n}\sum_i\partial\hat f(x_i)/\partial y_i\).
Weight decay (L2)
Penalty \(\frac\alpha2\lVert\mathbf w\rVert^2\). Adds \(\alpha\mathbf w\) to the gradient and scales eigen-direction \(i\) of \(\mathbf w^*\) by \(\lambda_i/(\lambda_i + \alpha)\).
Effective number of parameters
\(\sum_i\lambda_i/(\lambda_i + \alpha) \lt n\): how many directions survive L2 regularization.
Dataset augmentation
New training examples from label-preserving transformations such as rotations, shifts and blurring.
Parameter sharing and tying
Reusing one set of weights: a CNN filter at every position; the encoder's \(W\) and decoder's \(W^\top\) in an autoencoder.
Soft targets (label smoothing)
Target \(1 - \varepsilon\) for the true class and \(\varepsilon/9\) for each of the other nine classes.
Early stopping, patience \(p\)
Stop when the validation error has not improved for \(p\) steps and return the model from step \(k - p\).
Bagging
Ensemble of one classifier trained on samples drawn with replacement; \(\text{mse} = \frac1kV + \frac{k-1}{k}C\).
Dropout, thinned network
Keep each unit with probability \(p\) per mini-batch, sharing weights across the \(2^n\) thinned networks; at test time keep all units and scale weights by \(p\).

Test yourself

Q1In the curve-fitting experiment the 30 degree-1 fits are nearly identical, while the 30 degree-25 fits differ wildly. Which model has high bias and which high variance, and which part of the test error hurts each?

Degree 1: high bias (its average line is far from the sinusoid) and low variance. Degree 25: low bias (its average follows the sinusoid) and high variance. Since test error = bias² + variance + σ², the line is hurt by the bias² term and the polynomial by the variance term; σ² affects both equally.

Q2True error = empirical error − σ² + 2E[ε(f̂(x) − f(x))]. Why is the last term zero when the empirical error is computed on test data, but not on training data?

A test point's \(y\), and so its \(\varepsilon = y - f(x)\), played no part in estimating \(\hat f\). So \(\varepsilon\) is independent of \(\hat f(x) - f(x)\) and \(E[\varepsilon(\hat f - f)] = E[\varepsilon]E[\hat f - f] = 0\). The training \(y_i\) were used to fit \(\hat f\), so the two are dependent and the term survives. By Stein's lemma it equals \(\frac{2\sigma^2}{n}\sum_i\partial\hat f(x_i)/\partial y_i\), which is larger for more sensitive, more complex models.

Q3The Hessian at \(\mathbf w^*\) has eigenvalues 10 and 0.1, and you use L2 regularization with \(\alpha = 1\). By what factor is each eigen-component of \(\mathbf w^*\) scaled, and what is the effective number of parameters?

\(10/11 \approx 0.91\) and \(0.1/1.1 \approx 0.09\). The steep direction is almost fully kept and the flat one almost removed. Effective parameters \(= 0.909 + 0.091 = 1.0\) out of 2.

Q4A linear model \(\hat y = \sum_i w_ix_i\) with \(\mathbf w = (2, -1, 0.5)\) is trained on inputs corrupted by independent Gaussian noise of variance \(\sigma^2 = 0.01\). What does the noise add to the expected squared error?

\(\sigma^2\sum_i w_i^2\) \(= 0.01 \times (4 + 1 + 0.25)\) \(= 0.0525\). It is an L2 penalty, \(\frac\alpha2\lVert\mathbf w\rVert^2\) with \(\alpha = 2\sigma^2 = 0.02\).

Q5With \(\varepsilon = 0.1\) and 10 classes, what is the soft target for an image of a 3, and how does it change the loss?

0.9 for class 3 and \(0.1/9 \approx 0.011\) for each of the other nine classes. The cross-entropy becomes \(0.9 \times\) the usual loss \(-\log q_3\) plus \(0.1 \times\) the average of \(-\log q_i\) over the other classes, a loss-plus-regularizer form that stops the network from putting probability 1 on a label that may be wrong.

Q6The validation error is lowest at step 37 and never improves afterwards. With patience \(p = 5\), at which step does training stop, and which model is returned?

Steps 38 to 42 bring no improvement, so at \(k = 42\) the previous 5 steps show none and training stops. The model returned is the one stored at step \(k - p = 37\).

Q7An ensemble averages 10 models whose errors have variance \(V = 1\) and pairwise covariance \(C = 0.2\). What is the ensemble's mse, and what would it be with \(C = 1\)?

\(\frac1kV + \frac{k-1}{k}C\) \(= 0.1 + 0.9 \times 0.2 = 0.28\), against 1 for a single model. With \(C = 1 = V\) the errors are perfectly correlated and the mse stays at 1: no gain.

Q8A network has 20 droppable nodes, and a hidden unit kept with \(p = 0.5\) has an outgoing weight of 1.2. How many thinned networks are there, and what weight is used at test time?

\(2^{20} = 1{,}048{,}576\) thinned networks, all sharing one set of weights; each mini-batch trains one of them. At test time the unit is always present and its outgoing weight is \(p \times 1.2 = 0.6\), the input the next layer received on average during training.