Sub topic 17
Dropout in neural networks
This chapter assumes you can build and train a small Keras Sequential model. It also assumes you know what a validation set is and how L2 weight penalties work. Dropout is a regularisation method that works by randomly disabling units during training. Unlike L1 and L2, it does not add a term to the loss.
The idea
A large network can overfit by letting hidden units co-adapt. One unit learns to fix the errors of another, and together they memorise quirks of the training set. Dropout breaks these dependencies. On each training step, every unit in a chosen layer is set to zero with probability p (the dropout rate). The remaining units must produce a useful prediction without the others, so no unit can rely on a particular partner being present.
Each step trains a different random thinned sub-network. The full network at test time behaves like an average of the many sub-networks, similar to an ensemble. That averaging reduces variance, which is why dropout is a remedy for overfitting.
Training versus inference
Dropout behaves differently in the two phases.
- Training: a random mask zeroes about a fraction
pof the activations. - Inference: no units are dropped. The full network is used.
If the network only dropped units during training, the expected size of the next layer's input would be smaller during training than at inference. Modern libraries avoid this with inverted dropout. They divide the surviving activations by 1 - p during training, so inference needs no adjustment. The NumPy sketch below shows the mechanism.
import numpy as np
rng = np.random.default_rng(0)
activations = np.ones(10_000)
p = 0.5
mask = rng.random(activations.shape) >= p # True means the unit is kept
dropped = activations * mask / (1 - p) # inverted dropout
print(round(dropped.mean(), 2)) # close to 1.0, the same expected value
print(round(mask.mean(), 2)) # close to 0.5, the fraction keptUsing dropout in Keras
In Keras, keras.layers.Dropout(rate) is placed after the layer whose outputs you want to drop. The layer is active inside fit and inactive inside predict and evaluate, so you do not switch modes yourself. This script is self-contained. It trains the same network with and without dropout on noisy synthetic data.
import numpy as np
from tensorflow import keras
rng = np.random.default_rng(0)
X = rng.normal(size=(600, 20)).astype("float32")
y = (X[:, 0] + X[:, 1] - X[:, 2] + rng.normal(0, 1.0, size=600) > 0).astype("float32")
X_train, y_train = X[:400], y[:400]
def build(rate):
return keras.Sequential([
keras.layers.Input(shape=(20,)),
keras.layers.Dense(128, activation="relu"),
keras.layers.Dropout(rate),
keras.layers.Dense(128, activation="relu"),
keras.layers.Dropout(rate),
keras.layers.Dense(1, activation="sigmoid"),
])
for rate in (0.0, 0.5):
keras.utils.set_random_seed(0)
model = build(rate)
model.compile(optimizer="adam", loss="binary_crossentropy")
history = model.fit(X_train, y_train, validation_split=0.25,
epochs=100, batch_size=32, verbose=0)
print(rate,
round(history.history["loss"][-1], 3),
round(history.history["val_loss"][-1], 3))With rate=0.0 the training loss usually falls close to zero while the validation loss rises. The gap between the two is the overfitting signature. With rate=0.5 the training loss stays higher and the validation loss is typically lower and steadier. Exact numbers vary by version and hardware, so compare the gap, not the digits.
Choosing where and how much
| Choice | Typical guidance |
|---|---|
| Rate on dense hidden layers | 0.2 to 0.5. Start near 0.3 and tune it. |
| Rate on the input layer | Small, 0.1 to 0.2, or none. Dropping input features throws away information directly. |
| Output layer | Do not apply dropout to it. |
| Convolutional layers | Use a low rate, or `SpatialDropout2D`, which drops whole feature maps because neighbouring pixels are strongly correlated. |
| Wide layers | Tolerate higher rates. Narrow layers lose too much capacity. |
Treat the rate as a hyperparameter. Choose it by validation loss or cross-validation, using the same discipline as for the strength of an L2 penalty. A higher rate gives stronger regularisation, and too high a rate causes underfitting.
Reading the training curves
Dropout changes how you interpret the numbers Keras reports.
- The reported training loss is computed with dropout active. It is noisier and higher than the loss the same weights would give at inference.
- The validation loss is computed with dropout off. Early in training it can therefore be lower than the training loss. This is expected and does not mean validation data leaked into training.
- To measure the real train-versus-validation gap, call
model.evaluate(X_train, y_train)after training. This evaluates the training data in inference mode.
Combining dropout with other methods
Dropout is usually one part of a regularisation setup, not the whole of it.
- L2 weight decay: the two combine well, and the earlier example in this tutorial uses both. Tune them together, because each reduces capacity.
- Early stopping: dropout makes validation loss noisy, so use a larger
patience, for example 10 instead of 3. Setrestore_best_weights=Trueso the best epoch is kept. - Batch normalisation: the two interact badly in some architectures. Dropout changes the variance of activations between training and inference, and batch normalisation's running statistics were collected under the training variance. Many modern networks use only one of the two, or place dropout after the last normalisation layer.
- Data augmentation: these two also work together, and augmentation often gives larger gains on image data.
Common errors
- Leaving dropout on at inference. In Keras, calling the model directly as
model(x)runs in inference mode by default. If you callmodel(x, training=True), dropout is on and predictions are random. Do this only on purpose. - Applying dropout to a model that underfits. If training error is already high, dropout makes it worse. Fix high bias with more capacity or longer training instead.
- Too high a rate on small layers. A 16-unit layer with
rate=0.5keeps about 8 units per step, which may be too few to learn the task. - Changing the rate without retraining for longer. Dropout slows convergence. Models with dropout usually need more epochs, which is a reason to pair it with early stopping instead of a fixed epoch count.
- Expecting dropout to fix leakage or bad splits. It lowers variance. It cannot repair a validation set that overlaps with the training set.
Dropout at prediction time
Keeping dropout on at inference and averaging many stochastic predictions is called Monte Carlo dropout. The spread of the predictions gives a rough measure of uncertainty. It is an approximation, and it is not needed for ordinary regularisation.
Exercise
A network with two Dropout(0.5) layers shows a training loss of 0.62 and a validation loss of 0.48 at the end of an epoch, with both still falling. A teammate says the validation set must have leaked into training. What is a more likely explanation, and how would you check it?
Show answer
Keras computes the reported training loss with dropout active, which adds noise and raises the loss. The validation loss is computed with dropout off. A lower validation loss early in training is therefore normal. To check, call model.evaluate on the training data after the epoch, which runs in inference mode, and compare that loss to the validation loss. If the two are similar, nothing leaked. If the training loss is still far lower than the validation loss after many epochs, the model is overfitting.