Watch talks from the 2019 TensorFlow Dev Summit Watch now

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

from __future__ import absolute_import, division, print_function

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

import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)
2.0.0-alpha0

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

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)
Train on 25000 samples, validate on 25000 samples
Epoch 1/20
25000/25000 - 4s - loss: 0.4881 - accuracy: 0.7869 - binary_crossentropy: 0.4881 - val_loss: 0.3445 - val_accuracy: 0.8765 - val_binary_crossentropy: 0.3445
Epoch 2/20
25000/25000 - 3s - loss: 0.2552 - accuracy: 0.9138 - binary_crossentropy: 0.2552 - val_loss: 0.2867 - val_accuracy: 0.8894 - val_binary_crossentropy: 0.2867
Epoch 3/20
25000/25000 - 3s - loss: 0.1864 - accuracy: 0.9357 - binary_crossentropy: 0.1864 - val_loss: 0.2899 - val_accuracy: 0.8835 - val_binary_crossentropy: 0.2899
Epoch 4/20
25000/25000 - 3s - loss: 0.1501 - accuracy: 0.9492 - binary_crossentropy: 0.1501 - val_loss: 0.3181 - val_accuracy: 0.8760 - val_binary_crossentropy: 0.3181
Epoch 5/20
25000/25000 - 3s - loss: 0.1230 - accuracy: 0.9598 - binary_crossentropy: 0.1230 - val_loss: 0.3308 - val_accuracy: 0.8756 - val_binary_crossentropy: 0.3308
Epoch 6/20
25000/25000 - 3s - loss: 0.1009 - accuracy: 0.9698 - binary_crossentropy: 0.1009 - val_loss: 0.3600 - val_accuracy: 0.8728 - val_binary_crossentropy: 0.3600
Epoch 7/20
25000/25000 - 3s - loss: 0.0832 - accuracy: 0.9764 - binary_crossentropy: 0.0832 - val_loss: 0.3924 - val_accuracy: 0.8679 - val_binary_crossentropy: 0.3924
Epoch 8/20
25000/25000 - 3s - loss: 0.0695 - accuracy: 0.9823 - binary_crossentropy: 0.0695 - val_loss: 0.4238 - val_accuracy: 0.8645 - val_binary_crossentropy: 0.4238
Epoch 9/20
25000/25000 - 3s - loss: 0.0554 - accuracy: 0.9876 - binary_crossentropy: 0.0554 - val_loss: 0.4602 - val_accuracy: 0.8628 - val_binary_crossentropy: 0.4602
Epoch 10/20
25000/25000 - 3s - loss: 0.0451 - accuracy: 0.9910 - binary_crossentropy: 0.0451 - val_loss: 0.5070 - val_accuracy: 0.8604 - val_binary_crossentropy: 0.5070
Epoch 11/20
25000/25000 - 3s - loss: 0.0345 - accuracy: 0.9944 - binary_crossentropy: 0.0345 - val_loss: 0.5511 - val_accuracy: 0.8581 - val_binary_crossentropy: 0.5511
Epoch 12/20
25000/25000 - 3s - loss: 0.0257 - accuracy: 0.9964 - binary_crossentropy: 0.0257 - val_loss: 0.5937 - val_accuracy: 0.8567 - val_binary_crossentropy: 0.5937
Epoch 13/20
25000/25000 - 3s - loss: 0.0191 - accuracy: 0.9984 - binary_crossentropy: 0.0191 - val_loss: 0.6493 - val_accuracy: 0.8544 - val_binary_crossentropy: 0.6493
Epoch 14/20
25000/25000 - 3s - loss: 0.0131 - accuracy: 0.9990 - binary_crossentropy: 0.0131 - val_loss: 0.7073 - val_accuracy: 0.8537 - val_binary_crossentropy: 0.7073
Epoch 15/20
25000/25000 - 3s - loss: 0.0093 - accuracy: 0.9993 - binary_crossentropy: 0.0093 - val_loss: 0.7430 - val_accuracy: 0.8540 - val_binary_crossentropy: 0.7430
Epoch 16/20
25000/25000 - 3s - loss: 0.0068 - accuracy: 0.9995 - binary_crossentropy: 0.0068 - val_loss: 0.7921 - val_accuracy: 0.8532 - val_binary_crossentropy: 0.7921
Epoch 17/20
25000/25000 - 3s - loss: 0.0052 - accuracy: 0.9995 - binary_crossentropy: 0.0052 - val_loss: 0.8222 - val_accuracy: 0.8529 - val_binary_crossentropy: 0.8222
Epoch 18/20
25000/25000 - 3s - loss: 0.0039 - accuracy: 0.9998 - binary_crossentropy: 0.0039 - val_loss: 0.8674 - val_accuracy: 0.8530 - val_binary_crossentropy: 0.8674
Epoch 19/20
25000/25000 - 3s - loss: 0.0030 - accuracy: 0.9998 - binary_crossentropy: 0.0030 - val_loss: 0.8911 - val_accuracy: 0.8528 - val_binary_crossentropy: 0.8911
Epoch 20/20
25000/25000 - 3s - loss: 0.0024 - accuracy: 0.9999 - binary_crossentropy: 0.0024 - val_loss: 0.9194 - val_accuracy: 0.8529 - val_binary_crossentropy: 0.9194

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.6651 - accuracy: 0.6075 - binary_crossentropy: 0.6651 - val_loss: 0.6323 - val_accuracy: 0.6588 - val_binary_crossentropy: 0.6323
Epoch 2/20
25000/25000 - 3s - loss: 0.5969 - accuracy: 0.7276 - binary_crossentropy: 0.5969 - val_loss: 0.5779 - val_accuracy: 0.7404 - val_binary_crossentropy: 0.5779
Epoch 3/20
25000/25000 - 4s - loss: 0.5420 - accuracy: 0.8007 - binary_crossentropy: 0.5420 - val_loss: 0.5358 - val_accuracy: 0.7846 - val_binary_crossentropy: 0.5358
Epoch 4/20
25000/25000 - 3s - loss: 0.4982 - accuracy: 0.8413 - binary_crossentropy: 0.4982 - val_loss: 0.5023 - val_accuracy: 0.8180 - val_binary_crossentropy: 0.5023
Epoch 5/20
25000/25000 - 3s - loss: 0.4624 - accuracy: 0.8704 - binary_crossentropy: 0.4624 - val_loss: 0.4785 - val_accuracy: 0.8241 - val_binary_crossentropy: 0.4785
Epoch 6/20
25000/25000 - 3s - loss: 0.4327 - accuracy: 0.8883 - binary_crossentropy: 0.4327 - val_loss: 0.4543 - val_accuracy: 0.8570 - val_binary_crossentropy: 0.4543
Epoch 7/20
25000/25000 - 4s - loss: 0.4072 - accuracy: 0.9032 - binary_crossentropy: 0.4072 - val_loss: 0.4391 - val_accuracy: 0.8553 - val_binary_crossentropy: 0.4391
Epoch 8/20
25000/25000 - 4s - loss: 0.3849 - accuracy: 0.9134 - binary_crossentropy: 0.3849 - val_loss: 0.4245 - val_accuracy: 0.8640 - val_binary_crossentropy: 0.4245
Epoch 9/20
25000/25000 - 4s - loss: 0.3652 - accuracy: 0.9212 - binary_crossentropy: 0.3652 - val_loss: 0.4157 - val_accuracy: 0.8619 - val_binary_crossentropy: 0.4157
Epoch 10/20
25000/25000 - 3s - loss: 0.3476 - accuracy: 0.9284 - binary_crossentropy: 0.3476 - val_loss: 0.4044 - val_accuracy: 0.8705 - val_binary_crossentropy: 0.4044
Epoch 11/20
25000/25000 - 4s - loss: 0.3314 - accuracy: 0.9353 - binary_crossentropy: 0.3314 - val_loss: 0.3962 - val_accuracy: 0.8728 - val_binary_crossentropy: 0.3962
Epoch 12/20
25000/25000 - 4s - loss: 0.3166 - accuracy: 0.9405 - binary_crossentropy: 0.3166 - val_loss: 0.3888 - val_accuracy: 0.8744 - val_binary_crossentropy: 0.3888
Epoch 13/20
25000/25000 - 3s - loss: 0.3027 - accuracy: 0.9452 - binary_crossentropy: 0.3027 - val_loss: 0.3843 - val_accuracy: 0.8742 - val_binary_crossentropy: 0.3843
Epoch 14/20
25000/25000 - 4s - loss: 0.2900 - accuracy: 0.9494 - binary_crossentropy: 0.2900 - val_loss: 0.3812 - val_accuracy: 0.8733 - val_binary_crossentropy: 0.3812
Epoch 15/20
25000/25000 - 4s - loss: 0.2779 - accuracy: 0.9530 - binary_crossentropy: 0.2779 - val_loss: 0.3777 - val_accuracy: 0.8738 - val_binary_crossentropy: 0.3777
Epoch 16/20
25000/25000 - 3s - loss: 0.2666 - accuracy: 0.9558 - binary_crossentropy: 0.2666 - val_loss: 0.3730 - val_accuracy: 0.8744 - val_binary_crossentropy: 0.3730
Epoch 17/20
25000/25000 - 4s - loss: 0.2558 - accuracy: 0.9588 - binary_crossentropy: 0.2558 - val_loss: 0.3748 - val_accuracy: 0.8724 - val_binary_crossentropy: 0.3748
Epoch 18/20
25000/25000 - 4s - loss: 0.2458 - accuracy: 0.9613 - binary_crossentropy: 0.2458 - val_loss: 0.3707 - val_accuracy: 0.8744 - val_binary_crossentropy: 0.3707
Epoch 19/20
25000/25000 - 4s - loss: 0.2363 - accuracy: 0.9632 - binary_crossentropy: 0.2363 - val_loss: 0.3680 - val_accuracy: 0.8750 - val_binary_crossentropy: 0.3680
Epoch 20/20
25000/25000 - 4s - loss: 0.2276 - accuracy: 0.9655 - binary_crossentropy: 0.2276 - val_loss: 0.3654 - val_accuracy: 0.8755 - val_binary_crossentropy: 0.3654

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 - 6s - loss: 0.3436 - accuracy: 0.8533 - binary_crossentropy: 0.3436 - val_loss: 0.2970 - val_accuracy: 0.8774 - val_binary_crossentropy: 0.2970
Epoch 2/20
25000/25000 - 5s - loss: 0.1419 - accuracy: 0.9487 - binary_crossentropy: 0.1419 - val_loss: 0.3333 - val_accuracy: 0.8716 - val_binary_crossentropy: 0.3333
Epoch 3/20
25000/25000 - 5s - loss: 0.0466 - accuracy: 0.9869 - binary_crossentropy: 0.0466 - val_loss: 0.4502 - val_accuracy: 0.8680 - val_binary_crossentropy: 0.4502
Epoch 4/20
25000/25000 - 5s - loss: 0.0068 - accuracy: 0.9988 - binary_crossentropy: 0.0068 - val_loss: 0.6078 - val_accuracy: 0.8658 - val_binary_crossentropy: 0.6078
Epoch 5/20
25000/25000 - 5s - loss: 8.2359e-04 - accuracy: 1.0000 - binary_crossentropy: 8.2359e-04 - val_loss: 0.6902 - val_accuracy: 0.8698 - val_binary_crossentropy: 0.6902
Epoch 6/20
25000/25000 - 5s - loss: 2.1378e-04 - accuracy: 1.0000 - binary_crossentropy: 2.1378e-04 - val_loss: 0.7351 - val_accuracy: 0.8700 - val_binary_crossentropy: 0.7351
Epoch 7/20
25000/25000 - 6s - loss: 1.3067e-04 - accuracy: 1.0000 - binary_crossentropy: 1.3067e-04 - val_loss: 0.7644 - val_accuracy: 0.8704 - val_binary_crossentropy: 0.7644
Epoch 8/20
25000/25000 - 6s - loss: 9.4273e-05 - accuracy: 1.0000 - binary_crossentropy: 9.4273e-05 - val_loss: 0.7877 - val_accuracy: 0.8700 - val_binary_crossentropy: 0.7877
Epoch 9/20
25000/25000 - 5s - loss: 7.2173e-05 - accuracy: 1.0000 - binary_crossentropy: 7.2173e-05 - val_loss: 0.8066 - val_accuracy: 0.8703 - val_binary_crossentropy: 0.8066
Epoch 10/20
25000/25000 - 5s - loss: 5.7300e-05 - accuracy: 1.0000 - binary_crossentropy: 5.7300e-05 - val_loss: 0.8235 - val_accuracy: 0.8704 - val_binary_crossentropy: 0.8235
Epoch 11/20
25000/25000 - 5s - loss: 4.6368e-05 - accuracy: 1.0000 - binary_crossentropy: 4.6368e-05 - val_loss: 0.8400 - val_accuracy: 0.8700 - val_binary_crossentropy: 0.8400
Epoch 12/20
25000/25000 - 5s - loss: 3.8188e-05 - accuracy: 1.0000 - binary_crossentropy: 3.8188e-05 - val_loss: 0.8553 - val_accuracy: 0.8705 - val_binary_crossentropy: 0.8553
Epoch 13/20
25000/25000 - 5s - loss: 3.1415e-05 - accuracy: 1.0000 - binary_crossentropy: 3.1415e-05 - val_loss: 0.8704 - val_accuracy: 0.8709 - val_binary_crossentropy: 0.8704
Epoch 14/20
25000/25000 - 5s - loss: 2.6080e-05 - accuracy: 1.0000 - binary_crossentropy: 2.6080e-05 - val_loss: 0.8868 - val_accuracy: 0.8706 - val_binary_crossentropy: 0.8868
Epoch 15/20
25000/25000 - 5s - loss: 2.1638e-05 - accuracy: 1.0000 - binary_crossentropy: 2.1638e-05 - val_loss: 0.9030 - val_accuracy: 0.8702 - val_binary_crossentropy: 0.9030
Epoch 16/20
25000/25000 - 5s - loss: 1.8066e-05 - accuracy: 1.0000 - binary_crossentropy: 1.8066e-05 - val_loss: 0.9198 - val_accuracy: 0.8702 - val_binary_crossentropy: 0.9198
Epoch 17/20
25000/25000 - 5s - loss: 1.5080e-05 - accuracy: 1.0000 - binary_crossentropy: 1.5080e-05 - val_loss: 0.9362 - val_accuracy: 0.8701 - val_binary_crossentropy: 0.9362
Epoch 18/20
25000/25000 - 5s - loss: 1.2686e-05 - accuracy: 1.0000 - binary_crossentropy: 1.2686e-05 - val_loss: 0.9524 - val_accuracy: 0.8700 - val_binary_crossentropy: 0.9524
Epoch 19/20
25000/25000 - 5s - loss: 1.0747e-05 - accuracy: 1.0000 - binary_crossentropy: 1.0747e-05 - val_loss: 0.9681 - val_accuracy: 0.8702 - val_binary_crossentropy: 0.9681
Epoch 20/20
25000/25000 - 5s - loss: 9.1827e-06 - accuracy: 1.0000 - binary_crossentropy: 9.1827e-06 - val_loss: 0.9834 - val_accuracy: 0.8702 - val_binary_crossentropy: 0.9834

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 - 3s - loss: 0.4968 - accuracy: 0.8198 - binary_crossentropy: 0.4535 - val_loss: 0.3682 - val_accuracy: 0.8781 - val_binary_crossentropy: 0.3223
Epoch 2/20
25000/25000 - 3s - loss: 0.2942 - accuracy: 0.9117 - binary_crossentropy: 0.2448 - val_loss: 0.3376 - val_accuracy: 0.8865 - val_binary_crossentropy: 0.2857
Epoch 3/20
25000/25000 - 3s - loss: 0.2473 - accuracy: 0.9314 - binary_crossentropy: 0.1932 - val_loss: 0.3408 - val_accuracy: 0.8853 - val_binary_crossentropy: 0.2853
Epoch 4/20
25000/25000 - 3s - loss: 0.2260 - accuracy: 0.9414 - binary_crossentropy: 0.1690 - val_loss: 0.3592 - val_accuracy: 0.8786 - val_binary_crossentropy: 0.3010
Epoch 5/20
25000/25000 - 3s - loss: 0.2111 - accuracy: 0.9492 - binary_crossentropy: 0.1519 - val_loss: 0.3705 - val_accuracy: 0.8764 - val_binary_crossentropy: 0.3105
Epoch 6/20
25000/25000 - 3s - loss: 0.1995 - accuracy: 0.9542 - binary_crossentropy: 0.1385 - val_loss: 0.3833 - val_accuracy: 0.8748 - val_binary_crossentropy: 0.3218
Epoch 7/20
25000/25000 - 3s - loss: 0.1924 - accuracy: 0.9569 - binary_crossentropy: 0.1301 - val_loss: 0.4054 - val_accuracy: 0.8710 - val_binary_crossentropy: 0.3425
Epoch 8/20
25000/25000 - 3s - loss: 0.1863 - accuracy: 0.9588 - binary_crossentropy: 0.1227 - val_loss: 0.4172 - val_accuracy: 0.8703 - val_binary_crossentropy: 0.3532
Epoch 9/20
25000/25000 - 3s - loss: 0.1806 - accuracy: 0.9599 - binary_crossentropy: 0.1159 - val_loss: 0.4358 - val_accuracy: 0.8653 - val_binary_crossentropy: 0.3707
Epoch 10/20
25000/25000 - 3s - loss: 0.1761 - accuracy: 0.9630 - binary_crossentropy: 0.1106 - val_loss: 0.4463 - val_accuracy: 0.8663 - val_binary_crossentropy: 0.3803
Epoch 11/20
25000/25000 - 3s - loss: 0.1716 - accuracy: 0.9651 - binary_crossentropy: 0.1051 - val_loss: 0.4604 - val_accuracy: 0.8643 - val_binary_crossentropy: 0.3935
Epoch 12/20
25000/25000 - 3s - loss: 0.1684 - accuracy: 0.9646 - binary_crossentropy: 0.1012 - val_loss: 0.4770 - val_accuracy: 0.8617 - val_binary_crossentropy: 0.4095
Epoch 13/20
25000/25000 - 3s - loss: 0.1639 - accuracy: 0.9692 - binary_crossentropy: 0.0960 - val_loss: 0.4884 - val_accuracy: 0.8606 - val_binary_crossentropy: 0.4203
Epoch 14/20
25000/25000 - 3s - loss: 0.1617 - accuracy: 0.9682 - binary_crossentropy: 0.0933 - val_loss: 0.5072 - val_accuracy: 0.8582 - val_binary_crossentropy: 0.4385
Epoch 15/20
25000/25000 - 3s - loss: 0.1613 - accuracy: 0.9685 - binary_crossentropy: 0.0925 - val_loss: 0.5256 - val_accuracy: 0.8587 - val_binary_crossentropy: 0.4563
Epoch 16/20
25000/25000 - 3s - loss: 0.1597 - accuracy: 0.9689 - binary_crossentropy: 0.0895 - val_loss: 0.5360 - val_accuracy: 0.8546 - val_binary_crossentropy: 0.4656
Epoch 17/20
25000/25000 - 3s - loss: 0.1575 - accuracy: 0.9701 - binary_crossentropy: 0.0873 - val_loss: 0.5422 - val_accuracy: 0.8560 - val_binary_crossentropy: 0.4719
Epoch 18/20
25000/25000 - 3s - loss: 0.1559 - accuracy: 0.9714 - binary_crossentropy: 0.0851 - val_loss: 0.5778 - val_accuracy: 0.8516 - val_binary_crossentropy: 0.5069
Epoch 19/20
25000/25000 - 3s - loss: 0.1561 - accuracy: 0.9693 - binary_crossentropy: 0.0849 - val_loss: 0.5652 - val_accuracy: 0.8543 - val_binary_crossentropy: 0.4936
Epoch 20/20
25000/25000 - 3s - loss: 0.1490 - accuracy: 0.9750 - binary_crossentropy: 0.0775 - val_loss: 0.5752 - val_accuracy: 0.8532 - val_binary_crossentropy: 0.5040

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 - 4s - loss: 0.6059 - accuracy: 0.6622 - binary_crossentropy: 0.6059 - val_loss: 0.4356 - val_accuracy: 0.8602 - val_binary_crossentropy: 0.4356
Epoch 2/20
25000/25000 - 3s - loss: 0.4259 - accuracy: 0.8214 - binary_crossentropy: 0.4259 - val_loss: 0.3207 - val_accuracy: 0.8828 - val_binary_crossentropy: 0.3207
Epoch 3/20
25000/25000 - 3s - loss: 0.3316 - accuracy: 0.8795 - binary_crossentropy: 0.3316 - val_loss: 0.2837 - val_accuracy: 0.8890 - val_binary_crossentropy: 0.2837
Epoch 4/20
25000/25000 - 3s - loss: 0.2761 - accuracy: 0.9049 - binary_crossentropy: 0.2761 - val_loss: 0.2753 - val_accuracy: 0.8887 - val_binary_crossentropy: 0.2753
Epoch 5/20
25000/25000 - 3s - loss: 0.2334 - accuracy: 0.9237 - binary_crossentropy: 0.2334 - val_loss: 0.2797 - val_accuracy: 0.8875 - val_binary_crossentropy: 0.2797
Epoch 6/20
25000/25000 - 3s - loss: 0.2039 - accuracy: 0.9351 - binary_crossentropy: 0.2039 - val_loss: 0.2908 - val_accuracy: 0.8849 - val_binary_crossentropy: 0.2908
Epoch 7/20
25000/25000 - 3s - loss: 0.1792 - accuracy: 0.9447 - binary_crossentropy: 0.1792 - val_loss: 0.3114 - val_accuracy: 0.8829 - val_binary_crossentropy: 0.3114
Epoch 8/20
25000/25000 - 3s - loss: 0.1625 - accuracy: 0.9490 - binary_crossentropy: 0.1625 - val_loss: 0.3249 - val_accuracy: 0.8826 - val_binary_crossentropy: 0.3249
Epoch 9/20
25000/25000 - 3s - loss: 0.1405 - accuracy: 0.9560 - binary_crossentropy: 0.1405 - val_loss: 0.3417 - val_accuracy: 0.8811 - val_binary_crossentropy: 0.3417
Epoch 10/20
25000/25000 - 3s - loss: 0.1256 - accuracy: 0.9621 - binary_crossentropy: 0.1256 - val_loss: 0.3836 - val_accuracy: 0.8799 - val_binary_crossentropy: 0.3836
Epoch 11/20
25000/25000 - 3s - loss: 0.1152 - accuracy: 0.9650 - binary_crossentropy: 0.1152 - val_loss: 0.3932 - val_accuracy: 0.8779 - val_binary_crossentropy: 0.3932
Epoch 12/20
25000/25000 - 3s - loss: 0.1007 - accuracy: 0.9691 - binary_crossentropy: 0.1007 - val_loss: 0.4139 - val_accuracy: 0.8785 - val_binary_crossentropy: 0.4139
Epoch 13/20
25000/25000 - 3s - loss: 0.0900 - accuracy: 0.9740 - binary_crossentropy: 0.0900 - val_loss: 0.4557 - val_accuracy: 0.8778 - val_binary_crossentropy: 0.4557
Epoch 14/20
25000/25000 - 3s - loss: 0.0872 - accuracy: 0.9749 - binary_crossentropy: 0.0872 - val_loss: 0.4421 - val_accuracy: 0.8747 - val_binary_crossentropy: 0.4421
Epoch 15/20
25000/25000 - 3s - loss: 0.0785 - accuracy: 0.9763 - binary_crossentropy: 0.0785 - val_loss: 0.4921 - val_accuracy: 0.8766 - val_binary_crossentropy: 0.4921
Epoch 16/20
25000/25000 - 3s - loss: 0.0709 - accuracy: 0.9787 - binary_crossentropy: 0.0709 - val_loss: 0.4958 - val_accuracy: 0.8731 - val_binary_crossentropy: 0.4958
Epoch 17/20
25000/25000 - 3s - loss: 0.0708 - accuracy: 0.9793 - binary_crossentropy: 0.0708 - val_loss: 0.5323 - val_accuracy: 0.8736 - val_binary_crossentropy: 0.5323
Epoch 18/20
25000/25000 - 3s - loss: 0.0672 - accuracy: 0.9802 - binary_crossentropy: 0.0672 - val_loss: 0.5363 - val_accuracy: 0.8740 - val_binary_crossentropy: 0.5363
Epoch 19/20
25000/25000 - 3s - loss: 0.0608 - accuracy: 0.9815 - binary_crossentropy: 0.0608 - val_loss: 0.5643 - val_accuracy: 0.8743 - val_binary_crossentropy: 0.5643
Epoch 20/20
25000/25000 - 3s - loss: 0.0609 - accuracy: 0.9817 - binary_crossentropy: 0.0609 - val_loss: 0.5689 - val_accuracy: 0.8734 - val_binary_crossentropy: 0.5689
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.