A network’s training loss can keep falling long after its loss on held-out cases has started to rise. Which of the parameter vectors met along the way should be kept, and would a weight penalty or dropout have done better? This lesson defines weight decay and its decoupled form for adaptive optimizers, explains dropout, separates a network’s training mode from its evaluation mode, and turns early stopping into a declared rule for selecting a checkpoint by validation loss. A constructed example then shows what a fair comparison of these choices can and cannot establish.
Key terms
Weight decay
Definition Let be the mean training loss of a network with parameters , and let be the set of penalized weights. On this page contains every entry of the weight matrices and of the output weights, and the biases are left unpenalized by a stated choice. An L2 penalty with strength trains on the objective
For a penalized weight with data gradient , the partial derivative of is , so one plain gradient descent step with learning rate is
Weight decay is the rule on the second line. It multiplies each penalized weight by the factor and then takes the ordinary gradient step, and when the factor lies strictly between and . For plain gradient descent, and for stochastic gradient descent without momentum, the L2 penalty and weight decay with this factor produce exactly the same updates, even when the learning rate changes from step to step. Setting gives unregularized training. What a weight penalty prefers depends on how the inputs are scaled, so rescaling a feature changes which fits the penalty favors.
In plain words Each step pulls every penalized weight a fixed fraction of the way toward zero, and the data gradient then pushes it where the training data want it. A weight stays large only if the data keep pushing it there. The penalty is the one of ridge regression, now applied to the weights of a network. Smaller weights are a preference written into the objective, not proof of a better model, so the strength is chosen on validation data like any other setting.
Example Take a weight with data gradient , learning rate and . The shrink factor is , so the new weight is . Without decay the step gives . The difference equals , so the pull toward zero is proportional to the current size of the weight.
Decoupled weight decay
Definition Adam keeps, for each weight, running averages of its gradient and of the squared gradient, starting from ,
with and . It divides them by and to get and , and it moves the weight by with a small . An L2 penalty enters Adam through the gradient, since is replaced by in both averages, so the pull of the penalty is divided by the same coordinate-wise scale as the data gradient. Decoupled weight decay, the rule of AdamW, computes the averages from the data gradient alone and shrinks the weight in a separate term,
For Adam and other adaptive optimizers, and also for gradient descent with momentum, the coupled penalty and the decoupled decay generally produce different updates, and a value of tuned for one does not carry over to the other. Libraries differ in whether the decay coefficient is multiplied by the learning rate, and an option named weight decay may implement either rule, so a report names the optimizer, the regularization rule actually applied and its value.
In plain words Adam divides each weight’s step by a running measure of that weight’s own gradient size, so weights with large and small gradients move by steps of similar size. A penalty added to the gradient is divided along with it, which means that weights with a history of large gradients are decayed less than the others. Decoupled decay shrinks every penalized weight by the same fraction per step, whatever its gradient history.
Example Take the weight with data gradient , and again, now as the first step of Adam. At the corrections give and , so the step is , almost exactly times the sign of . Without any penalty the new weight is . With the L2 penalty the gradient becomes , which has the same sign, so the new weight is again , up to a difference below , and the penalty has had no visible effect. AdamW gives about , while plain gradient descent with either form gave .
Dropout
Definition Dropout acts on the activations of a layer during training, with a dropout probability such that and keep probability . In every training forward pass it draws independent masks , a fresh one for each unit of each example, and inverted dropout passes on
The backward pass uses the same mask, so no gradient flows back through a dropped unit and the gradient through a kept unit is multiplied by . At evaluation, inverted dropout is switched off and passes unchanged. The original form of dropout skips the division by in training and multiplies by at evaluation instead, and the two scale conventions must not be mixed. The equality of expectations holds unit by unit. It does not make the average network output over random masks equal to the output of the evaluation network, because the computation after the dropout layer is in general nonlinear.
In plain words Every training step uses a randomly thinned network, so no hidden unit can count on a particular partner being present. Dividing by the keep probability keeps each unit’s average output at its full value, so the network used for evaluation needs no rescaling. Dropout changes how training computes, not which network is evaluated.
Example A layer with keep probability produces the activations and , and the training pass draws the mask . The outputs are and . Over many masks the first unit gives with probability and otherwise, which averages to . At evaluation the outputs are simply and . Averages do not pass through a nonlinearity, though. Suppose the logit is for a single unit with activation and keep probability . The logit is or with equal probability and averages to the evaluation logit , but the predicted probabilities and average to about , while the evaluation network gives .
Training and evaluation modes
Definition Layers such as dropout and batch normalization compute differently in a network’s two modes. In training mode, dropout draws random masks, and batch normalization standardizes each feature with the mean and the variance of the current mini-batch and updates stored running averages of these statistics. In evaluation mode, dropout passes its input unchanged, and batch normalization standardizes with the stored running averages, so the output for one example does not depend on which other examples share its batch, and nothing is updated. Validation losses, checkpoint selection, test results and deployed predictions all use evaluation mode. The mode is a separate switch from gradient tracking. Turning off gradient computation leaves dropout active, and forward passes in training mode can update the batch normalization statistics even when no gradient is computed.
In plain words The mode tells each layer whether it is being trained or used. A model scored in training mode is a random, batch-dependent variant of the model that will actually be used, and running validation data through batch normalization in training mode even writes validation statistics into the model.
Example A batch normalization unit with scale , shift and a negligible receives the value . In training mode, in a batch with the values and , it uses the batch mean and the batch variance , computed with divisor , and outputs . In a batch with the values and the mean is , the variance is again , and the same value comes out as . In evaluation mode with stored running mean and running variance , it outputs in either batch. The dropout layer of the previous card likewise gives and for one draw in training mode and always and in evaluation mode. The constructed comparison on this page draws masks only inside its training updates and computes every reported loss with a separate deterministic prediction function.
Validation loss
Definition For parameters and validation examples that took no part in fitting, the validation loss is the mean loss
where is the logit the network computes for in evaluation mode. On this page is the binary cross-entropy written from the logit, , measured in nats per example, and no penalty term is included. For a fixed chosen without these examples, if they are independent draws from the population of interest, the validation loss is an unbiased estimate of the population risk of that network. Once it has been used to choose among checkpoints or candidates, the smallest value is an optimistically biased estimate for the one chosen. Comparisons across epochs or candidates need the same examples, the same loss with the same reduction, such as the mean over examples, and the same mode. The training loss reported next to it on this page is computed the same way on the training examples, which differs from the objective the optimizer minimizes when a penalty or dropout is in use.
In plain words Validation loss scores the current parameters on cases the optimizer never saw. Training loss and validation loss answer different questions, and they can move in opposite directions. Cross-entropy also registers changes in confidence that accuracy ignores, so validation loss can rise while validation accuracy stays the same.
Example The constructed comparison on this page has training cases and validation cases, with two features drawn uniformly from the square and the label when . Three training labels were deliberately flipped from to to model label errors, and the validation labels follow the unflipped rule. A network with tanh hidden units and a logistic output is trained by full-batch gradient descent with for epochs, one gradient step per epoch, from a fixed seed. Without regularization the validation loss starts at , reaches its minimum at epoch , where the training loss is , and rises to by epoch , while the training loss falls to . The validation accuracy is at both epochs, so accuracy alone would not show the change. The comparison also trains the same network with an L2 penalty of strength on its weights and, separately, with dropout probability on its hidden layer. For the weight decay candidate, the training loss at its selected checkpoint, epoch , is and the penalty adds , so its training objective there is . Plotting that objective next to the unpenalized training losses of other candidates would compare two different quantities.
Early stopping
Definition Early stopping evaluates the validation loss at declared checks during training, saves a copy of the parameters whenever the loss improves, and returns the saved checkpoint instead of the final parameters. Checkpoint selection is the rule that names the returned checkpoint. For a set of checked epochs, write for the parameters after epoch and for their validation loss. This page selects the earliest epoch with the smallest validation loss,
A patience rule with patience and minimum improvement counts a check as an improvement when its validation loss is below the best value so far by more than . It stops training after consecutive checks without improvement or when the budget of epochs runs out, whichever comes first, and returns the last checkpoint that counted as an improvement. With that is the earliest minimum among the checks actually made. The check frequency, , , the tie rule and the budget are declared before training. The saved checkpoint must be a copy of the parameters, not a reference to arrays the optimizer keeps changing, and resuming training from it also needs the optimizer state, such as momentum or Adam averages and the step count, the position in the learning rate schedule and the random number generator states. The stopping epoch is chosen on validation data, so it is a hyperparameter, and the chosen procedure is assessed on a protected test set.
In plain words Training traces a path through parameter space, and early stopping keeps the point on that path that predicted the validation cases best. The training loss usually keeps falling after that point as the network fits details of its own sample that do not carry over. Patience trades computation against the risk of quitting on a temporary plateau.
Example On the full recorded curve of the unregularized run, the selected checkpoint is epoch , and keeping the final parameters of epoch instead would cost nats of validation loss per case. A patience rule with behaves very differently depending on . The validation loss dips to at epoch and first goes below that value again at epoch . A patience of therefore stops training at epoch and returns epoch , a network with validation accuracy , worse than the accuracy of always predicting class , the more common training class. A patience of stops at epoch and returns epoch . Whether a flat stretch is temporary is known only in hindsight, which is one reason to declare a generous patience or to record the full curve when computation allows.
Check yourself
- A run records validation losses , , , , and at epochs to , and its training loss falls at every epoch. Which checkpoint does the earliest-minimum rule select on the full curve? With patience , and a check after every epoch, when does training stop and which checkpoint is returned? Is the falling training loss a reason to prefer epoch ?
Show the answer
The smallest validation loss, , occurs at epochs and , and the earliest-minimum rule breaks the tie in favor of epoch .
Under the patience rule, epochs , and each improve on the best value so far. At epoch the loss is not below the best value , so it is the first check without improvement, and epoch , with , is the second. Training stops after epoch and returns epoch . Epoch is never computed, so its loss of plays no part.
The training loss is not a reason to prefer epoch . It measures the fit to the cases the optimizer used, and it keeps falling while the validation evidence says the predictions for new cases have stopped improving.
- A layer uses inverted dropout with dropout probability . In one training pass it receives the activations , and and draws the mask . Find its outputs in that pass and in evaluation mode. Then explain what is wrong with two shortcuts, computing the validation loss with the model left in training mode, and multiplying the activations by at evaluation.
Show the answer
The keep probability is . In the training pass the kept activations are divided by and the dropped one becomes , so the outputs are , and . In evaluation mode the layer passes , and unchanged.
With the model left in training mode, every validation pass draws new masks, so the validation loss becomes a random number that describes a thinned network instead of the one that will be used, and checkpoint selection partly follows mask noise. If the network also has batch normalization, its outputs then depend on which cases share a batch, and the stored running statistics are updated with validation data.
Multiplying by at evaluation scales twice. Inverted dropout already divided by during training, so the evaluation network should use the activations as they are. Multiplying by belongs to the original form of dropout, which does not divide during training. Mixing the two conventions feeds the next layer activations at percent of the scale it saw on average during training.
- The three candidates of this page use the same data, network, seed, learning rate and budget of epochs, and each keeps its own best validation checkpoint. All losses are mean cross-entropy in evaluation mode without the penalty. A colleague concludes that regularization does not help this network. What does the evidence support, and what should be checked next?
| Candidate | Selected epoch | Training loss | Validation loss |
|---|---|---|---|
| No regularizer | |||
| Weight decay | |||
| Dropout |
Show the answer
The weight decay candidate has high training and validation losses, both close to the value of a score that always says , so within this budget it underfits. Its selected epoch is the last one, which means its validation loss was still falling when the budget ran out.
The dropout candidate trails the unregularized one by only nats per case. On these validation cases the standard error of the mean per-case difference between the two selected networks is about , more than twice the difference, and both checkpoints were chosen on these same cases. The data do not separate the two. Its selected epoch also sits at the end of the budget.
A checkpoint at the edge of the budget is a warning that the budget, not the stopping rule, ended the search. An additional run of the same three candidates with a budget of epochs, everything else unchanged, shows the effect. The unregularized network still selects epoch at , and its validation loss climbs to by epoch . The dropout network reaches at epoch , and the weight decay network is still improving at epoch , at . So the evidence supports a narrow statement. Under this seed and budget, these particular settings did not lower the selected validation loss, and with the network underfits within both budgets. It does not support a general verdict on regularization.
A sound next step declares one budget for all candidates in advance, long enough that every selected epoch falls well inside it, gives each technique a comparable search over its strength, repeats the runs over several seeds and compares on validation data. Choosing the budget after seeing these results is itself a selection, so the final claim comes from one evaluation of the chosen procedure on a protected test set.