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 if you continue to train for more epochs. This means the network has not yet learned all 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.9.0

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://s3.amazonaws.com/text-datasets/imdb.npz
17465344/17464789 [==============================] - 2s 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, then well a smaller version, and compare them.

Create a baseline model

baseline_model = keras.Sequential([
    keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(10000,)),
    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
 - 4s - loss: 0.4653 - acc: 0.8035 - binary_crossentropy: 0.4653 - val_loss: 0.3197 - val_acc: 0.8808 - val_binary_crossentropy: 0.3197
Epoch 2/20
 - 3s - loss: 0.2361 - acc: 0.9154 - binary_crossentropy: 0.2361 - val_loss: 0.2836 - val_acc: 0.8877 - val_binary_crossentropy: 0.2836
Epoch 3/20
 - 3s - loss: 0.1740 - acc: 0.9396 - binary_crossentropy: 0.1740 - val_loss: 0.2938 - val_acc: 0.8842 - val_binary_crossentropy: 0.2938
Epoch 4/20
 - 3s - loss: 0.1389 - acc: 0.9538 - binary_crossentropy: 0.1389 - val_loss: 0.3220 - val_acc: 0.8775 - val_binary_crossentropy: 0.3220
Epoch 5/20
 - 3s - loss: 0.1155 - acc: 0.9622 - binary_crossentropy: 0.1155 - val_loss: 0.3520 - val_acc: 0.8724 - val_binary_crossentropy: 0.3520
Epoch 6/20
 - 3s - loss: 0.0943 - acc: 0.9711 - binary_crossentropy: 0.0943 - val_loss: 0.3863 - val_acc: 0.8677 - val_binary_crossentropy: 0.3863
Epoch 7/20
 - 3s - loss: 0.0776 - acc: 0.9783 - binary_crossentropy: 0.0776 - val_loss: 0.4451 - val_acc: 0.8602 - val_binary_crossentropy: 0.4451
Epoch 8/20
 - 3s - loss: 0.0646 - acc: 0.9823 - binary_crossentropy: 0.0646 - val_loss: 0.4636 - val_acc: 0.8614 - val_binary_crossentropy: 0.4636
Epoch 9/20
 - 3s - loss: 0.0528 - acc: 0.9873 - binary_crossentropy: 0.0528 - val_loss: 0.5110 - val_acc: 0.8592 - val_binary_crossentropy: 0.5110
Epoch 10/20
 - 3s - loss: 0.0429 - acc: 0.9911 - binary_crossentropy: 0.0429 - val_loss: 0.5648 - val_acc: 0.8562 - val_binary_crossentropy: 0.5648
Epoch 11/20
 - 3s - loss: 0.0364 - acc: 0.9927 - binary_crossentropy: 0.0364 - val_loss: 0.5966 - val_acc: 0.8560 - val_binary_crossentropy: 0.5966
Epoch 12/20
 - 3s - loss: 0.0284 - acc: 0.9958 - binary_crossentropy: 0.0284 - val_loss: 0.6392 - val_acc: 0.8533 - val_binary_crossentropy: 0.6392
Epoch 13/20
 - 3s - loss: 0.0225 - acc: 0.9972 - binary_crossentropy: 0.0225 - val_loss: 0.6842 - val_acc: 0.8528 - val_binary_crossentropy: 0.6842
Epoch 14/20
 - 3s - loss: 0.0178 - acc: 0.9984 - binary_crossentropy: 0.0178 - val_loss: 0.7184 - val_acc: 0.8505 - val_binary_crossentropy: 0.7184
Epoch 15/20
 - 3s - loss: 0.0142 - acc: 0.9989 - binary_crossentropy: 0.0142 - val_loss: 0.7574 - val_acc: 0.8506 - val_binary_crossentropy: 0.7574
Epoch 16/20
 - 3s - loss: 0.0117 - acc: 0.9991 - binary_crossentropy: 0.0117 - val_loss: 0.7811 - val_acc: 0.8500 - val_binary_crossentropy: 0.7811
Epoch 17/20
 - 3s - loss: 0.0096 - acc: 0.9994 - binary_crossentropy: 0.0096 - val_loss: 0.8176 - val_acc: 0.8496 - val_binary_crossentropy: 0.8176
Epoch 18/20
 - 3s - loss: 0.0080 - acc: 0.9995 - binary_crossentropy: 0.0080 - val_loss: 0.8464 - val_acc: 0.8493 - val_binary_crossentropy: 0.8464
Epoch 19/20
 - 3s - loss: 0.0067 - acc: 0.9995 - binary_crossentropy: 0.0067 - val_loss: 0.8594 - val_acc: 0.8494 - val_binary_crossentropy: 0.8594
Epoch 20/20
 - 3s - loss: 0.0058 - acc: 0.9996 - binary_crossentropy: 0.0058 - val_loss: 0.8906 - val_acc: 0.8490 - val_binary_crossentropy: 0.8906

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=(10000,)),
    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
 - 4s - loss: 0.5800 - acc: 0.7760 - binary_crossentropy: 0.5800 - val_loss: 0.4639 - val_acc: 0.8609 - val_binary_crossentropy: 0.4639
Epoch 2/20
 - 3s - loss: 0.3674 - acc: 0.8972 - binary_crossentropy: 0.3674 - val_loss: 0.3498 - val_acc: 0.8821 - val_binary_crossentropy: 0.3498
Epoch 3/20
 - 3s - loss: 0.2728 - acc: 0.9186 - binary_crossentropy: 0.2728 - val_loss: 0.3054 - val_acc: 0.8875 - val_binary_crossentropy: 0.3054
Epoch 4/20
 - 3s - loss: 0.2237 - acc: 0.9312 - binary_crossentropy: 0.2237 - val_loss: 0.2898 - val_acc: 0.8888 - val_binary_crossentropy: 0.2898
Epoch 5/20
 - 3s - loss: 0.1926 - acc: 0.9399 - binary_crossentropy: 0.1926 - val_loss: 0.2868 - val_acc: 0.8856 - val_binary_crossentropy: 0.2868
Epoch 6/20
 - 3s - loss: 0.1699 - acc: 0.9462 - binary_crossentropy: 0.1699 - val_loss: 0.2857 - val_acc: 0.8875 - val_binary_crossentropy: 0.2857
Epoch 7/20
 - 3s - loss: 0.1520 - acc: 0.9534 - binary_crossentropy: 0.1520 - val_loss: 0.2911 - val_acc: 0.8843 - val_binary_crossentropy: 0.2911
Epoch 8/20
 - 3s - loss: 0.1377 - acc: 0.9582 - binary_crossentropy: 0.1377 - val_loss: 0.2995 - val_acc: 0.8819 - val_binary_crossentropy: 0.2995
Epoch 9/20
 - 3s - loss: 0.1260 - acc: 0.9617 - binary_crossentropy: 0.1260 - val_loss: 0.3096 - val_acc: 0.8795 - val_binary_crossentropy: 0.3096
Epoch 10/20
 - 3s - loss: 0.1149 - acc: 0.9664 - binary_crossentropy: 0.1149 - val_loss: 0.3214 - val_acc: 0.8772 - val_binary_crossentropy: 0.3214
Epoch 11/20
 - 3s - loss: 0.1056 - acc: 0.9700 - binary_crossentropy: 0.1056 - val_loss: 0.3323 - val_acc: 0.8758 - val_binary_crossentropy: 0.3323
Epoch 12/20
 - 3s - loss: 0.0966 - acc: 0.9728 - binary_crossentropy: 0.0966 - val_loss: 0.3472 - val_acc: 0.8719 - val_binary_crossentropy: 0.3472
Epoch 13/20
 - 3s - loss: 0.0887 - acc: 0.9767 - binary_crossentropy: 0.0887 - val_loss: 0.3587 - val_acc: 0.8714 - val_binary_crossentropy: 0.3587
Epoch 14/20
 - 3s - loss: 0.0819 - acc: 0.9792 - binary_crossentropy: 0.0819 - val_loss: 0.3741 - val_acc: 0.8694 - val_binary_crossentropy: 0.3741
Epoch 15/20
 - 3s - loss: 0.0753 - acc: 0.9818 - binary_crossentropy: 0.0753 - val_loss: 0.3879 - val_acc: 0.8686 - val_binary_crossentropy: 0.3879
Epoch 16/20
 - 3s - loss: 0.0694 - acc: 0.9842 - binary_crossentropy: 0.0694 - val_loss: 0.4037 - val_acc: 0.8679 - val_binary_crossentropy: 0.4037
Epoch 17/20
 - 3s - loss: 0.0640 - acc: 0.9862 - binary_crossentropy: 0.0640 - val_loss: 0.4208 - val_acc: 0.8649 - val_binary_crossentropy: 0.4208
Epoch 18/20
 - 3s - loss: 0.0587 - acc: 0.9886 - binary_crossentropy: 0.0587 - val_loss: 0.4414 - val_acc: 0.8630 - val_binary_crossentropy: 0.4414
Epoch 19/20
 - 3s - loss: 0.0541 - acc: 0.9903 - binary_crossentropy: 0.0541 - val_loss: 0.4531 - val_acc: 0.8630 - val_binary_crossentropy: 0.4531
Epoch 20/20
 - 3s - loss: 0.0497 - acc: 0.9914 - binary_crossentropy: 0.0497 - val_loss: 0.4701 - val_acc: 0.8617 - val_binary_crossentropy: 0.4701

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=(10000,)),
    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
 - 8s - loss: 0.3449 - acc: 0.8531 - binary_crossentropy: 0.3449 - val_loss: 0.2936 - val_acc: 0.8808 - val_binary_crossentropy: 0.2936
Epoch 2/20
 - 7s - loss: 0.1333 - acc: 0.9518 - binary_crossentropy: 0.1333 - val_loss: 0.3619 - val_acc: 0.8631 - val_binary_crossentropy: 0.3619
Epoch 3/20
 - 7s - loss: 0.0413 - acc: 0.9884 - binary_crossentropy: 0.0413 - val_loss: 0.4429 - val_acc: 0.8692 - val_binary_crossentropy: 0.4429
Epoch 4/20
 - 7s - loss: 0.0071 - acc: 0.9990 - binary_crossentropy: 0.0071 - val_loss: 0.5922 - val_acc: 0.8696 - val_binary_crossentropy: 0.5922
Epoch 5/20
 - 7s - loss: 8.2390e-04 - acc: 1.0000 - binary_crossentropy: 8.2390e-04 - val_loss: 0.6811 - val_acc: 0.8711 - val_binary_crossentropy: 0.6811
Epoch 6/20
 - 7s - loss: 2.2638e-04 - acc: 1.0000 - binary_crossentropy: 2.2638e-04 - val_loss: 0.7225 - val_acc: 0.8709 - val_binary_crossentropy: 0.7225
Epoch 7/20
 - 7s - loss: 1.3829e-04 - acc: 1.0000 - binary_crossentropy: 1.3829e-04 - val_loss: 0.7487 - val_acc: 0.8712 - val_binary_crossentropy: 0.7487
Epoch 8/20
 - 7s - loss: 9.8921e-05 - acc: 1.0000 - binary_crossentropy: 9.8921e-05 - val_loss: 0.7689 - val_acc: 0.8710 - val_binary_crossentropy: 0.7689
Epoch 9/20
 - 7s - loss: 7.4930e-05 - acc: 1.0000 - binary_crossentropy: 7.4930e-05 - val_loss: 0.7860 - val_acc: 0.8706 - val_binary_crossentropy: 0.7860
Epoch 10/20
 - 7s - loss: 5.8777e-05 - acc: 1.0000 - binary_crossentropy: 5.8777e-05 - val_loss: 0.8000 - val_acc: 0.8712 - val_binary_crossentropy: 0.8000
Epoch 11/20
 - 7s - loss: 4.7254e-05 - acc: 1.0000 - binary_crossentropy: 4.7254e-05 - val_loss: 0.8136 - val_acc: 0.8710 - val_binary_crossentropy: 0.8136
Epoch 12/20
 - 7s - loss: 3.8626e-05 - acc: 1.0000 - binary_crossentropy: 3.8626e-05 - val_loss: 0.8256 - val_acc: 0.8710 - val_binary_crossentropy: 0.8256
Epoch 13/20
 - 7s - loss: 3.2102e-05 - acc: 1.0000 - binary_crossentropy: 3.2102e-05 - val_loss: 0.8365 - val_acc: 0.8710 - val_binary_crossentropy: 0.8365
Epoch 14/20
 - 7s - loss: 2.7035e-05 - acc: 1.0000 - binary_crossentropy: 2.7035e-05 - val_loss: 0.8471 - val_acc: 0.8708 - val_binary_crossentropy: 0.8471
Epoch 15/20
 - 7s - loss: 2.2954e-05 - acc: 1.0000 - binary_crossentropy: 2.2954e-05 - val_loss: 0.8568 - val_acc: 0.8709 - val_binary_crossentropy: 0.8568
Epoch 16/20
 - 7s - loss: 1.9694e-05 - acc: 1.0000 - binary_crossentropy: 1.9694e-05 - val_loss: 0.8650 - val_acc: 0.8711 - val_binary_crossentropy: 0.8650
Epoch 17/20
 - 7s - loss: 1.7038e-05 - acc: 1.0000 - binary_crossentropy: 1.7038e-05 - val_loss: 0.8743 - val_acc: 0.8707 - val_binary_crossentropy: 0.8743
Epoch 18/20
 - 7s - loss: 1.4865e-05 - acc: 1.0000 - binary_crossentropy: 1.4865e-05 - val_loss: 0.8818 - val_acc: 0.8712 - val_binary_crossentropy: 0.8818
Epoch 19/20
 - 7s - loss: 1.3030e-05 - acc: 1.0000 - binary_crossentropy: 1.3030e-05 - val_loss: 0.8891 - val_acc: 0.8710 - val_binary_crossentropy: 0.8891
Epoch 20/20
 - 7s - loss: 1.1509e-05 - acc: 1.0000 - binary_crossentropy: 1.1509e-05 - val_loss: 0.8969 - val_acc: 0.8708 - val_binary_crossentropy: 0.8969

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=(10000,)),
    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
 - 4s - loss: 0.5413 - acc: 0.7902 - binary_crossentropy: 0.5012 - val_loss: 0.3929 - val_acc: 0.8796 - val_binary_crossentropy: 0.3520
Epoch 2/20
 - 3s - loss: 0.3120 - acc: 0.9081 - binary_crossentropy: 0.2663 - val_loss: 0.3363 - val_acc: 0.8867 - val_binary_crossentropy: 0.2871
Epoch 3/20
 - 3s - loss: 0.2570 - acc: 0.9292 - binary_crossentropy: 0.2053 - val_loss: 0.3370 - val_acc: 0.8871 - val_binary_crossentropy: 0.2835
Epoch 4/20
 - 3s - loss: 0.2309 - acc: 0.9404 - binary_crossentropy: 0.1758 - val_loss: 0.3484 - val_acc: 0.8833 - val_binary_crossentropy: 0.2923
Epoch 5/20
 - 3s - loss: 0.2174 - acc: 0.9464 - binary_crossentropy: 0.1598 - val_loss: 0.3605 - val_acc: 0.8803 - val_binary_crossentropy: 0.3020
Epoch 6/20
 - 3s - loss: 0.2044 - acc: 0.9518 - binary_crossentropy: 0.1454 - val_loss: 0.3756 - val_acc: 0.8766 - val_binary_crossentropy: 0.3162
Epoch 7/20
 - 3s - loss: 0.1980 - acc: 0.9531 - binary_crossentropy: 0.1376 - val_loss: 0.3902 - val_acc: 0.8733 - val_binary_crossentropy: 0.3289
Epoch 8/20
 - 3s - loss: 0.1892 - acc: 0.9583 - binary_crossentropy: 0.1273 - val_loss: 0.4007 - val_acc: 0.8729 - val_binary_crossentropy: 0.3386
Epoch 9/20
 - 3s - loss: 0.1831 - acc: 0.9595 - binary_crossentropy: 0.1206 - val_loss: 0.4157 - val_acc: 0.8712 - val_binary_crossentropy: 0.3527
Epoch 10/20
 - 3s - loss: 0.1811 - acc: 0.9605 - binary_crossentropy: 0.1174 - val_loss: 0.4338 - val_acc: 0.8667 - val_binary_crossentropy: 0.3696
Epoch 11/20
 - 3s - loss: 0.1759 - acc: 0.9628 - binary_crossentropy: 0.1111 - val_loss: 0.4464 - val_acc: 0.8647 - val_binary_crossentropy: 0.3810
Epoch 12/20
 - 3s - loss: 0.1732 - acc: 0.9632 - binary_crossentropy: 0.1076 - val_loss: 0.4715 - val_acc: 0.8594 - val_binary_crossentropy: 0.4055
Epoch 13/20
 - 3s - loss: 0.1723 - acc: 0.9637 - binary_crossentropy: 0.1053 - val_loss: 0.4685 - val_acc: 0.8623 - val_binary_crossentropy: 0.4012
Epoch 14/20
 - 3s - loss: 0.1618 - acc: 0.9674 - binary_crossentropy: 0.0947 - val_loss: 0.4780 - val_acc: 0.8596 - val_binary_crossentropy: 0.4112
Epoch 15/20
 - 3s - loss: 0.1559 - acc: 0.9716 - binary_crossentropy: 0.0893 - val_loss: 0.4882 - val_acc: 0.8607 - val_binary_crossentropy: 0.4216
Epoch 16/20
 - 3s - loss: 0.1540 - acc: 0.9723 - binary_crossentropy: 0.0871 - val_loss: 0.5042 - val_acc: 0.8582 - val_binary_crossentropy: 0.4371
Epoch 17/20
 - 3s - loss: 0.1518 - acc: 0.9726 - binary_crossentropy: 0.0846 - val_loss: 0.5104 - val_acc: 0.8570 - val_binary_crossentropy: 0.4428
Epoch 18/20
 - 3s - loss: 0.1505 - acc: 0.9723 - binary_crossentropy: 0.0826 - val_loss: 0.5334 - val_acc: 0.8559 - val_binary_crossentropy: 0.4651
Epoch 19/20
 - 3s - loss: 0.1478 - acc: 0.9729 - binary_crossentropy: 0.0794 - val_loss: 0.5345 - val_acc: 0.8583 - val_binary_crossentropy: 0.4659
Epoch 20/20
 - 3s - loss: 0.1481 - acc: 0.9726 - binary_crossentropy: 0.0790 - val_loss: 0.5437 - val_acc: 0.8550 - val_binary_crossentropy: 0.4741

l2(0.001) means that every coefficient in the weight matrix of the layer will add 0.001 * weight_coefficient_value 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=(10000,)),
    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
 - 4s - loss: 0.6051 - acc: 0.6668 - binary_crossentropy: 0.6051 - val_loss: 0.4621 - val_acc: 0.8550 - val_binary_crossentropy: 0.4621
Epoch 2/20
 - 3s - loss: 0.4313 - acc: 0.8227 - binary_crossentropy: 0.4313 - val_loss: 0.3240 - val_acc: 0.8838 - val_binary_crossentropy: 0.3240
Epoch 3/20
 - 3s - loss: 0.3388 - acc: 0.8751 - binary_crossentropy: 0.3388 - val_loss: 0.2842 - val_acc: 0.8888 - val_binary_crossentropy: 0.2842
Epoch 4/20
 - 3s - loss: 0.2795 - acc: 0.9042 - binary_crossentropy: 0.2795 - val_loss: 0.2754 - val_acc: 0.8894 - val_binary_crossentropy: 0.2754
Epoch 5/20
 - 4s - loss: 0.2404 - acc: 0.9159 - binary_crossentropy: 0.2404 - val_loss: 0.2776 - val_acc: 0.8864 - val_binary_crossentropy: 0.2776
Epoch 6/20
 - 3s - loss: 0.2091 - acc: 0.9293 - binary_crossentropy: 0.2091 - val_loss: 0.2878 - val_acc: 0.8866 - val_binary_crossentropy: 0.2878
Epoch 7/20
 - 3s - loss: 0.1816 - acc: 0.9373 - binary_crossentropy: 0.1816 - val_loss: 0.3080 - val_acc: 0.8848 - val_binary_crossentropy: 0.3080
Epoch 8/20
 - 3s - loss: 0.1634 - acc: 0.9461 - binary_crossentropy: 0.1634 - val_loss: 0.3227 - val_acc: 0.8838 - val_binary_crossentropy: 0.3227
Epoch 9/20
 - 3s - loss: 0.1457 - acc: 0.9517 - binary_crossentropy: 0.1457 - val_loss: 0.3426 - val_acc: 0.8826 - val_binary_crossentropy: 0.3426
Epoch 10/20
 - 3s - loss: 0.1357 - acc: 0.9558 - binary_crossentropy: 0.1357 - val_loss: 0.3422 - val_acc: 0.8803 - val_binary_crossentropy: 0.3422
Epoch 11/20
 - 3s - loss: 0.1222 - acc: 0.9581 - binary_crossentropy: 0.1222 - val_loss: 0.3651 - val_acc: 0.8797 - val_binary_crossentropy: 0.3651
Epoch 12/20
 - 3s - loss: 0.1120 - acc: 0.9622 - binary_crossentropy: 0.1120 - val_loss: 0.4039 - val_acc: 0.8793 - val_binary_crossentropy: 0.4039
Epoch 13/20
 - 3s - loss: 0.1042 - acc: 0.9626 - binary_crossentropy: 0.1042 - val_loss: 0.4221 - val_acc: 0.8772 - val_binary_crossentropy: 0.4221
Epoch 14/20
 - 3s - loss: 0.0928 - acc: 0.9688 - binary_crossentropy: 0.0928 - val_loss: 0.4469 - val_acc: 0.8782 - val_binary_crossentropy: 0.4469
Epoch 15/20
 - 3s - loss: 0.0917 - acc: 0.9674 - binary_crossentropy: 0.0917 - val_loss: 0.4704 - val_acc: 0.8758 - val_binary_crossentropy: 0.4704
Epoch 16/20
 - 3s - loss: 0.0846 - acc: 0.9699 - binary_crossentropy: 0.0846 - val_loss: 0.4858 - val_acc: 0.8751 - val_binary_crossentropy: 0.4858
Epoch 17/20
 - 3s - loss: 0.0800 - acc: 0.9704 - binary_crossentropy: 0.0800 - val_loss: 0.5085 - val_acc: 0.8767 - val_binary_crossentropy: 0.5085
Epoch 18/20
 - 3s - loss: 0.0749 - acc: 0.9728 - binary_crossentropy: 0.0749 - val_loss: 0.5353 - val_acc: 0.8740 - val_binary_crossentropy: 0.5353
Epoch 19/20
 - 3s - loss: 0.0715 - acc: 0.9741 - binary_crossentropy: 0.0715 - val_loss: 0.5607 - val_acc: 0.8734 - val_binary_crossentropy: 0.5607
Epoch 20/20
 - 3s - loss: 0.0692 - acc: 0.9756 - binary_crossentropy: 0.0692 - val_loss: 0.5359 - val_acc: 0.8750 - val_binary_crossentropy: 0.5359
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.