Explore overfitting and underfitting

View on TensorFlow.org Run in Google Colab View source on GitHub

As always, the code in this example will use the tf.keras API, which you can learn more about in the TensorFlow Keras guide.

In both of the previous examples—classifying movie reviews, and predicting housing prices—we saw that the accuracy of our model on the validation data would peak after training for a number of epochs, and would then start decreasing.

In other words, our model would overfit to the training data. Learning how to deal with overfitting is important. Although it's often possible to achieve high accuracy on the training set, what we really want is to develop models that generalize well to a testing data (or data they haven't seen before).

The opposite of overfitting is underfitting. Underfitting occurs when there is still room for improvement on the test data. This can happen for a number of reasons: If the model is not powerful enough, is over-regularized, or has simply not been trained long enough. This means the network has not learned the relevant patterns in the training data.

If you train for too long though, the model will start to overfit and learn patterns from the training data that don't generalize to the test data. We need to strike a balance. Understanding how to train for an appropriate number of epochs as we'll explore below is a useful skill.

To prevent overfitting, the best solution is to use more training data. A model trained on more data will naturally generalize better. When that is no longer possible, the next best solution is to use techniques like regularization. These place constraints on the quantity and type of information your model can store. If a network can only afford to memorize a small number of patterns, the optimization process will force it to focus on the most prominent patterns, which have a better chance of generalizing well.

In this notebook, we'll explore two common regularization techniques—weight regularization and dropout—and use them to improve our IMDB movie review classification notebook.

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)
1.10.1

Download the IMDB dataset

Rather than using an embedding as in the previous notebook, here we will multi-hot encode the sentences. This model will quickly overfit to the training set. It will be used to demonstrate when overfitting occurs, and how to fight it.

Multi-hot-encoding our lists means turning them into vectors of 0s and 1s. Concretely, this would mean for instance turning the sequence [3, 5] into a 10,000-dimensional vector that would be all-zeros except for indices 3 and 5, which would be ones.

NUM_WORDS = 10000

(train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words=NUM_WORDS)

def multi_hot_sequences(sequences, dimension):
    # Create an all-zero matrix of shape (len(sequences), dimension)
    results = np.zeros((len(sequences), dimension))
    for i, word_indices in enumerate(sequences):
        results[i, word_indices] = 1.0  # set specific indices of results[i] to 1s
    return results


train_data = multi_hot_sequences(train_data, dimension=NUM_WORDS)
test_data = multi_hot_sequences(test_data, dimension=NUM_WORDS)
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/imdb.npz
17465344/17464789 [==============================] - 0s 0us/step

Let's look at one of the resulting multi-hot vectors. The word indices are sorted by frequency, so it is expected that there are more 1-values near index zero, as we can see in this plot:

plt.plot(train_data[0])
[]

png

Demonstrate overfitting

The simplest way to prevent overfitting is to reduce the size of the model, i.e. the number of learnable parameters in the model (which is determined by the number of layers and the number of units per layer). In deep learning, the number of learnable parameters in a model is often referred to as the model's "capacity". Intuitively, a model with more parameters will have more "memorization capacity" and therefore will be able to easily learn a perfect dictionary-like mapping between training samples and their targets, a mapping without any generalization power, but this would be useless when making predictions on previously unseen data.

Always keep this in mind: deep learning models tend to be good at fitting to the training data, but the real challenge is generalization, not fitting.

On the other hand, if the network has limited memorization resources, it will not be able to learn the mapping as easily. To minimize its loss, it will have to learn compressed representations that have more predictive power. At the same time, if you make your model too small, it will have difficulty fitting to the training data. There is a balance between "too much capacity" and "not enough capacity".

Unfortunately, there is no magical formula to determine the right size or architecture of your model (in terms of the number of layers, or what the right size for each layer). You will have to experiment using a series of different architectures.

To find an appropriate model size, it's best to start with relatively few layers and parameters, then begin increasing the size of the layers or adding new layers until you see diminishing returns on the validation loss. Let's try this on our movie review classification network.

We'll create a simple model using only Dense layers as a baseline, then create smaller and larger versions, and compare them.

Create a baseline model

baseline_model = keras.Sequential([
    # `input_shape` is only required here so that `.summary` works. 
    keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),
    keras.layers.Dense(16, activation=tf.nn.relu),
    keras.layers.Dense(1, activation=tf.nn.sigmoid)
])

baseline_model.compile(optimizer='adam',
                       loss='binary_crossentropy',
                       metrics=['accuracy', 'binary_crossentropy'])

baseline_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 16)                160016    
_________________________________________________________________
dense_1 (Dense)              (None, 16)                272       
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 17        
=================================================================
Total params: 160,305
Trainable params: 160,305
Non-trainable params: 0
_________________________________________________________________
baseline_history = baseline_model.fit(train_data,
                                      train_labels,
                                      epochs=20,
                                      batch_size=512,
                                      validation_data=(test_data, test_labels),
                                      verbose=2)
Train on 25000 samples, validate on 25000 samples
Epoch 1/20
 - 3s - loss: 0.4892 - acc: 0.8047 - binary_crossentropy: 0.4892 - val_loss: 0.3365 - val_acc: 0.8740 - val_binary_crossentropy: 0.3365
Epoch 2/20
 - 3s - loss: 0.2488 - acc: 0.9087 - binary_crossentropy: 0.2488 - val_loss: 0.2857 - val_acc: 0.8851 - val_binary_crossentropy: 0.2857
Epoch 3/20
 - 3s - loss: 0.1830 - acc: 0.9364 - binary_crossentropy: 0.1830 - val_loss: 0.2893 - val_acc: 0.8860 - val_binary_crossentropy: 0.2893
Epoch 4/20
 - 3s - loss: 0.1449 - acc: 0.9514 - binary_crossentropy: 0.1449 - val_loss: 0.3132 - val_acc: 0.8788 - val_binary_crossentropy: 0.3132
Epoch 5/20
 - 3s - loss: 0.1176 - acc: 0.9613 - binary_crossentropy: 0.1176 - val_loss: 0.3404 - val_acc: 0.8744 - val_binary_crossentropy: 0.3404
Epoch 6/20
 - 3s - loss: 0.0942 - acc: 0.9716 - binary_crossentropy: 0.0942 - val_loss: 0.3731 - val_acc: 0.8715 - val_binary_crossentropy: 0.3731
Epoch 7/20
 - 3s - loss: 0.0748 - acc: 0.9796 - binary_crossentropy: 0.0748 - val_loss: 0.4255 - val_acc: 0.8621 - val_binary_crossentropy: 0.4255
Epoch 8/20
 - 3s - loss: 0.0591 - acc: 0.9847 - binary_crossentropy: 0.0591 - val_loss: 0.4525 - val_acc: 0.8634 - val_binary_crossentropy: 0.4525
Epoch 9/20
 - 3s - loss: 0.0450 - acc: 0.9904 - binary_crossentropy: 0.0450 - val_loss: 0.4934 - val_acc: 0.8612 - val_binary_crossentropy: 0.4934
Epoch 10/20
 - 3s - loss: 0.0339 - acc: 0.9944 - binary_crossentropy: 0.0339 - val_loss: 0.5402 - val_acc: 0.8584 - val_binary_crossentropy: 0.5402
Epoch 11/20
 - 3s - loss: 0.0254 - acc: 0.9968 - binary_crossentropy: 0.0254 - val_loss: 0.5762 - val_acc: 0.8581 - val_binary_crossentropy: 0.5762
Epoch 12/20
 - 3s - loss: 0.0185 - acc: 0.9980 - binary_crossentropy: 0.0185 - val_loss: 0.6190 - val_acc: 0.8565 - val_binary_crossentropy: 0.6190
Epoch 13/20
 - 3s - loss: 0.0133 - acc: 0.9989 - binary_crossentropy: 0.0133 - val_loss: 0.6566 - val_acc: 0.8571 - val_binary_crossentropy: 0.6566
Epoch 14/20
 - 3s - loss: 0.0097 - acc: 0.9996 - binary_crossentropy: 0.0097 - val_loss: 0.6954 - val_acc: 0.8554 - val_binary_crossentropy: 0.6954
Epoch 15/20
 - 3s - loss: 0.0071 - acc: 0.9998 - binary_crossentropy: 0.0071 - val_loss: 0.7263 - val_acc: 0.8549 - val_binary_crossentropy: 0.7263
Epoch 16/20
 - 3s - loss: 0.0055 - acc: 1.0000 - binary_crossentropy: 0.0055 - val_loss: 0.7558 - val_acc: 0.8549 - val_binary_crossentropy: 0.7558
Epoch 17/20
 - 3s - loss: 0.0043 - acc: 1.0000 - binary_crossentropy: 0.0043 - val_loss: 0.7817 - val_acc: 0.8543 - val_binary_crossentropy: 0.7817
Epoch 18/20
 - 3s - loss: 0.0035 - acc: 1.0000 - binary_crossentropy: 0.0035 - val_loss: 0.8078 - val_acc: 0.8544 - val_binary_crossentropy: 0.8078
Epoch 19/20
 - 3s - loss: 0.0029 - acc: 1.0000 - binary_crossentropy: 0.0029 - val_loss: 0.8292 - val_acc: 0.8542 - val_binary_crossentropy: 0.8292
Epoch 20/20
 - 3s - loss: 0.0024 - acc: 1.0000 - binary_crossentropy: 0.0024 - val_loss: 0.8515 - val_acc: 0.8534 - val_binary_crossentropy: 0.8515

Create a smaller model

Let's create a model with less hidden units to compare against the baseline model that we just created:

smaller_model = keras.Sequential([
    keras.layers.Dense(4, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),
    keras.layers.Dense(4, activation=tf.nn.relu),
    keras.layers.Dense(1, activation=tf.nn.sigmoid)
])

smaller_model.compile(optimizer='adam',
                loss='binary_crossentropy',
                metrics=['accuracy', 'binary_crossentropy'])

smaller_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_3 (Dense)              (None, 4)                 40004     
_________________________________________________________________
dense_4 (Dense)              (None, 4)                 20        
_________________________________________________________________
dense_5 (Dense)              (None, 1)                 5         
=================================================================
Total params: 40,029
Trainable params: 40,029
Non-trainable params: 0
_________________________________________________________________

And train the model using the same data:

smaller_history = smaller_model.fit(train_data,
                                    train_labels,
                                    epochs=20,
                                    batch_size=512,
                                    validation_data=(test_data, test_labels),
                                    verbose=2)
Train on 25000 samples, validate on 25000 samples
Epoch 1/20
 - 3s - loss: 0.5223 - acc: 0.7789 - binary_crossentropy: 0.5223 - val_loss: 0.3878 - val_acc: 0.8698 - val_binary_crossentropy: 0.3878
Epoch 2/20
 - 3s - loss: 0.2993 - acc: 0.9027 - binary_crossentropy: 0.2993 - val_loss: 0.3103 - val_acc: 0.8838 - val_binary_crossentropy: 0.3103
Epoch 3/20
 - 3s - loss: 0.2272 - acc: 0.9256 - binary_crossentropy: 0.2272 - val_loss: 0.2872 - val_acc: 0.8882 - val_binary_crossentropy: 0.2872
Epoch 4/20
 - 3s - loss: 0.1884 - acc: 0.9381 - binary_crossentropy: 0.1884 - val_loss: 0.2852 - val_acc: 0.8868 - val_binary_crossentropy: 0.2852
Epoch 5/20
 - 3s - loss: 0.1626 - acc: 0.9490 - binary_crossentropy: 0.1626 - val_loss: 0.2914 - val_acc: 0.8830 - val_binary_crossentropy: 0.2914
Epoch 6/20
 - 3s - loss: 0.1428 - acc: 0.9549 - binary_crossentropy: 0.1428 - val_loss: 0.2988 - val_acc: 0.8814 - val_binary_crossentropy: 0.2988
Epoch 7/20
 - 3s - loss: 0.1263 - acc: 0.9622 - binary_crossentropy: 0.1263 - val_loss: 0.3112 - val_acc: 0.8788 - val_binary_crossentropy: 0.3112
Epoch 8/20
 - 3s - loss: 0.1132 - acc: 0.9672 - binary_crossentropy: 0.1132 - val_loss: 0.3259 - val_acc: 0.8758 - val_binary_crossentropy: 0.3259
Epoch 9/20
 - 3s - loss: 0.1017 - acc: 0.9705 - binary_crossentropy: 0.1017 - val_loss: 0.3405 - val_acc: 0.8739 - val_binary_crossentropy: 0.3405
Epoch 10/20
 - 3s - loss: 0.0914 - acc: 0.9746 - binary_crossentropy: 0.0914 - val_loss: 0.3565 - val_acc: 0.8719 - val_binary_crossentropy: 0.3565
Epoch 11/20
 - 3s - loss: 0.0826 - acc: 0.9781 - binary_crossentropy: 0.0826 - val_loss: 0.3752 - val_acc: 0.8696 - val_binary_crossentropy: 0.3752
Epoch 12/20
 - 3s - loss: 0.0739 - acc: 0.9817 - binary_crossentropy: 0.0739 - val_loss: 0.3936 - val_acc: 0.8675 - val_binary_crossentropy: 0.3936
Epoch 13/20
 - 3s - loss: 0.0661 - acc: 0.9848 - binary_crossentropy: 0.0661 - val_loss: 0.4120 - val_acc: 0.8660 - val_binary_crossentropy: 0.4120
Epoch 14/20
 - 3s - loss: 0.0594 - acc: 0.9872 - binary_crossentropy: 0.0594 - val_loss: 0.4316 - val_acc: 0.8646 - val_binary_crossentropy: 0.4316
Epoch 15/20
 - 3s - loss: 0.0531 - acc: 0.9901 - binary_crossentropy: 0.0531 - val_loss: 0.4528 - val_acc: 0.8637 - val_binary_crossentropy: 0.4528
Epoch 16/20
 - 3s - loss: 0.0478 - acc: 0.9914 - binary_crossentropy: 0.0478 - val_loss: 0.4749 - val_acc: 0.8621 - val_binary_crossentropy: 0.4749
Epoch 17/20
 - 3s - loss: 0.0433 - acc: 0.9927 - binary_crossentropy: 0.0433 - val_loss: 0.4979 - val_acc: 0.8608 - val_binary_crossentropy: 0.4979
Epoch 18/20
 - 3s - loss: 0.0382 - acc: 0.9941 - binary_crossentropy: 0.0382 - val_loss: 0.5194 - val_acc: 0.8585 - val_binary_crossentropy: 0.5194
Epoch 19/20
 - 3s - loss: 0.0339 - acc: 0.9953 - binary_crossentropy: 0.0339 - val_loss: 0.5396 - val_acc: 0.8578 - val_binary_crossentropy: 0.5396
Epoch 20/20
 - 3s - loss: 0.0303 - acc: 0.9962 - binary_crossentropy: 0.0303 - val_loss: 0.5625 - val_acc: 0.8577 - val_binary_crossentropy: 0.5625

Create a bigger model

As an exercise, you can create an even larger model, and see how quickly it begins overfitting. Next, let's add to this benchmark a network that has much more capacity, far more than the problem would warrant:

bigger_model = keras.models.Sequential([
    keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),
    keras.layers.Dense(512, activation=tf.nn.relu),
    keras.layers.Dense(1, activation=tf.nn.sigmoid)
])

bigger_model.compile(optimizer='adam',
                     loss='binary_crossentropy',
                     metrics=['accuracy','binary_crossentropy'])

bigger_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_6 (Dense)              (None, 512)               5120512   
_________________________________________________________________
dense_7 (Dense)              (None, 512)               262656    
_________________________________________________________________
dense_8 (Dense)              (None, 1)                 513       
=================================================================
Total params: 5,383,681
Trainable params: 5,383,681
Non-trainable params: 0
_________________________________________________________________

And, again, train the model using the same data:

bigger_history = bigger_model.fit(train_data, train_labels,
                                  epochs=20,
                                  batch_size=512,
                                  validation_data=(test_data, test_labels),
                                  verbose=2)
Train on 25000 samples, validate on 25000 samples
Epoch 1/20
 - 5s - loss: 0.3402 - acc: 0.8567 - binary_crossentropy: 0.3402 - val_loss: 0.2948 - val_acc: 0.8800 - val_binary_crossentropy: 0.2948
Epoch 2/20
 - 5s - loss: 0.1336 - acc: 0.9512 - binary_crossentropy: 0.1336 - val_loss: 0.3539 - val_acc: 0.8647 - val_binary_crossentropy: 0.3539
Epoch 3/20
 - 5s - loss: 0.0412 - acc: 0.9887 - binary_crossentropy: 0.0412 - val_loss: 0.4402 - val_acc: 0.8690 - val_binary_crossentropy: 0.4402
Epoch 4/20
 - 5s - loss: 0.0068 - acc: 0.9989 - binary_crossentropy: 0.0068 - val_loss: 0.5875 - val_acc: 0.8705 - val_binary_crossentropy: 0.5875
Epoch 5/20
 - 5s - loss: 8.4845e-04 - acc: 1.0000 - binary_crossentropy: 8.4845e-04 - val_loss: 0.6820 - val_acc: 0.8719 - val_binary_crossentropy: 0.6820
Epoch 6/20
 - 5s - loss: 2.0660e-04 - acc: 1.0000 - binary_crossentropy: 2.0660e-04 - val_loss: 0.7224 - val_acc: 0.8720 - val_binary_crossentropy: 0.7224
Epoch 7/20
 - 5s - loss: 1.2424e-04 - acc: 1.0000 - binary_crossentropy: 1.2424e-04 - val_loss: 0.7492 - val_acc: 0.8717 - val_binary_crossentropy: 0.7492
Epoch 8/20
 - 5s - loss: 8.8397e-05 - acc: 1.0000 - binary_crossentropy: 8.8397e-05 - val_loss: 0.7692 - val_acc: 0.8716 - val_binary_crossentropy: 0.7692
Epoch 9/20
 - 5s - loss: 6.7112e-05 - acc: 1.0000 - binary_crossentropy: 6.7112e-05 - val_loss: 0.7863 - val_acc: 0.8716 - val_binary_crossentropy: 0.7863
Epoch 10/20
 - 5s - loss: 5.2867e-05 - acc: 1.0000 - binary_crossentropy: 5.2867e-05 - val_loss: 0.8001 - val_acc: 0.8719 - val_binary_crossentropy: 0.8001
Epoch 11/20
 - 5s - loss: 4.2732e-05 - acc: 1.0000 - binary_crossentropy: 4.2732e-05 - val_loss: 0.8132 - val_acc: 0.8719 - val_binary_crossentropy: 0.8132
Epoch 12/20
 - 5s - loss: 3.5089e-05 - acc: 1.0000 - binary_crossentropy: 3.5089e-05 - val_loss: 0.8249 - val_acc: 0.8718 - val_binary_crossentropy: 0.8249
Epoch 13/20
 - 5s - loss: 2.9329e-05 - acc: 1.0000 - binary_crossentropy: 2.9329e-05 - val_loss: 0.8351 - val_acc: 0.8717 - val_binary_crossentropy: 0.8351
Epoch 14/20
 - 5s - loss: 2.4808e-05 - acc: 1.0000 - binary_crossentropy: 2.4808e-05 - val_loss: 0.8451 - val_acc: 0.8717 - val_binary_crossentropy: 0.8451
Epoch 15/20
 - 5s - loss: 2.1180e-05 - acc: 1.0000 - binary_crossentropy: 2.1180e-05 - val_loss: 0.8541 - val_acc: 0.8718 - val_binary_crossentropy: 0.8541
Epoch 16/20
 - 5s - loss: 1.8254e-05 - acc: 1.0000 - binary_crossentropy: 1.8254e-05 - val_loss: 0.8623 - val_acc: 0.8716 - val_binary_crossentropy: 0.8623
Epoch 17/20
 - 5s - loss: 1.5842e-05 - acc: 1.0000 - binary_crossentropy: 1.5842e-05 - val_loss: 0.8712 - val_acc: 0.8718 - val_binary_crossentropy: 0.8712
Epoch 18/20
 - 5s - loss: 1.3885e-05 - acc: 1.0000 - binary_crossentropy: 1.3885e-05 - val_loss: 0.8785 - val_acc: 0.8717 - val_binary_crossentropy: 0.8785
Epoch 19/20
 - 5s - loss: 1.2194e-05 - acc: 1.0000 - binary_crossentropy: 1.2194e-05 - val_loss: 0.8857 - val_acc: 0.8716 - val_binary_crossentropy: 0.8857
Epoch 20/20
 - 5s - loss: 1.0799e-05 - acc: 1.0000 - binary_crossentropy: 1.0799e-05 - val_loss: 0.8930 - val_acc: 0.8719 - val_binary_crossentropy: 0.8930

Plot the training and validation loss

The solid lines show the training loss, and the dashed lines show the validation loss (remember: a lower validation loss indicates a better model). Here, the smaller network begins overfitting later than the baseline model (after 6 epochs rather than 4) and its performance degrades much more slowly once it starts overfitting.

def plot_history(histories, key='binary_crossentropy'):
  plt.figure(figsize=(16,10))
    
  for name, history in histories:
    val = plt.plot(history.epoch, history.history['val_'+key],
                   '--', label=name.title()+' Val')
    plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
             label=name.title()+' Train')

  plt.xlabel('Epochs')
  plt.ylabel(key.replace('_',' ').title())
  plt.legend()

  plt.xlim([0,max(history.epoch)])


plot_history([('baseline', baseline_history),
              ('smaller', smaller_history),
              ('bigger', bigger_history)])

png

Notice that the larger network begins overfitting almost right away, after just one epoch, and overfits much more severely. The more capacity the network has, the quicker it will be able to model the training data (resulting in a low training loss), but the more susceptible it is to overfitting (resulting in a large difference between the training and validation loss).

Strategies

Add weight regularization

You may be familiar with Occam's Razor principle: given two explanations for something, the explanation most likely to be correct is the "simplest" one, the one that makes the least amount of assumptions. This also applies to the models learned by neural networks: given some training data and a network architecture, there are multiple sets of weights values (multiple models) that could explain the data, and simpler models are less likely to overfit than complex ones.

A "simple model" in this context is a model where the distribution of parameter values has less entropy (or a model with fewer parameters altogether, as we saw in the section above). Thus a common way to mitigate overfitting is to put constraints on the complexity of a network by forcing its weights only to take small values, which makes the distribution of weight values more "regular". This is called "weight regularization", and it is done by adding to the loss function of the network a cost associated with having large weights. This cost comes in two flavors:

  • L1 regularization, where the cost added is proportional to the absolute value of the weights coefficients (i.e. to what is called the "L1 norm" of the weights).

  • L2 regularization, where the cost added is proportional to the square of the value of the weights coefficients (i.e. to what is called the "L2 norm" of the weights). L2 regularization is also called weight decay in the context of neural networks. Don't let the different name confuse you: weight decay is mathematically the exact same as L2 regularization.

In tf.keras, weight regularization is added by passing weight regularizer instances to layers as keyword arguments. Let's add L2 weight regularization now.

l2_model = keras.models.Sequential([
    keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),
                       activation=tf.nn.relu, input_shape=(NUM_WORDS,)),
    keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),
                       activation=tf.nn.relu),
    keras.layers.Dense(1, activation=tf.nn.sigmoid)
])

l2_model.compile(optimizer='adam',
                 loss='binary_crossentropy',
                 metrics=['accuracy', 'binary_crossentropy'])

l2_model_history = l2_model.fit(train_data, train_labels,
                                epochs=20,
                                batch_size=512,
                                validation_data=(test_data, test_labels),
                                verbose=2)
Train on 25000 samples, validate on 25000 samples
Epoch 1/20
 - 3s - loss: 0.5577 - acc: 0.8056 - binary_crossentropy: 0.5191 - val_loss: 0.4066 - val_acc: 0.8742 - val_binary_crossentropy: 0.3652
Epoch 2/20
 - 3s - loss: 0.3258 - acc: 0.9055 - binary_crossentropy: 0.2786 - val_loss: 0.3412 - val_acc: 0.8873 - val_binary_crossentropy: 0.2898
Epoch 3/20
 - 3s - loss: 0.2698 - acc: 0.9240 - binary_crossentropy: 0.2157 - val_loss: 0.3382 - val_acc: 0.8874 - val_binary_crossentropy: 0.2822
Epoch 4/20
 - 3s - loss: 0.2442 - acc: 0.9358 - binary_crossentropy: 0.1866 - val_loss: 0.3455 - val_acc: 0.8842 - val_binary_crossentropy: 0.2870
Epoch 5/20
 - 3s - loss: 0.2303 - acc: 0.9412 - binary_crossentropy: 0.1704 - val_loss: 0.3577 - val_acc: 0.8804 - val_binary_crossentropy: 0.2970
Epoch 6/20
 - 3s - loss: 0.2176 - acc: 0.9469 - binary_crossentropy: 0.1563 - val_loss: 0.3680 - val_acc: 0.8786 - val_binary_crossentropy: 0.3065
Epoch 7/20
 - 3s - loss: 0.2105 - acc: 0.9500 - binary_crossentropy: 0.1481 - val_loss: 0.3820 - val_acc: 0.8746 - val_binary_crossentropy: 0.3190
Epoch 8/20
 - 3s - loss: 0.2016 - acc: 0.9538 - binary_crossentropy: 0.1379 - val_loss: 0.3876 - val_acc: 0.8743 - val_binary_crossentropy: 0.3239
Epoch 9/20
 - 3s - loss: 0.1960 - acc: 0.9554 - binary_crossentropy: 0.1320 - val_loss: 0.4011 - val_acc: 0.8721 - val_binary_crossentropy: 0.3366
Epoch 10/20
 - 3s - loss: 0.1939 - acc: 0.9566 - binary_crossentropy: 0.1289 - val_loss: 0.4192 - val_acc: 0.8682 - val_binary_crossentropy: 0.3538
Epoch 11/20
 - 3s - loss: 0.1888 - acc: 0.9585 - binary_crossentropy: 0.1230 - val_loss: 0.4226 - val_acc: 0.8683 - val_binary_crossentropy: 0.3562
Epoch 12/20
 - 3s - loss: 0.1839 - acc: 0.9596 - binary_crossentropy: 0.1176 - val_loss: 0.4476 - val_acc: 0.8636 - val_binary_crossentropy: 0.3811
Epoch 13/20
 - 3s - loss: 0.1836 - acc: 0.9593 - binary_crossentropy: 0.1160 - val_loss: 0.4496 - val_acc: 0.8656 - val_binary_crossentropy: 0.3817
Epoch 14/20
 - 3s - loss: 0.1738 - acc: 0.9644 - binary_crossentropy: 0.1059 - val_loss: 0.4596 - val_acc: 0.8619 - val_binary_crossentropy: 0.3921
Epoch 15/20
 - 3s - loss: 0.1680 - acc: 0.9663 - binary_crossentropy: 0.1005 - val_loss: 0.4737 - val_acc: 0.8620 - val_binary_crossentropy: 0.4060
Epoch 16/20
 - 3s - loss: 0.1646 - acc: 0.9680 - binary_crossentropy: 0.0966 - val_loss: 0.4885 - val_acc: 0.8596 - val_binary_crossentropy: 0.4203
Epoch 17/20
 - 3s - loss: 0.1627 - acc: 0.9682 - binary_crossentropy: 0.0945 - val_loss: 0.5006 - val_acc: 0.8579 - val_binary_crossentropy: 0.4319
Epoch 18/20
 - 3s - loss: 0.1611 - acc: 0.9679 - binary_crossentropy: 0.0920 - val_loss: 0.5182 - val_acc: 0.8566 - val_binary_crossentropy: 0.4486
Epoch 19/20
 - 3s - loss: 0.1582 - acc: 0.9689 - binary_crossentropy: 0.0883 - val_loss: 0.5269 - val_acc: 0.8589 - val_binary_crossentropy: 0.4568
Epoch 20/20
 - 3s - loss: 0.1566 - acc: 0.9706 - binary_crossentropy: 0.0859 - val_loss: 0.5406 - val_acc: 0.8546 - val_binary_crossentropy: 0.4696

l2(0.001) means that every coefficient in the weight matrix of the layer will add 0.001 * weight_coefficient_value**2 to the total loss of the network. Note that because this penalty is only added at training time, the loss for this network will be much higher at training than at test time.

Here's the impact of our L2 regularization penalty:

plot_history([('baseline', baseline_history),
              ('l2', l2_model_history)])

png

As you can see, the L2 regularized model has become much more resistant to overfitting than the baseline model, even though both models have the same number of parameters.

Add dropout

Dropout is one of the most effective and most commonly used regularization techniques for neural networks, developed by Hinton and his students at the University of Toronto. Dropout, applied to a layer, consists of randomly "dropping out" (i.e. set to zero) a number of output features of the layer during training. Let's say a given layer would normally have returned a vector [0.2, 0.5, 1.3, 0.8, 1.1] for a given input sample during training; after applying dropout, this vector will have a few zero entries distributed at random, e.g. [0, 0.5, 1.3, 0, 1.1]. The "dropout rate" is the fraction of the features that are being zeroed-out; it is usually set between 0.2 and 0.5. At test time, no units are dropped out, and instead the layer's output values are scaled down by a factor equal to the dropout rate, so as to balance for the fact that more units are active than at training time.

In tf.keras you can introduce dropout in a network via the Dropout layer, which gets applied to the output of layer right before.

Let's add two Dropout layers in our IMDB network to see how well they do at reducing overfitting:

dpt_model = keras.models.Sequential([
    keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(16, activation=tf.nn.relu),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(1, activation=tf.nn.sigmoid)
])

dpt_model.compile(optimizer='adam',
                  loss='binary_crossentropy',
                  metrics=['accuracy','binary_crossentropy'])

dpt_model_history = dpt_model.fit(train_data, train_labels,
                                  epochs=20,
                                  batch_size=512,
                                  validation_data=(test_data, test_labels),
                                  verbose=2)

Train on 25000 samples, validate on 25000 samples
Epoch 1/20
 - 3s - loss: 0.6325 - acc: 0.6321 - binary_crossentropy: 0.6325 - val_loss: 0.5171 - val_acc: 0.8483 - val_binary_crossentropy: 0.5171
Epoch 2/20
 - 3s - loss: 0.4804 - acc: 0.8014 - binary_crossentropy: 0.4804 - val_loss: 0.3664 - val_acc: 0.8813 - val_binary_crossentropy: 0.3664
Epoch 3/20
 - 3s - loss: 0.3717 - acc: 0.8690 - binary_crossentropy: 0.3717 - val_loss: 0.3026 - val_acc: 0.8862 - val_binary_crossentropy: 0.3026
Epoch 4/20
 - 3s - loss: 0.3057 - acc: 0.8962 - binary_crossentropy: 0.3057 - val_loss: 0.2867 - val_acc: 0.8893 - val_binary_crossentropy: 0.2867
Epoch 5/20
 - 3s - loss: 0.2646 - acc: 0.9128 - binary_crossentropy: 0.2646 - val_loss: 0.2783 - val_acc: 0.8870 - val_binary_crossentropy: 0.2783
Epoch 6/20
 - 3s - loss: 0.2313 - acc: 0.9247 - binary_crossentropy: 0.2313 - val_loss: 0.2950 - val_acc: 0.8860 - val_binary_crossentropy: 0.2950
Epoch 7/20
 - 3s - loss: 0.2036 - acc: 0.9363 - binary_crossentropy: 0.2036 - val_loss: 0.3056 - val_acc: 0.8856 - val_binary_crossentropy: 0.3056
Epoch 8/20
 - 3s - loss: 0.1871 - acc: 0.9414 - binary_crossentropy: 0.1871 - val_loss: 0.3208 - val_acc: 0.8837 - val_binary_crossentropy: 0.3208
Epoch 9/20
 - 3s - loss: 0.1720 - acc: 0.9458 - binary_crossentropy: 0.1720 - val_loss: 0.3350 - val_acc: 0.8830 - val_binary_crossentropy: 0.3350
Epoch 10/20
 - 3s - loss: 0.1561 - acc: 0.9501 - binary_crossentropy: 0.1561 - val_loss: 0.3495 - val_acc: 0.8819 - val_binary_crossentropy: 0.3495
Epoch 11/20
 - 3s - loss: 0.1425 - acc: 0.9553 - binary_crossentropy: 0.1425 - val_loss: 0.3594 - val_acc: 0.8800 - val_binary_crossentropy: 0.3594
Epoch 12/20
 - 3s - loss: 0.1346 - acc: 0.9580 - binary_crossentropy: 0.1346 - val_loss: 0.3786 - val_acc: 0.8780 - val_binary_crossentropy: 0.3786
Epoch 13/20
 - 3s - loss: 0.1238 - acc: 0.9626 - binary_crossentropy: 0.1238 - val_loss: 0.3990 - val_acc: 0.8782 - val_binary_crossentropy: 0.3990
Epoch 14/20
 - 3s - loss: 0.1156 - acc: 0.9632 - binary_crossentropy: 0.1156 - val_loss: 0.4132 - val_acc: 0.8765 - val_binary_crossentropy: 0.4132
Epoch 15/20
 - 3s - loss: 0.1079 - acc: 0.9685 - binary_crossentropy: 0.1079 - val_loss: 0.4554 - val_acc: 0.8761 - val_binary_crossentropy: 0.4554
Epoch 16/20
 - 3s - loss: 0.1033 - acc: 0.9687 - binary_crossentropy: 0.1033 - val_loss: 0.4588 - val_acc: 0.8759 - val_binary_crossentropy: 0.4588
Epoch 17/20
 - 3s - loss: 0.0967 - acc: 0.9692 - binary_crossentropy: 0.0967 - val_loss: 0.4907 - val_acc: 0.8746 - val_binary_crossentropy: 0.4907
Epoch 18/20
 - 3s - loss: 0.0918 - acc: 0.9717 - binary_crossentropy: 0.0918 - val_loss: 0.4882 - val_acc: 0.8757 - val_binary_crossentropy: 0.4882
Epoch 19/20
 - 3s - loss: 0.0890 - acc: 0.9718 - binary_crossentropy: 0.0890 - val_loss: 0.5233 - val_acc: 0.8752 - val_binary_crossentropy: 0.5233
Epoch 20/20
 - 3s - loss: 0.0826 - acc: 0.9737 - binary_crossentropy: 0.0826 - val_loss: 0.5554 - val_acc: 0.8754 - val_binary_crossentropy: 0.5554
plot_history([('baseline', baseline_history),
              ('dropout', dpt_model_history)])

png

Adding dropout is a clear improvement over the baseline model.

To recap: here the most common ways to prevent overfitting in neural networks:

  • Get more training data.
  • Reduce the capacity of the network.
  • Add weight regularization.
  • Add dropout.

And two important approaches not covered in this guide are data-augmentation and batch normalization.

#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.