Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Regularization for neural nets

P4.1740 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A network with many more parameters than training examples can fit the noise in its labels and still look perfect on the training set, so every serious training recipe adds something that holds the fit back.

Before this: Train, validation and test sets, Regularization: L1 and L2, Backpropagation: step by step with numbers, Optimizers

After this lesson you can

  • Show with a small experiment that a large network fits noisy labels, and read the gap between training and test results
  • Write the weight-decay update and say which parameters it is usually applied to
  • Explain inverted dropout, including why nothing is dropped or scaled at test time, and the naming clash between the keep and drop probability
  • Describe early stopping with patience and a saved best checkpoint
  • Compute a label-smoothed target and say what it changes about the loss

A network with 64 hidden units and 60 training examples has far more knobs than facts to learn. Give it labels where a fifth are wrong and it will learn the wrong ones too. Its training accuracy reaches nearly 100%100\%, and on new data its loss can be worse than that of a coin flip. Part 3 named this problem overfitting (P3.A3), and showed that the gap between training and validation results is how you see it (P3.A4, P3.A5). Networks are especially prone to it, because they are so flexible (P4.11).

Regularization means anything that gives up a little training fit to do better on new data. P3.A6 did it for linear models with a penalty. This lesson covers the four tools that networks use most: weight decay, dropout, early stopping and label smoothing.

A network that memorizes noise

Here is a small made-up task. Ten inputs are random numbers, but only the first two matter: the true class is 11 when x1+x2>0x_1+x_2>0. Then 20%20\% of the labels are flipped at random (in this training set, 99 of 6060), so the best possible accuracy on fresh data with the same noise is about 80%80\% (on the test set used below, the true rule scores 81.9%81.9\% because of sampling). The network has 6464 ReLU hidden units, and it is trained by gradient descent on the mean cross-entropy (P4.6, P4.8).

The cell below trains it four ways, five times each with different random starting weights, and reports the average. Weight decay, dropout and early stopping are explained in the sections that follow. For now, read the first row: none means plain training for 10001000 steps.

Try it: one network, four ways to train it

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the code gives this table (on the machine used for this lesson; the cell takes about a second):

mean of 5 runs train  test  test
                 acc   acc  loss
none            0.997 0.690 1.082
weight decay    0.823 0.703 0.586
dropout 0.5     0.983 0.702 0.842
early stopping  0.810 0.662 0.635

Read it row by row.

  • None. The network gets 99.7%99.7\% of the training labels right. That includes the flipped ones, so it has memorized the noise. On the test set its accuracy is only 69.0%69.0\%, and its test loss is 1.0821.082. A model that always answers “50 percent” has loss ln⁡2=0.693\ln 2 = 0.693, so this network is worse than not knowing anything: it is confidently wrong on many new points.
  • The other three all have a training accuracy that is lower, or a little lower, and a much smaller test loss. That is what regularization looks like. Their test accuracies are closer together (66.2%66.2\% to 70.3%70.3\%). Over the five runs, one method’s test accuracy varies by up to about three percentage points (for example 67.4%67.4\% to 70.8%70.8\% for plain training), so a difference of one or two points between methods here is not reliable. The differences in loss are large and the same in every run.
  • Early stopping is not a win on accuracy here. It stopped very early, when the network had only started to learn, and its mean test accuracy is the lowest of the four (66.2%66.2\%; its runs overlap with plain training, so treat the gap as small). A good loss and a good accuracy are different things, and a regularizer can help one and not the other.

This is one made-up task. It shows the pattern, not a ranking of the methods.

0200400600800100000.20.40.60.811.2

training loss validation loss horizontal axis: training step

At step 1000: training loss 0.094, validation loss 1.106.

Training loss (solid blue line) and validation loss (dashed pink line) of one run of the cell above, for no regularization, weight decay and dropout. The validation set here is the 500 held-out points used for early stopping. With no regularization, the training loss keeps falling while the validation loss rises after about step 40. Losses are computed with dropout switched off. Drag the step slider, and turn on the marker to see where the lowest validation loss is.

In the plain run, training loss falls steadily while validation loss falls, reaches a minimum and then rises, as the network starts to fit noise. The regularizers flatten that rise.

Weight decay

The oldest idea is the one from P3.A6: add a penalty for large weights. For the weights W\mathbf{W} of a network the penalized loss is

Ltotal=L+λ2∥W∥2.\mathcal{L}_{\text{total}} = \mathcal{L} + \frac{\lambda}{2}\lVert\mathbf{W}\rVert^2 .

Its gradient adds λW\lambda\mathbf{W}, so one step of gradient descent is

W←W−η(g+λW)=(1−ηλ) W−η g.\begin{aligned} \mathbf{W} &\leftarrow \mathbf{W} - \eta(\mathbf{g} + \lambda\mathbf{W})\\ &= (1-\eta\lambda)\,\mathbf{W} - \eta\,\mathbf{g}. \end{aligned}

Every step first shrinks every weight by the factor 1−ηλ1-\eta\lambda and then takes the usual step. This is weight decay. In the cell above, λ=0.1\lambda = 0.1 and η=0.03\eta = 0.03, so each step multiplies the weights by 0.9970.997. That is a tiny pull per step, but it acts on every one of the 10001000 steps and the data must keep pushing back for a weight to stay large. Small weights give a smoother function, which is harder to bend around single noisy points. In the table, weight decay cut the training accuracy to 82.3%82.3\% and the test loss to 0.5860.586.

Three points that cause confusion:

  • With Adam it is not the same as the penalty. For plain SGD, the penalty’s gradient and the shrink-by-a-factor form are one update. For Adam they are not, which is why the decoupled form AdamW exists. P4.13 explained this with numbers; here, “weight decay” in a large model usually means AdamW’s version. In PyTorch it is the weight_decay argument of the optimizer. The two optimizers use different defaults (00 for Adam, 0.010.01 for AdamW).
  • Which parameters. The penalty is usually put on the weight matrices. Biases and the scale and shift parameters of normalization layers (P4.19) are often left out. One reason often given is that there are few of them and they do not drive overfitting much. It is a common convention and not a law, and some recipes decay everything. The PyTorch block below shows how to make the two groups. The cell above also leaves the biases alone.
  • The size of λ\lambda needs tuning. Too small does nothing, and too large stops the network from fitting even the real pattern. Values such as 0.010.01 and 0.10.1 are common starting points for AdamW, but the best value depends on the model, the learning rate and the length of training (P4.23).

Dropout

Dropout takes a different route. At every training step, each hidden unit is switched off with probability pp. A switched-off unit sends 00 to the next layer for this step, and its incoming and outgoing edges might as well not exist. The next step draws a completely new random set. No unit can count on a particular partner being present, so units are pushed to learn features that are useful on their own. (The 2012 arXiv paper by Hinton and co-authors called what is prevented “co-adaptation” of feature detectors. The long version is Srivastava et al., JMLR 2014.)

The mask

Write the output of a layer as h\mathbf{h}. Draw a mask m\mathbf{m}, with one entry per unit, where each mim_i is 11 (kept) with probability 1−p1-p and 00 (dropped) with probability pp. The entries are independent of one another, which is the Bernoulli variable of P1.D3 repeated once per unit. In inverted dropout the kept outputs are also scaled up:

h~=m⊙h1−p,mi∼Bernoulli(1−p),\begin{aligned} \tilde{\mathbf{h}} &= \frac{\mathbf{m}\odot\mathbf{h}}{1-p},\\ m_i &\sim \text{Bernoulli}(1-p), \end{aligned}

where ⊙\odot multiplies entry by entry. Press the buttons below. With p=0.5p=0.5 about half of the 16 hidden units are dropped at each step, but which ones changes every time.

inputhidden 1hidden 2outputAkept × 2kept × 2

kept unit dropped unit (crossed, dashed, no edges)

Step 1: 5 of 16 hidden units kept, 11 dropped.

Average over all 1 step: 0.313 of the units kept. Keep probability 1 − p = 0.5.

Unit A (output 3) sent 0 this step. Average so far: 0. The unscaled output is 3.

The masks are made-up but seeded: the same step always gives the same mask, and a larger p only drops more of the same units. Unit A is a made-up unit whose output would be 3.

A network with 4 inputs, two hidden layers of 8 units, and 2 outputs. Each training step draws a new mask. A dropped unit is grey, dashed and crossed, and its edges disappear. Kept units are filled blue, and the label under each hidden layer shows the factor that kept outputs are multiplied by. Next step draws a new mask, Play does it automatically, and +100 steps jumps ahead so that the averages settle. Unit A is a made-up unit with output 3: the readout shows what it sends and the average over steps. The slider changes the drop probability, and Evaluation mode shows the same network when it is used for predictions.

Things to try, and what to notice:

  1. Next step a few times. The count of kept units jumps around 88 (for p=0.5p=0.5) but is not always 88. Each unit is its own coin flip, so 1616 units are not split exactly in half.
  2. +100 steps, then again. The average fraction kept moves toward 1−p1-p. A fresh mask every step is Monte Carlo sampling (P1.D9), and the average of many masks is steady even though one mask is not.
  3. Look at unit A. At p=0.5p=0.5 it sends 66 when kept, never 33. Its average over many steps comes close to 33, its unscaled output. That is the reason for the factor 1/(1−p)1/(1-p).
  4. Set p=0.75p=0.75 and look at the label under the hidden layers: kept outputs are multiplied by 44.
  5. Turn on Evaluation mode. Every unit is back, nothing is scaled, and unit A sends exactly 33.

Why the scale 1/(1−p)1/(1-p)

If a unit’s output is hh and it is kept with probability 1−p1-p, then without scaling the expected output is h(1−p)h(1-p), smaller than hh. At test time, with every unit present, the next layer would suddenly receive larger inputs than it ever saw in training. Dividing the kept outputs by 1−p1-p fixes the average: by linearity of expectation (P1.D4),

E ⁣[m h1−p]=h E[m]1−p=h(1−p)1−p=h.\mathbb{E}\!\left[\frac{m\,h}{1-p}\right] = \frac{h\,\mathbb{E}[m]}{1-p} = \frac{h(1-p)}{1-p} = h .

The expected value is unchanged. The variance is not: it becomes h2 p/(1−p)h^2\,p/(1-p), which is the noise that dropout adds. For h=3h=3 and p=0.25p=0.25 that is 33, the same example as in P1.D4. The cell below checks both numbers by simulation, and a layer of eight units.

Try it: dropout keeps the average, adds noise

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

fraction kept:     0.75
mean, no scale:    2.251
mean, scaled:      3.001
variance, scaled:  2.997
formula x^2 p/(1-p): 3.0
layer output, mean over steps:
1.00 1.99 3.00 4.00 5.00 6.00 7.01 8.01
units dropped per step: mean 2.0

The unscaled version has mean 2.2512.251 and the scaled one 3.0013.001, as predicted. The variance, 2.9972.997, matches x2p/(1−p)=3x^2p/(1-p) = 3. The layer’s mean outputs come back to 11 through 88, with about 22 of the 88 units dropped per step (8p8p).

Train mode and eval mode

Dropout is on only while training. When you use the model to predict, all units are used and nothing is scaled: the layer is the identity function. That works only because the scaling was done during training, which is why this version is called inverted. The original paper kept the training step plain and, at test time, multiplied the weights by the keep probability instead. Both have the same effect on the average, and the inverted form leaves the test-time model unchanged, which is simpler. It is the form PyTorch uses.

In PyTorch the switch is model.train() and model.eval() (P2.7). Forgetting model.eval() before measuring validation accuracy gives noisy and usually worse numbers, and it is a classic bug. Wrap evaluation in torch.no_grad() as well; that part saves memory and does not change the mode.

Two names for pp

What happens in backpropagation

The mask is part of the forward pass, so the backward pass goes through it (P4.8). A dropped unit sent 00, so no gradient flows through it and its incoming weights get no update from this example. A kept unit’s gradient is multiplied by the same 1/(1−p)1/(1-p) as its output. Each step trains a different thinned-out sub-network, but all of them share one set of weights.

Why does it help, and where is it used?

Two explanations are common, and both are partial. Dropping units prevents units from relying on one another, as above. The second view: a layer with nn units has 2n2^n possible masks, so training samples from a huge family of thinned networks, and the full network at test time approximates averaging all of them, as an ensemble (P3.B4). For the 1616 hidden units in the picture there are 65,53665{,}536 masks. The averaging is approximate and the explanation is a way to think, not a proof.

Where it is used varies. It is common in smaller networks and in fully connected layers, often with pp between about 0.10.1 and 0.50.5, and many transformer implementations include a small dropout. Some very large models trained on huge datasets use little or none, because with enough data overfitting is less of a problem. Treat these as habits to check against a recipe, not rules. Dropout also usually needs more training steps to reach the same training loss, which is why the training loss in the figure above stays higher.

Go deeper Dropout at prediction time on purpose

Some methods keep dropout switched on at prediction time and run the same input several times. The spread of the answers is then used as a rough estimate of how unsure the model is, sometimes called Monte Carlo dropout. How well that spread matches real uncertainty is debated, and it is not the standard way to run a model. It does show that the mask is just a random input to the network, and that eval() is a choice and not something automatic.

Early stopping

The curves above suggest the simplest idea of all: stop training when the validation loss stops improving. The recipe has three parts.

  1. After every epoch (or every few hundred steps) compute the loss on the validation set (P3.A4).
  2. Save a copy of the weights whenever the validation loss reaches a new lowest value. This copy is the best checkpoint.
  3. If the validation loss has not improved for a number of checks in a row, called the patience, stop. Load the best checkpoint, not the last weights.

Patience matters because validation loss is noisy: one bad epoch does not mean the run is over, and one good epoch does not mean it is time to stop. A larger patience is safer and costs more training time. In the cell above, patience was 3030 steps. Over the five runs the best checkpoint came between step 4141 and step 8181.

Early stopping also acts as a regularizer in its own right: the longer you train, the more complex a function the network can express, so stopping earlier limits it. (In some simple settings stopping early behaves much like weight decay, but this does not carry over exactly to deep networks.)

One more point. The validation set made the choice of stopping step, so its score is a little optimistic by construction. That is why the cell above reports on a separate test set (P3.A4).

Label smoothing

The other three tools act on the weights, the activations or the length of training. Label smoothing works on the target. With a one-hot label, cross-entropy keeps asking for the true class to get probability 11 (P1.E3), and that needs the logit of the true class to be infinitely larger than the others. The loss never says “enough”. So the weights and logits tend to keep growing, which is one reason networks become over-confident.

Label smoothing replaces the one-hot target y\mathbf{y} over KK classes by

yε=(1−ε) y+εK 1,\mathbf{y}_{\varepsilon} = (1-\varepsilon)\,\mathbf{y} + \frac{\varepsilon}{K}\,\mathbf{1},

a mix of the one-hot vector and the uniform distribution (P1.E2). The true class gets 1−ε+ε/K1-\varepsilon+\varepsilon/K and every other class ε/K\varepsilon/K. Szegedy et al. introduced it for the Inception-v3 image network (arXiv 2015, CVPR 2016).

A worked example, K=10K=10 and ε=0.1\varepsilon=0.1. The numbers are those of P1.E2, with the formula of P1.E3. The target becomes 0.910.91 for the true class and 0.010.01 for each of the nine others. Its entropy is 0.7220.722 bits, which is 0.722ln⁡2=0.5000.722\ln 2=0.500 nats (P1.E2 uses bits, the training loss uses nats). A one-hot label has entropy 00.

Now the training loss, H(yε,q)H(\mathbf{y}_\varepsilon,\mathbf{q}) with the model’s probabilities q\mathbf{q}:

  • The best the model can do is q=yε\mathbf{q}=\mathbf{y}_\varepsilon. The loss is then the entropy of the target, 0.5000.500 nats, and the gradient with respect to the logits, q−yε\mathbf{q}-\mathbf{y}_\varepsilon (P4.6), is exactly 0\mathbf{0}. Training has a place to stop.
  • That place needs a finite logit gap. The true class needs ln⁡(0.91/0.01)=ln⁡91=4.51\ln(0.91/0.01) = \ln 91 = 4.51 more than each other class. With a one-hot target the loss only reaches 00 as the gap goes to infinity.
  • Being sure is now penalized. Suppose the model gives the true class 0.970.97 and spreads the remaining 0.030.03 equally. The one-hot loss is −ln⁡0.97=0.030-\ln 0.97 = 0.030, which is small. The smoothed loss is 0.5410.541, higher than the best value of 0.5000.500, and the gradient on the true class is 0.97−0.91=+0.060.97-0.91=+0.06: it pushes the confidence back down.

For K=3K=3 and ε=0.1\varepsilon=0.1 the target (1,0,0)(1,0,0) becomes (0.933,0.033,0.033)(0.933,0.033,0.033), the example in P3.A8.

One convention to check. PyTorch’s CrossEntropyLoss(label_smoothing=ε) uses exactly this form: ε\varepsilon is spread over all KK classes, including the true one. The PyTorch docs describe it as a mixture of the original target and a uniform distribution. Some other write-ups spread ε\varepsilon over the K−1K-1 wrong classes only, which gives different numbers for the same ε\varepsilon, so check the definition before you compare values. The value ε=0.1\varepsilon=0.1 is a common choice, not a rule.

What it does, and what it does not. Label smoothing often gives less over-confident probabilities. Müller, Kornblith and Hinton (NeurIPS 2019) report better calibration (P3.A10) on several tasks as well as better generalization, and also that a teacher trained with smoothing teaches a student worse in knowledge distillation (P10.F2). Results depend on the task, so it is a tool to try, not a promise. It is not a prior on the weights (P1.D11), because it changes the targets and not the parameters. And if the labels are really wrong, as in our noisy task, smoothing softens the damage but does not know which labels are wrong.

Other ways to hold a network back

  • Data augmentation adds fresh, slightly changed copies of the training data (flips, crops, noise), so the network cannot memorize one fixed picture. It is often very effective for images, and P4.18 covers it.
  • Noise injection adds small random noise to inputs or activations. Dropout is one kind of multiplicative noise on activations.
  • A smaller network, or more data. Fewer parameters limit what can be fitted, and more data is the best regularizer when it is available.
  • Max-norm constraints cap the length of each unit’s weight vector. This is a projection (P1.F7), and Srivastava et al. used it together with dropout.

Which to use?

There is no single recipe, but these habits are common starting points, not rules:

  • Always keep a validation set and watch the two curves. That is the only way to know whether you have a problem (P4.22).
  • AdamW with a small weight decay is a common default for transformers and for many other models.
  • Early stopping is cheap, so a saved best checkpoint is almost free insurance.
  • Dropout is worth trying when a smaller network overfits. When the training set is large, try little or none.
  • Label smoothing is worth trying for classification with many classes, and it needs only one number.
  • They interact. Dropout slows training, and weight decay and the learning rate (P4.14) work together, so change one thing at a time. Each has its own strength to tune.

Intuition

An overfit network is a student who memorized the practice exam. Weight decay makes memorizing expensive, because big weights cost something. Dropout makes the student study with a random half of the notebook missing each day, so no single page can carry the answer. Early stopping takes the exam as soon as the practice-test score stops improving. Label smoothing stops the student from being certain when the answer key itself is sometimes wrong.

The analogy breaks in one place: a real student can tell when a question is hard. A network treats every training label as equally true, including the wrong ones, and only these tricks stop it.

Math

  • Weight decay: L+λ2∥W∥2\mathcal{L}+\frac{\lambda}{2}\lVert\mathbf{W}\rVert^2; gradient step gives W←(1−ηλ)W−ηg\mathbf{W}\leftarrow(1-\eta\lambda)\mathbf{W}-\eta\mathbf{g}. Adam: decoupled form (P4.13).
  • Inverted dropout: h~=m⊙h/(1−p)\tilde{\mathbf{h}}=\mathbf{m}\odot\mathbf{h}/(1-p) with independent mi∼Bernoulli(1−p)m_i\sim\text{Bernoulli}(1-p). E[h~]=h\mathbb{E}[\tilde h]=h and Var(h~)=h2p/(1−p)\mathrm{Var}(\tilde h)=h^2p/(1-p).
  • Backward through dropout: ∂L/∂hi=mi1−p ∂L/∂h~i\partial L/\partial h_i = \dfrac{m_i}{1-p}\,\partial L/\partial\tilde h_i.
  • Evaluation: h~=h\tilde{\mathbf{h}}=\mathbf{h}.
  • Number of masks: 2n2^n for nn units.
  • Label smoothing: yε=(1−ε)y+ε1/K\mathbf{y}_\varepsilon=(1-\varepsilon)\mathbf{y}+\varepsilon\mathbf{1}/K. For softmax with cross-entropy, ∂L/∂z=q−yε\partial L/\partial\mathbf{z}=\mathbf{q}-\mathbf{y}_\varepsilon. The minimum is at q=yε\mathbf{q}=\mathbf{y}_\varepsilon, a logit gap of ln⁡1−ε+ε/Kε/K\ln\frac{1-\varepsilon+\varepsilon/K}{\varepsilon/K} (=ln⁡91=\ln 91 for K=10K=10, ε=0.1\varepsilon=0.1).
  • Early stopping: keep θ\boldsymbol{\theta} at arg⁡min⁡tLval(θt)\arg\min_t \mathcal{L}_{\text{val}}(\boldsymbol{\theta}_t), stop when no new minimum for the patience.

Code

The program below shows dropout in train and eval mode, checks that the built-in label smoothing equals the formula, and builds the two weight-decay groups (weights decayed, biases not). Run locally with PyTorch 2.9.1; the dropout masks are random, so your zeros will fall in other places.

import torch
from torch import nn

torch.manual_seed(0)
drop = nn.Dropout(p=0.5)            # p is the DROP probability
x = torch.ones(1, 8)

drop.train()
print("train:", drop(x))
print("train:", drop(x))            # a fresh mask on every call
drop.eval()
print("eval: ", drop(x))            # identity

# the scale 1/(1-p): average over many masks
drop.train()
big = torch.ones(100000)
print("mean:", round(drop(big).mean().item(), 3))

# label smoothing: the built-in equals the formula
z = torch.tensor([[2.0, 0.5, -1.0]])
y = torch.tensor([0])
for eps in (0.0, 0.1):
    loss = nn.CrossEntropyLoss(label_smoothing=eps)(z, y)
    print(f"eps={eps}: {loss.item():.4f}")
t = torch.tensor([[0.9 + 0.1 / 3, 0.1 / 3, 0.1 / 3]])
print("by hand:", round(-(t * torch.log_softmax(z, 1)).sum().item(), 4))

# which parameters get weight decay: weight matrices only
model = nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 1))
decay = [p for p in model.parameters() if p.ndim >= 2]
no_decay = [p for p in model.parameters() if p.ndim < 2]
opt = torch.optim.AdamW(
    [{"params": decay, "weight_decay": 0.1},
     {"params": no_decay, "weight_decay": 0.0}], lr=1e-3)
print([g["weight_decay"] for g in opt.param_groups],
      [sum(p.numel() for p in g["params"]) for g in opt.param_groups])
train: tensor([[0., 0., 2., 0., 0., 0., 2., 2.]])
train: tensor([[0., 2., 2., 2., 2., 0., 2., 2.]])
eval:  tensor([[1., 1., 1., 1., 1., 1., 1., 1.]])
mean: 0.998
eps=0.0: 0.2413
eps=0.1: 0.3913
by hand: 0.3913
[0.1, 0.0] [704, 65]

The first two lines are two different masks for the same input: the kept entries become 2=1/(1−0.5)2 = 1/(1-0.5). In eval mode the layer returns the input. The mean over 100,000100{,}000 units is close to 11, as inverted dropout promises. The two losses 0.24130.2413 and 0.39130.3913 are with and without smoothing, and the hand-made target gives the same 0.39130.3913. The last line shows the two decay values and the group sizes: 704704 weights (10⋅64+6410\cdot 64+64) get decay 0.10.1, and the 6565 biases (64+164+1) get none.

Check your understanding

  1. A layer uses inverted dropout with drop probability p=0.2p=0.2. By what number is each kept output multiplied during training?

  2. What does an nn.Dropout layer do after model.eval() has been called?

  3. Which statement about the two meanings of pp in dropout is correct?

  4. Training with early stopping ends because the validation loss has not improved for the patience. Which weights should the final model use?

  5. With K=5K=5 classes and ε=0.1\varepsilon=0.1, label smoothing in the form (1−ε)y+ε/K(1-\varepsilon)\mathbf{y}+\varepsilon/K gives the true class which target value?

Exercises

  1. A weight is 55 and its loss gradient is 00 at this step. With weight decay λ=0.2\lambda=0.2 and learning rate η=0.1\eta=0.1 in plain SGD, what is the weight after one step?
    Show answerThe factor is 1−ηλ=1−0.02=0.981-\eta\lambda=1-0.02=0.98, so the weight becomes 5⋅0.98=4.95\cdot 0.98=4.9.
  2. A unit outputs h=5h=5 and the drop probability is p=0.2p=0.2. What does the unit send in training when it is kept and when it is dropped? What are the expected value and the variance of what it sends?
    Show answerKept: 5/0.8=6.255/0.8=6.25. Dropped: 00. The expected value is 0.8⋅6.25=50.8\cdot 6.25=5, and the variance is h2p/(1−p)h^2p/(1-p), which is 25⋅0.2/0.8=6.2525\cdot 0.2/0.8=6.25. A simulation with a million masks gives about 5.005.00 and 6.256.25.
  3. A layer has 100100 units and p=0.3p=0.3. How many units are dropped at one step on average, and what is the standard deviation of that count?
    Show answerThe count is the sum of 100100 independent Bernoulli variables with probability 0.30.3 (P1.D3), so its mean is 100⋅0.3=30100\cdot 0.3=30 and its standard deviation 100⋅0.3⋅0.7=4.58\sqrt{100\cdot 0.3\cdot 0.7}=4.58.
  4. Four classes and ε=0.2\varepsilon=0.2. Write the smoothed target for true class 11. What is the cross-entropy loss if the model outputs (0.7,0.1,0.1,0.1)(0.7,0.1,0.1,0.1), and what would it be with the one-hot target?
    Show answerThe target is (0.85,0.05,0.05,0.05)(0.85,0.05,0.05,0.05), from 0.8+0.050.8+0.05 and 0.050.05. The smoothed loss is −(0.85ln⁡0.7+0.15ln⁡0.1)-(0.85\ln 0.7+0.15\ln 0.1), which is 0.6490.649. The one-hot loss is −ln⁡0.7=0.357-\ln 0.7=0.357.
  5. The validation losses after epochs 11 to 88 are 0.700.70, 0.620.62, 0.580.58, 0.570.57, 0.580.58, 0.590.59, 0.600.60, 0.610.61. With patience 33, after which epoch does early stopping stop, and which epoch’s weights are kept?
    Show answerThe lowest loss, 0.570.57, is at epoch 4. Epochs 5, 6 and 7 are not better, so that is three checks in a row and training stops after epoch 7. The weights from epoch 4 are loaded.

Next: P4.18 covers data augmentation, the other main tool against overfitting. P4.19 covers normalization layers, which also behave differently in training and evaluation, and P4.22 puts the curves from this lesson into a training and debugging recipe.

Key takeaways

  • Regularization is anything that trades a little training fit for better results on new data. In networks the common tools are weight decay, dropout, early stopping and label smoothing.
  • Weight decay shrinks each weight by the factor 1−ηλ1-\eta\lambda at every step. With plain SGD it equals an L2 penalty, and with Adam the decoupled form (AdamW) is used (P4.13).
  • Dropout multiplies each hidden unit by a fresh random 00 or 1/(1−p)1/(1-p) at every training step. The scale keeps the expected output unchanged, so in evaluation mode dropout does nothing.
  • In PyTorch nn.Dropout(p) takes the drop probability pp. The original paper's pp was the keep probability, so check which one a source means.
  • Early stopping keeps the weights from the step with the lowest validation loss. Label smoothing replaces the one-hot target by (1−ε)(1-\varepsilon) times it plus ε/K\varepsilon/K on every class.
Found a mistake? Tell us