Sub topic 17
Dropout, More Data, and Data Augmentation
This chapter assumes you know how a neural network is trained with gradient descent, and that you have met L2 weight decay and early stopping in earlier chapters. It covers two more ways to reduce overfitting in neural networks.
Dropout in neural networks
Dropout randomly switches off a fraction of a layer's units on each training step. The fraction is the dropout rate. With a rate of 0.5, each unit is zeroed with probability 0.5, and a new random choice is made for every batch.
This stops units from relying on specific partners. A unit cannot count on another unit being present, so it has to learn features that are useful on their own. You can also think of dropout as training many thinned networks that share weights, then averaging them at prediction time.
Dropout behaves differently in training and in inference:
- Training: units are dropped, and the surviving activations are scaled up by 1 / (1 − rate). This keeps the expected activation the same.
- Inference: no units are dropped and no scaling is needed. Keras does this for you when you call
predictorevaluate.
import numpy as np
from tensorflow import keras
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 20)).astype("float32")
y = (X[:, 0] + X[:, 1] > 0).astype("float32")
model = keras.Sequential([
keras.layers.Input(shape=(20,)),
keras.layers.Dense(64, activation="relu"),
keras.layers.Dropout(0.5),
keras.layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
model.fit(X, y, validation_split=0.2, epochs=20, verbose=0)
print(model.evaluate(X, y, verbose=0))Training loss with dropout is noisier and usually higher than validation loss at first. This is expected and is not a bug.
More data and data augmentation
Overfitting happens when a model has more capacity than the data can constrain. More real data is often the most effective remedy. A learning curve tells you whether it will help. If validation error is still falling as the training set grows, more data is worth collecting. If the curves have already flattened, more data will not help much, and you should look at model capacity or regularisation.
Collecting data is often expensive. Data augmentation creates extra training examples by applying label-preserving transformations to the data you already have. For images, these include flips, small rotations, crops, and brightness changes. For text and audio, examples include synonym swaps and added background noise.
from tensorflow import keras
augment = keras.Sequential([
keras.layers.RandomFlip("horizontal"),
keras.layers.RandomRotation(0.1),
keras.layers.RandomZoom(0.1),
])
model = keras.Sequential([
keras.layers.Input(shape=(64, 64, 3)),
augment,
keras.layers.Conv2D(16, 3, activation="relu"),
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dropout(0.3),
keras.layers.Dense(10, activation="softmax"),
])
model.summary()Keras augmentation layers are active only during training, like dropout. Each epoch therefore sees slightly different versions of each image.
Common errors
- Augmenting the validation or test set. Evaluate on unmodified data only. Otherwise your estimate no longer reflects real inputs.
- Transformations that change the label. Flipping a "6" vertically can make it look like a "9", and flipping text breaks it.
- Augmenting before splitting. Copies of one original image can land in both training and validation sets. This is data leakage. Split first, then augment the training portion only.
Exercise
A network has training accuracy 99% and validation accuracy 82%. You add Dropout(0.5) after every layer, including the narrow output layer, and both accuracies drop to about 70%. What most likely went wrong, and what would you change?
Show answer
The rate is too high and is applied in too many places, so the model now underfits (high bias). Training accuracy fell along with validation accuracy, which signals this. Remove dropout from the output layer, lower the rate to about 0.2 to 0.3 on the wide hidden layers, and compare validation accuracy again.