Explore overfitting and underfitting

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

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 fuel efficiency—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 set (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.

from __future__ import absolute_import, division, print_function, unicode_literals

!pip install -q tensorflow==2.0.0-beta1
import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)
2.0.0-beta1

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)

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])
[<matplotlib.lines.Line2D at 0x7f07e5d375f8>]

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 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='relu', input_shape=(NUM_WORDS,)),
    keras.layers.Dense(16, activation='relu'),
    keras.layers.Dense(1, activation='sigmoid')
])

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

baseline_model.summary()
Model: "sequential"
_________________________________________________________________
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)
WARNING: Logging before flag parsing goes to stderr.
W0614 17:36:34.386701 139673406682880 deprecation.py:323] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow/python/ops/math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where

Train on 25000 samples, validate on 25000 samples
Epoch 1/20
25000/25000 - 5s - loss: 0.5435 - accuracy: 0.7573 - binary_crossentropy: 0.5435 - val_loss: 0.3906 - val_accuracy: 0.8675 - val_binary_crossentropy: 0.3906
Epoch 2/20
25000/25000 - 4s - loss: 0.2790 - accuracy: 0.9034 - binary_crossentropy: 0.2790 - val_loss: 0.2889 - val_accuracy: 0.8872 - val_binary_crossentropy: 0.2889
Epoch 3/20
25000/25000 - 4s - loss: 0.1947 - accuracy: 0.9311 - binary_crossentropy: 0.1947 - val_loss: 0.2861 - val_accuracy: 0.8861 - val_binary_crossentropy: 0.2861
Epoch 4/20
25000/25000 - 4s - loss: 0.1572 - accuracy: 0.9461 - binary_crossentropy: 0.1572 - val_loss: 0.3030 - val_accuracy: 0.8798 - val_binary_crossentropy: 0.3030
Epoch 5/20
25000/25000 - 4s - loss: 0.1297 - accuracy: 0.9570 - binary_crossentropy: 0.1297 - val_loss: 0.3207 - val_accuracy: 0.8769 - val_binary_crossentropy: 0.3207
Epoch 6/20
25000/25000 - 3s - loss: 0.1091 - accuracy: 0.9660 - binary_crossentropy: 0.1091 - val_loss: 0.3461 - val_accuracy: 0.8739 - val_binary_crossentropy: 0.3461
Epoch 7/20
25000/25000 - 4s - loss: 0.0923 - accuracy: 0.9724 - binary_crossentropy: 0.0923 - val_loss: 0.3743 - val_accuracy: 0.8699 - val_binary_crossentropy: 0.3743
Epoch 8/20
25000/25000 - 3s - loss: 0.0791 - accuracy: 0.9773 - binary_crossentropy: 0.0791 - val_loss: 0.4051 - val_accuracy: 0.8671 - val_binary_crossentropy: 0.4051
Epoch 9/20
25000/25000 - 4s - loss: 0.0656 - accuracy: 0.9833 - binary_crossentropy: 0.0656 - val_loss: 0.4379 - val_accuracy: 0.8652 - val_binary_crossentropy: 0.4379
Epoch 10/20
25000/25000 - 4s - loss: 0.0557 - accuracy: 0.9866 - binary_crossentropy: 0.0557 - val_loss: 0.4746 - val_accuracy: 0.8624 - val_binary_crossentropy: 0.4746
Epoch 11/20
25000/25000 - 4s - loss: 0.0435 - accuracy: 0.9910 - binary_crossentropy: 0.0435 - val_loss: 0.5135 - val_accuracy: 0.8601 - val_binary_crossentropy: 0.5135
Epoch 12/20
25000/25000 - 3s - loss: 0.0333 - accuracy: 0.9940 - binary_crossentropy: 0.0333 - val_loss: 0.5561 - val_accuracy: 0.8591 - val_binary_crossentropy: 0.5561
Epoch 13/20
25000/25000 - 4s - loss: 0.0250 - accuracy: 0.9965 - binary_crossentropy: 0.0250 - val_loss: 0.5952 - val_accuracy: 0.8569 - val_binary_crossentropy: 0.5952
Epoch 14/20
25000/25000 - 3s - loss: 0.0180 - accuracy: 0.9978 - binary_crossentropy: 0.0180 - val_loss: 0.6357 - val_accuracy: 0.8549 - val_binary_crossentropy: 0.6357
Epoch 15/20
25000/25000 - 4s - loss: 0.0133 - accuracy: 0.9988 - binary_crossentropy: 0.0133 - val_loss: 0.6691 - val_accuracy: 0.8562 - val_binary_crossentropy: 0.6691
Epoch 16/20
25000/25000 - 3s - loss: 0.0099 - accuracy: 0.9994 - binary_crossentropy: 0.0099 - val_loss: 0.7028 - val_accuracy: 0.8535 - val_binary_crossentropy: 0.7028
Epoch 17/20
25000/25000 - 4s - loss: 0.0073 - accuracy: 0.9997 - binary_crossentropy: 0.0073 - val_loss: 0.7265 - val_accuracy: 0.8543 - val_binary_crossentropy: 0.7265
Epoch 18/20
25000/25000 - 4s - loss: 0.0055 - accuracy: 0.9998 - binary_crossentropy: 0.0055 - val_loss: 0.7547 - val_accuracy: 0.8536 - val_binary_crossentropy: 0.7547
Epoch 19/20
25000/25000 - 4s - loss: 0.0042 - accuracy: 0.9998 - binary_crossentropy: 0.0042 - val_loss: 0.7752 - val_accuracy: 0.8539 - val_binary_crossentropy: 0.7752
Epoch 20/20
25000/25000 - 3s - loss: 0.0033 - accuracy: 0.9999 - binary_crossentropy: 0.0033 - val_loss: 0.7939 - val_accuracy: 0.8542 - val_binary_crossentropy: 0.7939

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='relu', input_shape=(NUM_WORDS,)),
    keras.layers.Dense(4, activation='relu'),
    keras.layers.Dense(1, activation='sigmoid')
])

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

smaller_model.summary()
Model: "sequential_1"
_________________________________________________________________
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
25000/25000 - 4s - loss: 0.5741 - accuracy: 0.7644 - binary_crossentropy: 0.5741 - val_loss: 0.4683 - val_accuracy: 0.8536 - val_binary_crossentropy: 0.4683
Epoch 2/20
25000/25000 - 4s - loss: 0.3749 - accuracy: 0.8862 - binary_crossentropy: 0.3749 - val_loss: 0.3575 - val_accuracy: 0.8753 - val_binary_crossentropy: 0.3575
Epoch 3/20
25000/25000 - 4s - loss: 0.2826 - accuracy: 0.9096 - binary_crossentropy: 0.2826 - val_loss: 0.3133 - val_accuracy: 0.8838 - val_binary_crossentropy: 0.3133
Epoch 4/20
25000/25000 - 3s - loss: 0.2330 - accuracy: 0.9237 - binary_crossentropy: 0.2330 - val_loss: 0.2931 - val_accuracy: 0.8872 - val_binary_crossentropy: 0.2931
Epoch 5/20
25000/25000 - 4s - loss: 0.2007 - accuracy: 0.9344 - binary_crossentropy: 0.2007 - val_loss: 0.2855 - val_accuracy: 0.8878 - val_binary_crossentropy: 0.2855
Epoch 6/20
25000/25000 - 3s - loss: 0.1780 - accuracy: 0.9420 - binary_crossentropy: 0.1780 - val_loss: 0.2842 - val_accuracy: 0.8873 - val_binary_crossentropy: 0.2842
Epoch 7/20
25000/25000 - 4s - loss: 0.1594 - accuracy: 0.9486 - binary_crossentropy: 0.1594 - val_loss: 0.2882 - val_accuracy: 0.8856 - val_binary_crossentropy: 0.2882
Epoch 8/20
25000/25000 - 4s - loss: 0.1444 - accuracy: 0.9541 - binary_crossentropy: 0.1444 - val_loss: 0.2947 - val_accuracy: 0.8839 - val_binary_crossentropy: 0.2947
Epoch 9/20
25000/25000 - 4s - loss: 0.1317 - accuracy: 0.9586 - binary_crossentropy: 0.1317 - val_loss: 0.3093 - val_accuracy: 0.8786 - val_binary_crossentropy: 0.3093
Epoch 10/20
25000/25000 - 3s - loss: 0.1212 - accuracy: 0.9626 - binary_crossentropy: 0.1212 - val_loss: 0.3155 - val_accuracy: 0.8781 - val_binary_crossentropy: 0.3155
Epoch 11/20
25000/25000 - 4s - loss: 0.1111 - accuracy: 0.9669 - binary_crossentropy: 0.1111 - val_loss: 0.3260 - val_accuracy: 0.8763 - val_binary_crossentropy: 0.3260
Epoch 12/20
25000/25000 - 4s - loss: 0.1025 - accuracy: 0.9699 - binary_crossentropy: 0.1025 - val_loss: 0.3407 - val_accuracy: 0.8740 - val_binary_crossentropy: 0.3407
Epoch 13/20
25000/25000 - 4s - loss: 0.0944 - accuracy: 0.9736 - binary_crossentropy: 0.0944 - val_loss: 0.3518 - val_accuracy: 0.8733 - val_binary_crossentropy: 0.3518
Epoch 14/20
25000/25000 - 3s - loss: 0.0873 - accuracy: 0.9755 - binary_crossentropy: 0.0873 - val_loss: 0.3662 - val_accuracy: 0.8708 - val_binary_crossentropy: 0.3662
Epoch 15/20
25000/25000 - 4s - loss: 0.0809 - accuracy: 0.9783 - binary_crossentropy: 0.0809 - val_loss: 0.3801 - val_accuracy: 0.8690 - val_binary_crossentropy: 0.3801
Epoch 16/20
25000/25000 - 3s - loss: 0.0753 - accuracy: 0.9806 - binary_crossentropy: 0.0753 - val_loss: 0.3954 - val_accuracy: 0.8673 - val_binary_crossentropy: 0.3954
Epoch 17/20
25000/25000 - 4s - loss: 0.0685 - accuracy: 0.9835 - binary_crossentropy: 0.0685 - val_loss: 0.4096 - val_accuracy: 0.8662 - val_binary_crossentropy: 0.4096
Epoch 18/20
25000/25000 - 3s - loss: 0.0632 - accuracy: 0.9862 - binary_crossentropy: 0.0632 - val_loss: 0.4284 - val_accuracy: 0.8642 - val_binary_crossentropy: 0.4284
Epoch 19/20
25000/25000 - 4s - loss: 0.0584 - accuracy: 0.9874 - binary_crossentropy: 0.0584 - val_loss: 0.4417 - val_accuracy: 0.8636 - val_binary_crossentropy: 0.4417
Epoch 20/20
25000/25000 - 3s - loss: 0.0538 - accuracy: 0.9894 - binary_crossentropy: 0.0538 - val_loss: 0.4590 - val_accuracy: 0.8624 - val_binary_crossentropy: 0.4590

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='relu', input_shape=(NUM_WORDS,)),
    keras.layers.Dense(512, activation='relu'),
    keras.layers.Dense(1, activation='sigmoid')
])

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

bigger_model.summary()
Model: "sequential_2"
_________________________________________________________________
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
25000/25000 - 7s - loss: 0.3504 - accuracy: 0.8484 - binary_crossentropy: 0.3504 - val_loss: 0.3066 - val_accuracy: 0.8734 - val_binary_crossentropy: 0.3066
Epoch 2/20
25000/25000 - 7s - loss: 0.1451 - accuracy: 0.9473 - binary_crossentropy: 0.1451 - val_loss: 0.3286 - val_accuracy: 0.8747 - val_binary_crossentropy: 0.3286
Epoch 3/20
25000/25000 - 7s - loss: 0.0478 - accuracy: 0.9859 - binary_crossentropy: 0.0478 - val_loss: 0.4457 - val_accuracy: 0.8685 - val_binary_crossentropy: 0.4457
Epoch 4/20
25000/25000 - 7s - loss: 0.0072 - accuracy: 0.9991 - binary_crossentropy: 0.0072 - val_loss: 0.5815 - val_accuracy: 0.8684 - val_binary_crossentropy: 0.5815
Epoch 5/20
25000/25000 - 7s - loss: 8.4594e-04 - accuracy: 1.0000 - binary_crossentropy: 8.4594e-04 - val_loss: 0.6755 - val_accuracy: 0.8712 - val_binary_crossentropy: 0.6755
Epoch 6/20
25000/25000 - 7s - loss: 2.2323e-04 - accuracy: 1.0000 - binary_crossentropy: 2.2323e-04 - val_loss: 0.7145 - val_accuracy: 0.8712 - val_binary_crossentropy: 0.7145
Epoch 7/20
25000/25000 - 7s - loss: 1.3682e-04 - accuracy: 1.0000 - binary_crossentropy: 1.3682e-04 - val_loss: 0.7393 - val_accuracy: 0.8713 - val_binary_crossentropy: 0.7393
Epoch 8/20
25000/25000 - 7s - loss: 9.8825e-05 - accuracy: 1.0000 - binary_crossentropy: 9.8825e-05 - val_loss: 0.7579 - val_accuracy: 0.8710 - val_binary_crossentropy: 0.7579
Epoch 9/20
25000/25000 - 7s - loss: 7.5939e-05 - accuracy: 1.0000 - binary_crossentropy: 7.5939e-05 - val_loss: 0.7727 - val_accuracy: 0.8711 - val_binary_crossentropy: 0.7727
Epoch 10/20
25000/25000 - 7s - loss: 6.0573e-05 - accuracy: 1.0000 - binary_crossentropy: 6.0573e-05 - val_loss: 0.7846 - val_accuracy: 0.8720 - val_binary_crossentropy: 0.7846
Epoch 11/20
25000/25000 - 7s - loss: 4.9462e-05 - accuracy: 1.0000 - binary_crossentropy: 4.9462e-05 - val_loss: 0.7961 - val_accuracy: 0.8712 - val_binary_crossentropy: 0.7961
Epoch 12/20
25000/25000 - 7s - loss: 4.1340e-05 - accuracy: 1.0000 - binary_crossentropy: 4.1340e-05 - val_loss: 0.8059 - val_accuracy: 0.8716 - val_binary_crossentropy: 0.8059
Epoch 13/20
25000/25000 - 7s - loss: 3.4927e-05 - accuracy: 1.0000 - binary_crossentropy: 3.4927e-05 - val_loss: 0.8144 - val_accuracy: 0.8719 - val_binary_crossentropy: 0.8144
Epoch 14/20
25000/25000 - 7s - loss: 3.0028e-05 - accuracy: 1.0000 - binary_crossentropy: 3.0028e-05 - val_loss: 0.8225 - val_accuracy: 0.8717 - val_binary_crossentropy: 0.8225
Epoch 15/20
25000/25000 - 7s - loss: 2.6054e-05 - accuracy: 1.0000 - binary_crossentropy: 2.6054e-05 - val_loss: 0.8295 - val_accuracy: 0.8717 - val_binary_crossentropy: 0.8295
Epoch 16/20
25000/25000 - 7s - loss: 2.2880e-05 - accuracy: 1.0000 - binary_crossentropy: 2.2880e-05 - val_loss: 0.8366 - val_accuracy: 0.8718 - val_binary_crossentropy: 0.8366
Epoch 17/20
25000/25000 - 7s - loss: 2.0204e-05 - accuracy: 1.0000 - binary_crossentropy: 2.0204e-05 - val_loss: 0.8429 - val_accuracy: 0.8719 - val_binary_crossentropy: 0.8429
Epoch 18/20
25000/25000 - 7s - loss: 1.7972e-05 - accuracy: 1.0000 - binary_crossentropy: 1.7972e-05 - val_loss: 0.8487 - val_accuracy: 0.8718 - val_binary_crossentropy: 0.8487
Epoch 19/20
25000/25000 - 7s - loss: 1.6091e-05 - accuracy: 1.0000 - binary_crossentropy: 1.6091e-05 - val_loss: 0.8541 - val_accuracy: 0.8719 - val_binary_crossentropy: 0.8541
Epoch 20/20
25000/25000 - 7s - loss: 1.4484e-05 - accuracy: 1.0000 - binary_crossentropy: 1.4484e-05 - val_loss: 0.8593 - val_accuracy: 0.8720 - val_binary_crossentropy: 0.8593

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 to prevent overfitting

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 squared "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.

L1 regularization introduces sparsity to make some of your weight parameters zero. L2 regularization will penalize the weights parameters without making them sparse—one reason why L2 is more common.

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='relu', input_shape=(NUM_WORDS,)),
    keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),
                       activation='relu'),
    keras.layers.Dense(1, activation='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
25000/25000 - 5s - loss: 0.5295 - accuracy: 0.8148 - binary_crossentropy: 0.4887 - val_loss: 0.3801 - val_accuracy: 0.8801 - val_binary_crossentropy: 0.3360
Epoch 2/20
25000/25000 - 4s - loss: 0.3049 - accuracy: 0.9076 - binary_crossentropy: 0.2554 - val_loss: 0.3387 - val_accuracy: 0.8876 - val_binary_crossentropy: 0.2855
Epoch 3/20
25000/25000 - 4s - loss: 0.2536 - accuracy: 0.9302 - binary_crossentropy: 0.1978 - val_loss: 0.3437 - val_accuracy: 0.8851 - val_binary_crossentropy: 0.2863
Epoch 4/20
25000/25000 - 4s - loss: 0.2330 - accuracy: 0.9393 - binary_crossentropy: 0.1738 - val_loss: 0.3631 - val_accuracy: 0.8781 - val_binary_crossentropy: 0.3027
Epoch 5/20
25000/25000 - 4s - loss: 0.2176 - accuracy: 0.9470 - binary_crossentropy: 0.1562 - val_loss: 0.3712 - val_accuracy: 0.8769 - val_binary_crossentropy: 0.3091
Epoch 6/20
25000/25000 - 4s - loss: 0.2059 - accuracy: 0.9526 - binary_crossentropy: 0.1428 - val_loss: 0.3836 - val_accuracy: 0.8749 - val_binary_crossentropy: 0.3201
Epoch 7/20
25000/25000 - 4s - loss: 0.1990 - accuracy: 0.9542 - binary_crossentropy: 0.1348 - val_loss: 0.4034 - val_accuracy: 0.8713 - val_binary_crossentropy: 0.3387
Epoch 8/20
25000/25000 - 4s - loss: 0.1929 - accuracy: 0.9567 - binary_crossentropy: 0.1276 - val_loss: 0.4146 - val_accuracy: 0.8696 - val_binary_crossentropy: 0.3490
Epoch 9/20
25000/25000 - 5s - loss: 0.1878 - accuracy: 0.9585 - binary_crossentropy: 0.1214 - val_loss: 0.4298 - val_accuracy: 0.8656 - val_binary_crossentropy: 0.3630
Epoch 10/20
25000/25000 - 5s - loss: 0.1829 - accuracy: 0.9607 - binary_crossentropy: 0.1157 - val_loss: 0.4405 - val_accuracy: 0.8670 - val_binary_crossentropy: 0.3730
Epoch 11/20
25000/25000 - 4s - loss: 0.1779 - accuracy: 0.9635 - binary_crossentropy: 0.1101 - val_loss: 0.4512 - val_accuracy: 0.8653 - val_binary_crossentropy: 0.3830
Epoch 12/20
25000/25000 - 5s - loss: 0.1747 - accuracy: 0.9628 - binary_crossentropy: 0.1060 - val_loss: 0.4647 - val_accuracy: 0.8634 - val_binary_crossentropy: 0.3958
Epoch 13/20
25000/25000 - 5s - loss: 0.1703 - accuracy: 0.9672 - binary_crossentropy: 0.1012 - val_loss: 0.4761 - val_accuracy: 0.8625 - val_binary_crossentropy: 0.4067
Epoch 14/20
25000/25000 - 4s - loss: 0.1683 - accuracy: 0.9660 - binary_crossentropy: 0.0986 - val_loss: 0.4919 - val_accuracy: 0.8589 - val_binary_crossentropy: 0.4218
Epoch 15/20
25000/25000 - 4s - loss: 0.1678 - accuracy: 0.9674 - binary_crossentropy: 0.0976 - val_loss: 0.5063 - val_accuracy: 0.8605 - val_binary_crossentropy: 0.4356
Epoch 16/20
25000/25000 - 4s - loss: 0.1642 - accuracy: 0.9682 - binary_crossentropy: 0.0928 - val_loss: 0.5094 - val_accuracy: 0.8572 - val_binary_crossentropy: 0.4380
Epoch 17/20
25000/25000 - 4s - loss: 0.1613 - accuracy: 0.9689 - binary_crossentropy: 0.0901 - val_loss: 0.5202 - val_accuracy: 0.8590 - val_binary_crossentropy: 0.4488
Epoch 18/20
25000/25000 - 4s - loss: 0.1623 - accuracy: 0.9689 - binary_crossentropy: 0.0902 - val_loss: 0.5563 - val_accuracy: 0.8546 - val_binary_crossentropy: 0.4838
Epoch 19/20
25000/25000 - 4s - loss: 0.1610 - accuracy: 0.9682 - binary_crossentropy: 0.0883 - val_loss: 0.5347 - val_accuracy: 0.8559 - val_binary_crossentropy: 0.4617
Epoch 20/20
25000/25000 - 5s - loss: 0.1520 - accuracy: 0.9752 - binary_crossentropy: 0.0793 - val_loss: 0.5456 - val_accuracy: 0.8568 - val_binary_crossentropy: 0.4734

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='relu', input_shape=(NUM_WORDS,)),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(16, activation='relu'),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(1, activation='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
25000/25000 - 5s - loss: 0.6143 - accuracy: 0.6682 - binary_crossentropy: 0.6143 - val_loss: 0.4819 - val_accuracy: 0.8586 - val_binary_crossentropy: 0.4819
Epoch 2/20
25000/25000 - 4s - loss: 0.4486 - accuracy: 0.8210 - binary_crossentropy: 0.4486 - val_loss: 0.3502 - val_accuracy: 0.8823 - val_binary_crossentropy: 0.3502
Epoch 3/20
25000/25000 - 4s - loss: 0.3543 - accuracy: 0.8742 - binary_crossentropy: 0.3543 - val_loss: 0.3037 - val_accuracy: 0.8895 - val_binary_crossentropy: 0.3037
Epoch 4/20
25000/25000 - 4s - loss: 0.2968 - accuracy: 0.9008 - binary_crossentropy: 0.2968 - val_loss: 0.2826 - val_accuracy: 0.8897 - val_binary_crossentropy: 0.2826
Epoch 5/20
25000/25000 - 4s - loss: 0.2510 - accuracy: 0.9173 - binary_crossentropy: 0.2510 - val_loss: 0.2767 - val_accuracy: 0.8884 - val_binary_crossentropy: 0.2767
Epoch 6/20
25000/25000 - 4s - loss: 0.2200 - accuracy: 0.9300 - binary_crossentropy: 0.2200 - val_loss: 0.2909 - val_accuracy: 0.8857 - val_binary_crossentropy: 0.2909
Epoch 7/20
25000/25000 - 4s - loss: 0.1907 - accuracy: 0.9376 - binary_crossentropy: 0.1907 - val_loss: 0.2935 - val_accuracy: 0.8847 - val_binary_crossentropy: 0.2935
Epoch 8/20
25000/25000 - 4s - loss: 0.1705 - accuracy: 0.9476 - binary_crossentropy: 0.1705 - val_loss: 0.3140 - val_accuracy: 0.8850 - val_binary_crossentropy: 0.3140
Epoch 9/20
25000/25000 - 4s - loss: 0.1468 - accuracy: 0.9536 - binary_crossentropy: 0.1468 - val_loss: 0.3418 - val_accuracy: 0.8811 - val_binary_crossentropy: 0.3418
Epoch 10/20
25000/25000 - 5s - loss: 0.1313 - accuracy: 0.9598 - binary_crossentropy: 0.1313 - val_loss: 0.3731 - val_accuracy: 0.8803 - val_binary_crossentropy: 0.3731
Epoch 11/20
25000/25000 - 4s - loss: 0.1218 - accuracy: 0.9629 - binary_crossentropy: 0.1218 - val_loss: 0.3755 - val_accuracy: 0.8796 - val_binary_crossentropy: 0.3755
Epoch 12/20
25000/25000 - 4s - loss: 0.1102 - accuracy: 0.9656 - binary_crossentropy: 0.1102 - val_loss: 0.3962 - val_accuracy: 0.8792 - val_binary_crossentropy: 0.3962
Epoch 13/20
25000/25000 - 4s - loss: 0.1022 - accuracy: 0.9681 - binary_crossentropy: 0.1022 - val_loss: 0.4369 - val_accuracy: 0.8790 - val_binary_crossentropy: 0.4369
Epoch 14/20
25000/25000 - 5s - loss: 0.0931 - accuracy: 0.9702 - binary_crossentropy: 0.0931 - val_loss: 0.4528 - val_accuracy: 0.8778 - val_binary_crossentropy: 0.4528
Epoch 15/20
25000/25000 - 4s - loss: 0.0886 - accuracy: 0.9726 - binary_crossentropy: 0.0886 - val_loss: 0.4817 - val_accuracy: 0.8754 - val_binary_crossentropy: 0.4817
Epoch 16/20
25000/25000 - 4s - loss: 0.0808 - accuracy: 0.9745 - binary_crossentropy: 0.0808 - val_loss: 0.4971 - val_accuracy: 0.8745 - val_binary_crossentropy: 0.4971
Epoch 17/20
25000/25000 - 4s - loss: 0.0758 - accuracy: 0.9745 - binary_crossentropy: 0.0758 - val_loss: 0.4992 - val_accuracy: 0.8746 - val_binary_crossentropy: 0.4992
Epoch 18/20
25000/25000 - 4s - loss: 0.0720 - accuracy: 0.9762 - binary_crossentropy: 0.0720 - val_loss: 0.5373 - val_accuracy: 0.8756 - val_binary_crossentropy: 0.5373
Epoch 19/20
25000/25000 - 4s - loss: 0.0709 - accuracy: 0.9768 - binary_crossentropy: 0.0709 - val_loss: 0.5491 - val_accuracy: 0.8744 - val_binary_crossentropy: 0.5491
Epoch 20/20
25000/25000 - 4s - loss: 0.0663 - accuracy: 0.9783 - binary_crossentropy: 0.0663 - val_loss: 0.5506 - val_accuracy: 0.8740 - val_binary_crossentropy: 0.5506
plot_history([('baseline', baseline_history),
              ('dropout', dpt_model_history)])

png

Adding dropout is a clear improvement over the baseline model.

To recap: here are 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.