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 [==============================] - 3s 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
 - 2s - loss: 0.5007 - acc: 0.8012 - binary_crossentropy: 0.5007 - val_loss: 0.3494 - val_acc: 0.8729 - val_binary_crossentropy: 0.3494
Epoch 2/20
 - 2s - loss: 0.2577 - acc: 0.9078 - binary_crossentropy: 0.2577 - val_loss: 0.2851 - val_acc: 0.8871 - val_binary_crossentropy: 0.2851
Epoch 3/20
 - 2s - loss: 0.1846 - acc: 0.9349 - binary_crossentropy: 0.1846 - val_loss: 0.2894 - val_acc: 0.8849 - val_binary_crossentropy: 0.2894
Epoch 4/20
 - 2s - loss: 0.1445 - acc: 0.9516 - binary_crossentropy: 0.1445 - val_loss: 0.3165 - val_acc: 0.8804 - val_binary_crossentropy: 0.3165
Epoch 5/20
 - 2s - loss: 0.1168 - acc: 0.9622 - binary_crossentropy: 0.1168 - val_loss: 0.3437 - val_acc: 0.8749 - val_binary_crossentropy: 0.3437
Epoch 6/20
 - 2s - loss: 0.0928 - acc: 0.9718 - binary_crossentropy: 0.0928 - val_loss: 0.3756 - val_acc: 0.8708 - val_binary_crossentropy: 0.3756
Epoch 7/20
 - 2s - loss: 0.0734 - acc: 0.9801 - binary_crossentropy: 0.0734 - val_loss: 0.4244 - val_acc: 0.8627 - val_binary_crossentropy: 0.4244
Epoch 8/20
 - 2s - loss: 0.0583 - acc: 0.9861 - binary_crossentropy: 0.0583 - val_loss: 0.4600 - val_acc: 0.8624 - val_binary_crossentropy: 0.4600
Epoch 9/20
 - 2s - loss: 0.0452 - acc: 0.9908 - binary_crossentropy: 0.0452 - val_loss: 0.4988 - val_acc: 0.8613 - val_binary_crossentropy: 0.4988
Epoch 10/20
 - 2s - loss: 0.0341 - acc: 0.9940 - binary_crossentropy: 0.0341 - val_loss: 0.5442 - val_acc: 0.8584 - val_binary_crossentropy: 0.5442
Epoch 11/20
 - 2s - loss: 0.0256 - acc: 0.9965 - binary_crossentropy: 0.0256 - val_loss: 0.5814 - val_acc: 0.8574 - val_binary_crossentropy: 0.5814
Epoch 12/20
 - 2s - loss: 0.0188 - acc: 0.9982 - binary_crossentropy: 0.0188 - val_loss: 0.6234 - val_acc: 0.8558 - val_binary_crossentropy: 0.6234
Epoch 13/20
 - 2s - loss: 0.0133 - acc: 0.9989 - binary_crossentropy: 0.0133 - val_loss: 0.6586 - val_acc: 0.8551 - val_binary_crossentropy: 0.6586
Epoch 14/20
 - 2s - loss: 0.0094 - acc: 0.9996 - binary_crossentropy: 0.0094 - val_loss: 0.6936 - val_acc: 0.8534 - val_binary_crossentropy: 0.6936
Epoch 15/20
 - 2s - loss: 0.0067 - acc: 0.9999 - binary_crossentropy: 0.0067 - val_loss: 0.7204 - val_acc: 0.8544 - val_binary_crossentropy: 0.7204
Epoch 16/20
 - 2s - loss: 0.0051 - acc: 0.9999 - binary_crossentropy: 0.0051 - val_loss: 0.7471 - val_acc: 0.8538 - val_binary_crossentropy: 0.7471
Epoch 17/20
 - 2s - loss: 0.0040 - acc: 1.0000 - binary_crossentropy: 0.0040 - val_loss: 0.7696 - val_acc: 0.8544 - val_binary_crossentropy: 0.7696
Epoch 18/20
 - 2s - loss: 0.0032 - acc: 1.0000 - binary_crossentropy: 0.0032 - val_loss: 0.7895 - val_acc: 0.8534 - val_binary_crossentropy: 0.7895
Epoch 19/20
 - 2s - loss: 0.0026 - acc: 1.0000 - binary_crossentropy: 0.0026 - val_loss: 0.8083 - val_acc: 0.8546 - val_binary_crossentropy: 0.8083
Epoch 20/20
 - 2s - loss: 0.0021 - acc: 1.0000 - binary_crossentropy: 0.0021 - val_loss: 0.8241 - val_acc: 0.8536 - val_binary_crossentropy: 0.8241

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
 - 2s - loss: 0.6277 - acc: 0.6536 - binary_crossentropy: 0.6277 - val_loss: 0.5731 - val_acc: 0.7359 - val_binary_crossentropy: 0.5731
Epoch 2/20
 - 2s - loss: 0.5234 - acc: 0.8071 - binary_crossentropy: 0.5234 - val_loss: 0.5148 - val_acc: 0.8075 - val_binary_crossentropy: 0.5148
Epoch 3/20
 - 2s - loss: 0.4672 - acc: 0.8675 - binary_crossentropy: 0.4672 - val_loss: 0.4815 - val_acc: 0.8463 - val_binary_crossentropy: 0.4815
Epoch 4/20
 - 2s - loss: 0.4286 - acc: 0.8976 - binary_crossentropy: 0.4286 - val_loss: 0.4600 - val_acc: 0.8690 - val_binary_crossentropy: 0.4600
Epoch 5/20
 - 2s - loss: 0.3993 - acc: 0.9172 - binary_crossentropy: 0.3993 - val_loss: 0.4453 - val_acc: 0.8793 - val_binary_crossentropy: 0.4453
Epoch 6/20
 - 2s - loss: 0.3745 - acc: 0.9303 - binary_crossentropy: 0.3745 - val_loss: 0.4402 - val_acc: 0.8670 - val_binary_crossentropy: 0.4402
Epoch 7/20
 - 2s - loss: 0.3525 - acc: 0.9404 - binary_crossentropy: 0.3525 - val_loss: 0.4333 - val_acc: 0.8714 - val_binary_crossentropy: 0.4333
Epoch 8/20
 - 2s - loss: 0.3330 - acc: 0.9481 - binary_crossentropy: 0.3330 - val_loss: 0.4244 - val_acc: 0.8777 - val_binary_crossentropy: 0.4244
Epoch 9/20
 - 2s - loss: 0.3156 - acc: 0.9555 - binary_crossentropy: 0.3156 - val_loss: 0.4228 - val_acc: 0.8766 - val_binary_crossentropy: 0.4228
Epoch 10/20
 - 2s - loss: 0.2994 - acc: 0.9618 - binary_crossentropy: 0.2994 - val_loss: 0.4182 - val_acc: 0.8783 - val_binary_crossentropy: 0.4182
Epoch 11/20
 - 2s - loss: 0.2850 - acc: 0.9658 - binary_crossentropy: 0.2850 - val_loss: 0.4217 - val_acc: 0.8747 - val_binary_crossentropy: 0.4217
Epoch 12/20
 - 2s - loss: 0.2706 - acc: 0.9707 - binary_crossentropy: 0.2706 - val_loss: 0.4241 - val_acc: 0.8738 - val_binary_crossentropy: 0.4241
Epoch 13/20
 - 2s - loss: 0.2577 - acc: 0.9737 - binary_crossentropy: 0.2577 - val_loss: 0.4313 - val_acc: 0.8706 - val_binary_crossentropy: 0.4313
Epoch 14/20
 - 2s - loss: 0.2456 - acc: 0.9767 - binary_crossentropy: 0.2456 - val_loss: 0.4268 - val_acc: 0.8724 - val_binary_crossentropy: 0.4268
Epoch 15/20
 - 2s - loss: 0.2347 - acc: 0.9795 - binary_crossentropy: 0.2347 - val_loss: 0.4352 - val_acc: 0.8703 - val_binary_crossentropy: 0.4352
Epoch 16/20
 - 2s - loss: 0.2242 - acc: 0.9810 - binary_crossentropy: 0.2242 - val_loss: 0.4415 - val_acc: 0.8689 - val_binary_crossentropy: 0.4415
Epoch 17/20
 - 2s - loss: 0.2150 - acc: 0.9832 - binary_crossentropy: 0.2150 - val_loss: 0.4476 - val_acc: 0.8682 - val_binary_crossentropy: 0.4476
Epoch 18/20
 - 2s - loss: 0.2058 - acc: 0.9846 - binary_crossentropy: 0.2058 - val_loss: 0.4385 - val_acc: 0.8707 - val_binary_crossentropy: 0.4385
Epoch 19/20
 - 2s - loss: 0.1973 - acc: 0.9856 - binary_crossentropy: 0.1973 - val_loss: 0.4564 - val_acc: 0.8666 - val_binary_crossentropy: 0.4564
Epoch 20/20
 - 2s - loss: 0.1895 - acc: 0.9866 - binary_crossentropy: 0.1895 - val_loss: 0.4691 - val_acc: 0.8659 - val_binary_crossentropy: 0.4691

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
 - 6s - loss: 0.3469 - acc: 0.8521 - binary_crossentropy: 0.3469 - val_loss: 0.2975 - val_acc: 0.8787 - val_binary_crossentropy: 0.2975
Epoch 2/20
 - 5s - loss: 0.1326 - acc: 0.9519 - binary_crossentropy: 0.1326 - val_loss: 0.3676 - val_acc: 0.8620 - val_binary_crossentropy: 0.3676
Epoch 3/20
 - 6s - loss: 0.0400 - acc: 0.9892 - binary_crossentropy: 0.0400 - val_loss: 0.4453 - val_acc: 0.8691 - val_binary_crossentropy: 0.4453
Epoch 4/20
 - 6s - loss: 0.0062 - acc: 0.9991 - binary_crossentropy: 0.0062 - val_loss: 0.5866 - val_acc: 0.8700 - val_binary_crossentropy: 0.5866
Epoch 5/20
 - 6s - loss: 9.7459e-04 - acc: 1.0000 - binary_crossentropy: 9.7459e-04 - val_loss: 0.6634 - val_acc: 0.8706 - val_binary_crossentropy: 0.6634
Epoch 6/20
 - 5s - loss: 2.5291e-04 - acc: 1.0000 - binary_crossentropy: 2.5291e-04 - val_loss: 0.7083 - val_acc: 0.8715 - val_binary_crossentropy: 0.7083
Epoch 7/20
 - 5s - loss: 1.4555e-04 - acc: 1.0000 - binary_crossentropy: 1.4555e-04 - val_loss: 0.7359 - val_acc: 0.8714 - val_binary_crossentropy: 0.7359
Epoch 8/20
 - 5s - loss: 1.0164e-04 - acc: 1.0000 - binary_crossentropy: 1.0164e-04 - val_loss: 0.7572 - val_acc: 0.8713 - val_binary_crossentropy: 0.7572
Epoch 9/20
 - 5s - loss: 7.5574e-05 - acc: 1.0000 - binary_crossentropy: 7.5574e-05 - val_loss: 0.7768 - val_acc: 0.8713 - val_binary_crossentropy: 0.7768
Epoch 10/20
 - 5s - loss: 5.8227e-05 - acc: 1.0000 - binary_crossentropy: 5.8227e-05 - val_loss: 0.7929 - val_acc: 0.8715 - val_binary_crossentropy: 0.7929
Epoch 11/20
 - 6s - loss: 4.5927e-05 - acc: 1.0000 - binary_crossentropy: 4.5927e-05 - val_loss: 0.8084 - val_acc: 0.8716 - val_binary_crossentropy: 0.8084
Epoch 12/20
 - 6s - loss: 3.6884e-05 - acc: 1.0000 - binary_crossentropy: 3.6884e-05 - val_loss: 0.8226 - val_acc: 0.8717 - val_binary_crossentropy: 0.8226
Epoch 13/20
 - 6s - loss: 3.0095e-05 - acc: 1.0000 - binary_crossentropy: 3.0095e-05 - val_loss: 0.8348 - val_acc: 0.8719 - val_binary_crossentropy: 0.8348
Epoch 14/20
 - 5s - loss: 2.4907e-05 - acc: 1.0000 - binary_crossentropy: 2.4907e-05 - val_loss: 0.8475 - val_acc: 0.8718 - val_binary_crossentropy: 0.8475
Epoch 15/20
 - 5s - loss: 2.0810e-05 - acc: 1.0000 - binary_crossentropy: 2.0810e-05 - val_loss: 0.8587 - val_acc: 0.8718 - val_binary_crossentropy: 0.8587
Epoch 16/20
 - 5s - loss: 1.7592e-05 - acc: 1.0000 - binary_crossentropy: 1.7592e-05 - val_loss: 0.8683 - val_acc: 0.8722 - val_binary_crossentropy: 0.8683
Epoch 17/20
 - 6s - loss: 1.5003e-05 - acc: 1.0000 - binary_crossentropy: 1.5003e-05 - val_loss: 0.8799 - val_acc: 0.8719 - val_binary_crossentropy: 0.8799
Epoch 18/20
 - 5s - loss: 1.2921e-05 - acc: 1.0000 - binary_crossentropy: 1.2921e-05 - val_loss: 0.8884 - val_acc: 0.8717 - val_binary_crossentropy: 0.8884
Epoch 19/20
 - 5s - loss: 1.1134e-05 - acc: 1.0000 - binary_crossentropy: 1.1134e-05 - val_loss: 0.8979 - val_acc: 0.8718 - val_binary_crossentropy: 0.8979
Epoch 20/20
 - 5s - loss: 9.6089e-06 - acc: 1.0000 - binary_crossentropy: 9.6089e-06 - val_loss: 0.9090 - val_acc: 0.8718 - val_binary_crossentropy: 0.9090

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
 - 2s - loss: 0.5073 - acc: 0.8134 - binary_crossentropy: 0.4637 - val_loss: 0.3709 - val_acc: 0.8808 - val_binary_crossentropy: 0.3251
Epoch 2/20
 - 2s - loss: 0.2987 - acc: 0.9122 - binary_crossentropy: 0.2492 - val_loss: 0.3351 - val_acc: 0.8882 - val_binary_crossentropy: 0.2830
Epoch 3/20
 - 2s - loss: 0.2520 - acc: 0.9308 - binary_crossentropy: 0.1977 - val_loss: 0.3400 - val_acc: 0.8853 - val_binary_crossentropy: 0.2841
Epoch 4/20
 - 2s - loss: 0.2281 - acc: 0.9418 - binary_crossentropy: 0.1707 - val_loss: 0.3530 - val_acc: 0.8823 - val_binary_crossentropy: 0.2947
Epoch 5/20
 - 2s - loss: 0.2156 - acc: 0.9477 - binary_crossentropy: 0.1557 - val_loss: 0.3663 - val_acc: 0.8792 - val_binary_crossentropy: 0.3055
Epoch 6/20
 - 2s - loss: 0.2031 - acc: 0.9519 - binary_crossentropy: 0.1416 - val_loss: 0.3824 - val_acc: 0.8755 - val_binary_crossentropy: 0.3204
Epoch 7/20
 - 2s - loss: 0.1966 - acc: 0.9549 - binary_crossentropy: 0.1336 - val_loss: 0.3976 - val_acc: 0.8721 - val_binary_crossentropy: 0.3339
Epoch 8/20
 - 2s - loss: 0.1894 - acc: 0.9586 - binary_crossentropy: 0.1249 - val_loss: 0.4085 - val_acc: 0.8707 - val_binary_crossentropy: 0.3437
Epoch 9/20
 - 2s - loss: 0.1841 - acc: 0.9590 - binary_crossentropy: 0.1188 - val_loss: 0.4251 - val_acc: 0.8696 - val_binary_crossentropy: 0.3592
Epoch 10/20
 - 2s - loss: 0.1828 - acc: 0.9603 - binary_crossentropy: 0.1163 - val_loss: 0.4421 - val_acc: 0.8654 - val_binary_crossentropy: 0.3751
Epoch 11/20
 - 2s - loss: 0.1785 - acc: 0.9626 - binary_crossentropy: 0.1110 - val_loss: 0.4522 - val_acc: 0.8643 - val_binary_crossentropy: 0.3841
Epoch 12/20
 - 2s - loss: 0.1759 - acc: 0.9626 - binary_crossentropy: 0.1077 - val_loss: 0.4769 - val_acc: 0.8598 - val_binary_crossentropy: 0.4084
Epoch 13/20
 - 2s - loss: 0.1762 - acc: 0.9626 - binary_crossentropy: 0.1067 - val_loss: 0.4735 - val_acc: 0.8615 - val_binary_crossentropy: 0.4037
Epoch 14/20
 - 2s - loss: 0.1675 - acc: 0.9667 - binary_crossentropy: 0.0977 - val_loss: 0.4825 - val_acc: 0.8600 - val_binary_crossentropy: 0.4131
Epoch 15/20
 - 2s - loss: 0.1622 - acc: 0.9696 - binary_crossentropy: 0.0930 - val_loss: 0.4952 - val_acc: 0.8592 - val_binary_crossentropy: 0.4258
Epoch 16/20
 - 2s - loss: 0.1608 - acc: 0.9700 - binary_crossentropy: 0.0912 - val_loss: 0.5082 - val_acc: 0.8574 - val_binary_crossentropy: 0.4384
Epoch 17/20
 - 2s - loss: 0.1595 - acc: 0.9696 - binary_crossentropy: 0.0897 - val_loss: 0.5156 - val_acc: 0.8558 - val_binary_crossentropy: 0.4454
Epoch 18/20
 - 2s - loss: 0.1589 - acc: 0.9692 - binary_crossentropy: 0.0884 - val_loss: 0.5339 - val_acc: 0.8555 - val_binary_crossentropy: 0.4630
Epoch 19/20
 - 2s - loss: 0.1576 - acc: 0.9698 - binary_crossentropy: 0.0866 - val_loss: 0.5339 - val_acc: 0.8592 - val_binary_crossentropy: 0.4626
Epoch 20/20
 - 2s - loss: 0.1581 - acc: 0.9696 - binary_crossentropy: 0.0863 - val_loss: 0.5478 - val_acc: 0.8547 - val_binary_crossentropy: 0.4756

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
 - 2s - loss: 0.6219 - acc: 0.6442 - binary_crossentropy: 0.6219 - val_loss: 0.4819 - val_acc: 0.8539 - val_binary_crossentropy: 0.4819
Epoch 2/20
 - 2s - loss: 0.4647 - acc: 0.7940 - binary_crossentropy: 0.4647 - val_loss: 0.3491 - val_acc: 0.8795 - val_binary_crossentropy: 0.3491
Epoch 3/20
 - 2s - loss: 0.3617 - acc: 0.8563 - binary_crossentropy: 0.3617 - val_loss: 0.2897 - val_acc: 0.8862 - val_binary_crossentropy: 0.2897
Epoch 4/20
 - 2s - loss: 0.2967 - acc: 0.8929 - binary_crossentropy: 0.2967 - val_loss: 0.2760 - val_acc: 0.8865 - val_binary_crossentropy: 0.2760
Epoch 5/20
 - 2s - loss: 0.2543 - acc: 0.9135 - binary_crossentropy: 0.2543 - val_loss: 0.2759 - val_acc: 0.8870 - val_binary_crossentropy: 0.2759
Epoch 6/20
 - 2s - loss: 0.2189 - acc: 0.9266 - binary_crossentropy: 0.2189 - val_loss: 0.2873 - val_acc: 0.8860 - val_binary_crossentropy: 0.2873
Epoch 7/20
 - 2s - loss: 0.1904 - acc: 0.9364 - binary_crossentropy: 0.1904 - val_loss: 0.3064 - val_acc: 0.8853 - val_binary_crossentropy: 0.3064
Epoch 8/20
 - 2s - loss: 0.1696 - acc: 0.9450 - binary_crossentropy: 0.1696 - val_loss: 0.3126 - val_acc: 0.8828 - val_binary_crossentropy: 0.3126
Epoch 9/20
 - 2s - loss: 0.1610 - acc: 0.9481 - binary_crossentropy: 0.1610 - val_loss: 0.3294 - val_acc: 0.8801 - val_binary_crossentropy: 0.3294
Epoch 10/20
 - 2s - loss: 0.1446 - acc: 0.9519 - binary_crossentropy: 0.1446 - val_loss: 0.3490 - val_acc: 0.8808 - val_binary_crossentropy: 0.3490
Epoch 11/20
 - 2s - loss: 0.1288 - acc: 0.9569 - binary_crossentropy: 0.1288 - val_loss: 0.3677 - val_acc: 0.8792 - val_binary_crossentropy: 0.3677
Epoch 12/20
 - 2s - loss: 0.1185 - acc: 0.9598 - binary_crossentropy: 0.1185 - val_loss: 0.4013 - val_acc: 0.8782 - val_binary_crossentropy: 0.4013
Epoch 13/20
 - 2s - loss: 0.1112 - acc: 0.9636 - binary_crossentropy: 0.1112 - val_loss: 0.4135 - val_acc: 0.8775 - val_binary_crossentropy: 0.4135
Epoch 14/20
 - 2s - loss: 0.1007 - acc: 0.9650 - binary_crossentropy: 0.1007 - val_loss: 0.4463 - val_acc: 0.8780 - val_binary_crossentropy: 0.4463
Epoch 15/20
 - 2s - loss: 0.0932 - acc: 0.9676 - binary_crossentropy: 0.0932 - val_loss: 0.4808 - val_acc: 0.8772 - val_binary_crossentropy: 0.4808
Epoch 16/20
 - 2s - loss: 0.0887 - acc: 0.9685 - binary_crossentropy: 0.0887 - val_loss: 0.4612 - val_acc: 0.8759 - val_binary_crossentropy: 0.4612
Epoch 17/20
 - 2s - loss: 0.0865 - acc: 0.9690 - binary_crossentropy: 0.0865 - val_loss: 0.5000 - val_acc: 0.8779 - val_binary_crossentropy: 0.5000
Epoch 18/20
 - 2s - loss: 0.0779 - acc: 0.9716 - binary_crossentropy: 0.0779 - val_loss: 0.5124 - val_acc: 0.8772 - val_binary_crossentropy: 0.5124
Epoch 19/20
 - 2s - loss: 0.0771 - acc: 0.9720 - binary_crossentropy: 0.0771 - val_loss: 0.5115 - val_acc: 0.8758 - val_binary_crossentropy: 0.5115
Epoch 20/20
 - 2s - loss: 0.0722 - acc: 0.9733 - binary_crossentropy: 0.0722 - val_loss: 0.5403 - val_acc: 0.8745 - val_binary_crossentropy: 0.5403
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.