Dropout helps reduce overfitting by randomly setting a fraction of a layer’s activations to zero during training. The dropout rate controls that fraction; typical values range from 0.2 to 0.5. section 5.4.4
Dropping activations
A layer output such as [0.2, 0.5, 1.3, 0.8, 1.1] might become [0, 0.5, 1.3, 0, 1.1]. The zeroed entries are chosen randomly. In an IMDb review classifier, add layers.Dropout(0.5) after each hidden Dense layer to apply this idea in Keras. section 5.4.4
Listing 5.15 Adding dropout to the IMDB model
model = keras.Sequential( [ layers.Dense(16, activation="relu"), layers.Dropout(0.5), layers.Dense(16, activation="relu"), layers.Dropout(0.5), layers.Dense(1, activation="sigmoid"), ] ) model.compile( optimizer="rmsprop", loss="binary_crossentropy", metrics=["accuracy"], ) history_dropout = model.fit( train_data, train_labels, epochs=20, batch_size=512, validation_split=0.4, )
See the complete Keras classifier with dropout after both hidden layers. section 5.4.4
At inference time, dropout does not randomly remove activations. Scaling compensates for the difference between training and inference: with a rate of 0.5, one approach halves the output at test time. Another scales the surviving training activations up by dividing by 0.5 and leaves the output unchanged at test time. section 5.4.4
layer_output *= np.random.randint(low=0, high=2, size=layer_output.shape) #1 layer_output /= 0.5 #2
See the NumPy version that applies a random mask and scaling during training. section 5.4.4
For recurrent networks, use the same dropout mask at every timestep. A mask that changes across timesteps can disrupt the learning error propagated through time. Keras recurrent layers provide dropout for input units and recurrent_dropout for recurrent units. section 13.3.4
Listing 13.22 Training and evaluating a dropout-regularized LSTM
inputs = keras.Input(shape=(sequence_length, raw_data.shape[-1])) x = layers.LSTM(32, recurrent_dropout=0.25)(inputs) x = layers.Dropout(0.5)(x) #1 outputs = layers.Dense(1)(x) model = keras.Model(inputs, outputs) callbacks = [ keras.callbacks.ModelCheckpoint( "jena_lstm_dropout.keras", save_best_only=True ) ] model.compile(optimizer="adam", loss="mse", metrics=["mae"]) history = model.fit( train_dataset, epochs=50, validation_data=val_dataset, callbacks=callbacks, )
See an LSTM forecasting model with recurrent dropout and a separate dropout layer. section 13.3.4
Try dropout once a model can overfit, then compare training and validation performance as you tune it. Keep the test set for final evaluation: repeated tuning against validation data can itself lead to overfitting the validation process. section 6.2.5











