Overfit and underfit

Learn how to identify and avoid overfit and underfit models.

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

In both of the previous examples — classifying text and predicting fuel efficiency — the accuracy of models on the validation data would peak after training for a number of epochs and then stagnate or start decreasing.

In other words, your 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 you really want is to develop models that generalize well to a testing set (or data they haven’t seen before).

The opposite of overfitting is underfitting. Underfitting occurs when there is still room for improvement on the train 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. You need to strike a balance. Understanding how to train for an appropriate number of epochs as you’ll explore below is a useful skill.

To prevent overfitting, the best solution is to use more complete training data. The dataset should cover the full range of inputs that the model is expected to handle. Additional data may only be useful if it covers new and interesting cases.

A model trained on more complete 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, you’ll explore several common regularization techniques, and use them to improve on a classification model.

Setup

Before getting started, import the necessary packages:

library(tensorflow)
library(keras)
library(tfdatasets)
library(ggplot2)
logdir <- tempfile()

The Higgs dataset

The goal of this tutorial is not to do particle physics, so don’t dwell on the details of the dataset. It contains 11,000,000 examples, each with 28 features, and a binary class label.

gz <- get_file(
  'HIGGS.csv.gz',
  'http://mlphysics.ics.uci.edu/data/higgs/HIGGS.csv.gz'
)
FEATURES <- 28

The tf$data$experimental$CsvDataset class can be used to read csv records directly from a gzip file with no intermediate decompression step.

ds <- tf$data$experimental$CsvDataset(
  gz,
  lapply(seq_len(FEATURES + 1), function(x) tf$float32),
  compression_type = "GZIP"
)

That csv reader class returns a list of scalars for each record. The following function repacks that list of scalars into a (feature_vector, label) pair.

pack_row <- function(...) {
  row <- list(...)
  label <- row[[1]]
  features <- tf$stack(row[2:length(row)], 1L)
  list(features, label)
}

TensorFlow is most efficient when operating on large batches of data.

So, instead of repacking each row individually make a new tf$data$Dataset that takes batches of 10,000 examples, applies the pack_row function to each batch, and then splits the batches back up into individual records:

packed_ds <- ds %>%
  dataset_batch(10000) %>%
  dataset_map(pack_row)
packed_ds <- packed_ds$unbatch()

Inspect some of the records from this new packed_ds.

The features are not perfectly normalized, but this is sufficient for this tutorial.

batch <- packed_ds %>%
  dataset_batch(1000) %>%
  dataset_take(1) %>%
  reticulate::as_iterator() %>%
  reticulate::iter_next()
str(batch)
List of 2
 $ :<tf.Tensor: shape=(1000, 28), dtype=float32, numpy=…>
 $ :<tf.Tensor: shape=(1000), dtype=float32, numpy=…>

To keep this tutorial relatively short, use just the first 1,000 samples for validation, and the next 10,000 for training:

N_VALIDATION <- 1e3
N_TRAIN <- 1e4
BUFFER_SIZE <- 1e4
BATCH_SIZE <- 500
STEPS_PER_EPOCH <- N_TRAIN %/% BATCH_SIZE

The dataset_skip() and dataset_take() methods make this easy.

At the same time, use the dataset_cache() method to ensure that the loader doesn’t need to re-read the data from the file on each epoch:

validate_ds <- packed_ds %>%
  dataset_take(N_VALIDATION) %>%
  dataset_cache()
train_ds <- packed_ds %>%
  dataset_skip(N_VALIDATION) %>%
  dataset_take(N_TRAIN) %>%
  dataset_cache()
train_ds
<CacheDataset element_spec=(TensorSpec(shape=(28,), dtype=tf.float32, name=None), TensorSpec(shape=(), dtype=tf.float32, name=None))>

These datasets return individual examples. Use the dataset_batch() method to create batches of an appropriate size for training. Before batching, also remember to use dataset_shuffle() and dataset_repeat() on the training set.

validate_ds <- validate_ds %>% dataset_batch(BATCH_SIZE)
train_ds <- train_ds %>%
  dataset_shuffle(BUFFER_SIZE) %>%
  dataset_repeat() %>%
  dataset_batch(BATCH_SIZE)

Demonstrate overfitting

The simplest way to prevent overfitting is to start with a small model. A model with a small number of learnable parameters (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.

Start with a simple model using only densely-connected layers (tf$keras$layers$Dense) as a baseline, then create larger models, and compare them.

Training procedure

Many models train better if you gradually reduce the learning rate during training. Use keras::learning_rate_schedule* to reduce the learning rate over time:

lr_schedule <- learning_rate_schedule_inverse_time_decay(
  0.001,
  decay_steps = STEPS_PER_EPOCH*1000,
  decay_rate = 1,
  staircase = FALSE
)

get_optimizer <- function() {
  optimizer_adam(lr_schedule)
}

The code above sets a learning_rate_schedule_inverse_time_decay() to hyperbolically decrease the learning rate to 1/2 of the base rate at 1,000 epochs, 1/3 at 2,000 epochs, and so on.

step <- seq(1, 100000)
lr <- lr_schedule(step)
data.frame(step = as.numeric(step), lr = as.numeric(lr)) %>%
  ggplot(aes(x = step, y = lr)) +
  geom_line()

Each model in this tutorial will use the same training configuration. So set these up in a reusable way, starting with the list of callbacks.

The training for this tutorial runs for many short epochs.

We include callback_early_stopping() to avoid long and unnecessary training times. Note that this callback is set to monitor the val_binary_crossentropy, not the val_loss. This difference will be important later.

Use callback_tensorboard() to generate TensorBoard logs for the training.

get_callbacks <- function(name) {
  list(
    callback_early_stopping(monitor = 'val_binary_crossentropy', patience = 200),
    callback_tensorboard(file.path(logdir, name))
  )
}

Similarly each model will use the same compile() and fit() settings:

compile_and_fit <- function(model, name, optimizer = NULL, max_epochs = 10000) {
  if (is.null(optimizer)) {
    optimizer <- get_optimizer()
  }

  model %>% compile(
    optimizer = optimizer,
    loss = loss_binary_crossentropy(from_logits = TRUE),
    metrics = list(
      loss_binary_crossentropy(from_logits = TRUE, name = "binary_crossentropy"),
      "accuracy"
    )
  )

  summary(model)

  history <- model %>% fit(
    train_ds,
    steps_per_epoch = STEPS_PER_EPOCH,
    epochs = max_epochs,
    validation_data = validate_ds,
    callbacks = get_callbacks(name),
    verbose = 0
  )

  history
}

Tiny model

Start by training a model:

tiny_model <- keras_model_sequential() %>%
  layer_dense(16, activation = "elu", input_shape = shape(FEATURES)) %>%
  layer_dense(1)
size_histories <- list()
size_histories[['Tiny']] <- compile_and_fit(tiny_model, 'sizes/Tiny')
Model: "sequential"
____________________________________________________________________________
 Layer (type)                     Output Shape                  Param #     
============================================================================
 dense_1 (Dense)                  (None, 16)                    464         
 dense (Dense)                    (None, 1)                     17          
============================================================================
Total params: 481 (1.88 KB)
Trainable params: 481 (1.88 KB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________

Now check how the model did:

size_histories[["Tiny"]] %>%
  plot() +
  coord_cartesian(xlim = c(0, 5000))

Small model

To check if you can beat the performance of the small model, progressively train some larger models. Try two hidden layers with 16 units each:

small_model <- keras_model_sequential() %>%
  # `input_shape` is only required here so that `.summary` works.
  layer_dense(16, activation = 'elu', input_shape = shape(FEATURES)) %>%
  layer_dense(16, activation = 'elu') %>%
  layer_dense(1)
size_histories[['Small']] <- compile_and_fit(small_model, 'sizes/Small')
Model: "sequential_1"
____________________________________________________________________________
 Layer (type)                     Output Shape                  Param #     
============================================================================
 dense_4 (Dense)                  (None, 16)                    464         
 dense_3 (Dense)                  (None, 16)                    272         
 dense_2 (Dense)                  (None, 1)                     17          
============================================================================
Total params: 753 (2.94 KB)
Trainable params: 753 (2.94 KB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________

Medium model

Now try three hidden layers with 64 units each:

medium_model <- keras_model_sequential() %>%
  layer_dense(64, activation = 'elu', input_shape = shape(FEATURES)) %>%
  layer_dense(64, activation = 'elu') %>%
  layer_dense(64, activation = 'elu') %>%
  layer_dense(1)

And train the model using the same data:

size_histories[['Medium']] <- compile_and_fit(medium_model, "sizes/Medium")
Model: "sequential_2"
____________________________________________________________________________
 Layer (type)                     Output Shape                  Param #     
============================================================================
 dense_8 (Dense)                  (None, 64)                    1856        
 dense_7 (Dense)                  (None, 64)                    4160        
 dense_6 (Dense)                  (None, 64)                    4160        
 dense_5 (Dense)                  (None, 1)                     65          
============================================================================
Total params: 10241 (40.00 KB)
Trainable params: 10241 (40.00 KB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________

Large model

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

large_model <- keras_model_sequential() %>%
  layer_dense(512, activation = 'elu', input_shape = shape(FEATURES)) %>%
  layer_dense(512, activation = 'elu') %>%
  layer_dense(512, activation = 'elu') %>%
  layer_dense(512, activation = 'elu') %>%
  layer_dense(1)

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

size_histories[['large']] <- compile_and_fit(large_model, "sizes/large")
Model: "sequential_3"
____________________________________________________________________________
 Layer (type)                     Output Shape                  Param #     
============================================================================
 dense_13 (Dense)                 (None, 512)                   14848       
 dense_12 (Dense)                 (None, 512)                   262656      
 dense_11 (Dense)                 (None, 512)                   262656      
 dense_10 (Dense)                 (None, 512)                   262656      
 dense_9 (Dense)                  (None, 1)                     513         
============================================================================
Total params: 803329 (3.06 MB)
Trainable params: 803329 (3.06 MB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________

Plot the training and validation losses

The solid lines show the training loss, and the dashed lines show the validation loss (remember: a lower validation loss indicates a better model).

While building a larger model gives it more power, if this power is not constrained somehow it can easily overfit to the training set.

In this example, typically, only the "Tiny" model manages to avoid overfitting altogether, and each of the larger models overfit the data more quickly. This becomes so severe for the "large" model that you need to switch the plot to a log-scale to really figure out what’s happening.

This is apparent if you plot and compare the validation metrics to the training metrics.

  • It’s normal for there to be a small difference.
  • If both metrics are moving in the same direction, everything is fine.
  • If the validation metric begins to stagnate while the training metric continues to improve, you are probably close to overfitting.
  • If the validation metric is going in the wrong direction, the model is clearly overfitting.
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
plot_histories <- function(histories) {
  histories %>%
    purrr::map_dfr(as.data.frame, .id = "model") %>%
    filter(metric == "binary_crossentropy") %>%
    ggplot(aes(x = epoch, y = value, color = model, linetype = data)) +
    geom_smooth(se = FALSE) +
    coord_cartesian(ylim = c(0.5, 0.7)) +
    scale_x_log10()
}
plot_histories(size_histories)
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

Note: All the above training runs used the callback_ealry_stopping() to end the training once it was clear the model was not making progress.

View in TensorBoard

These models all wrote TensorBoard logs during training.

tensorboard(log_dir = logdir)

You can view the results of a previous run of this notebook on TensorBoard.dev.

TensorBoard.dev is a managed experience for hosting, tracking, and sharing ML experiments with everyone.

It’s also included in an <iframe> for convenience:

If you want to share TensorBoard results you can upload the logs to TensorBoard.dev by copying the following into a terminal session.

tensorboard dev upload --logdir logdir/sizes

Caution: This command does not terminate. It’s designed to continuously upload the results of long-running experiments. Once your data is uploaded you need to stop it using the “interrupt execution” option in your terminal tool.

Strategies to prevent overfitting

Before getting into the content of this section copy the training logs from the "Tiny" model above, to use as a baseline for comparison.

regularizer_histories <- list()
regularizer_histories[['Tiny']] <- size_histories[['Tiny']]

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 demonstrated 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 pushes weights towards exactly zero, encouraging a sparse model. L2 regularization will penalize the weights parameters without making them sparse since the penalty goes to zero for small weights—one reason why L2 is more common.

In tf$keras, weight regularization is added by passing weight regularizer instances to layers as keyword arguments. Add L2 weight regularization:

l2_model <- keras_model_sequential() %>%
  layer_dense(512, activation = 'elu',
              kernel_regularizer = regularizer_l2(0.001),
              input_shape <- shape(FEATURES)) %>%
  layer_dense(512, activation = 'elu',
              kernel_regularizer = regularizer_l2(0.001)) %>%
  layer_dense(512, activation = 'elu',
              kernel_regularizer = regularizer_l2(0.001)) %>%
  layer_dense(512, activation = 'elu',
              kernel_regularizer = regularizer_l2(0.001)) %>%
  layer_dense(1)
Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'

Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'

Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'

Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'
regularizer_histories[['l2']] <- compile_and_fit(l2_model, "regularizers/l2")
Model: <no summary available, model was not built>

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.

That is why we’re monitoring the binary_crossentropy directly. Because it doesn’t have this regularization component mixed in.

So, that same "Large" model with an L2 regularization penalty performs much better:

plot_histories(regularizer_histories)
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

As demonstrated in the diagram above, the "L2" regularized model is now much more competitive with the "Tiny" model. This "L2" model is also much more resistant to overfitting than the "Large" model it was based on despite having the same number of parameters.

More info

There are two important things to note about this sort of regularization:

  1. If you are writing your own training loop, then you need to be sure to ask the model for its regularization losses.
result <- l2_model(features)
regularization_loss <- tf$add_n(l2_model$losses)
  1. This implementation works by adding the weight penalties to the model’s loss, and then applying a standard optimization procedure after that.

There is a second approach that instead only runs the optimizer on the raw loss, and then while applying the calculated step the optimizer also applies some weight decay. This “decoupled weight decay” is used in optimizers like optimizer_ftrl() and optimizer_adamw().

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.

The intuitive explanation for dropout is that because individual nodes in the network cannot rely on the output of the others, each node must output features that are useful on their own.

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. For example, 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 Keras, you can introduce dropout in a network via the tf$keras$layers$Dropout layer, which gets applied to the output of layer right before.

Add two dropout layers to your network to check how well they do at reducing overfitting:

dropout_model <- keras_model_sequential() %>%
  layer_dense(512, activation = 'elu', input_shape = shape(FEATURES)) %>%
  layer_dropout(0.5) %>%
  layer_dense(512, activation = 'elu') %>%
  layer_dropout(0.5) %>%
  layer_dense(512, activation = 'elu') %>%
  layer_dropout(0.5) %>%
  layer_dense(512, activation = 'elu') %>%
  layer_dropout(0.5) %>%
  layer_dense(1)

regularizer_histories[['dropout']] <- compile_and_fit(dropout_model, "regularizers/dropout")
Model: "sequential_5"
____________________________________________________________________________
 Layer (type)                     Output Shape                  Param #     
============================================================================
 dense_23 (Dense)                 (None, 512)                   14848       
 dropout_3 (Dropout)              (None, 512)                   0           
 dense_22 (Dense)                 (None, 512)                   262656      
 dropout_2 (Dropout)              (None, 512)                   0           
 dense_21 (Dense)                 (None, 512)                   262656      
 dropout_1 (Dropout)              (None, 512)                   0           
 dense_20 (Dense)                 (None, 512)                   262656      
 dropout (Dropout)                (None, 512)                   0           
 dense_19 (Dense)                 (None, 1)                     513         
============================================================================
Total params: 803329 (3.06 MB)
Trainable params: 803329 (3.06 MB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________
plot_histories(regularizer_histories)
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

It’s clear from this plot that both of these regularization approaches improve the behavior of the "Large" model. But this still doesn’t beat even the "Tiny" baseline.

Next try them both, together, and see if that does better.

Combined L2 + dropout

combined_model <- keras_model_sequential() %>%
  layer_dense(512, kernel_regularizer = regularizer_l2(0.0001),
              activation = 'elu', input_shape = shape(FEATURES)) %>%
  layer_dropout(0.5) %>%
  layer_dense(512, kernel_regularizer = regularizer_l2(0.0001),
              activation = 'elu') %>%
  layer_dropout(0.5) %>%
  layer_dense(512, kernel_regularizer = regularizer_l2(0.0001),
              activation = 'elu') %>%
  layer_dropout(0.5) %>%
  layer_dense(512, kernel_regularizer = regularizer_l2(0.0001),
              activation = 'elu') %>%
  layer_dropout(0.5) %>%
  layer_dense(1)
Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'

Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'

Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'

Warning in keras$regularizers$l2(l = l): partial argument match of 'l' to
'l2'
regularizer_histories[['combined']] <- compile_and_fit(combined_model, "regularizers/combined")
Model: "sequential_6"
____________________________________________________________________________
 Layer (type)                     Output Shape                  Param #     
============================================================================
 dense_28 (Dense)                 (None, 512)                   14848       
 dropout_7 (Dropout)              (None, 512)                   0           
 dense_27 (Dense)                 (None, 512)                   262656      
 dropout_6 (Dropout)              (None, 512)                   0           
 dense_26 (Dense)                 (None, 512)                   262656      
 dropout_5 (Dropout)              (None, 512)                   0           
 dense_25 (Dense)                 (None, 512)                   262656      
 dropout_4 (Dropout)              (None, 512)                   0           
 dense_24 (Dense)                 (None, 1)                     513         
============================================================================
Total params: 803329 (3.06 MB)
Trainable params: 803329 (3.06 MB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________
plot_histories(regularizer_histories)
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

This model with the "Combined" regularization is obviously the best one so far.

View in TensorBoard

These models also recorded TensorBoard logs. Use the following to visualize the tensorboard:

tensorboard(file.path(logdir, "regularizers"))

You can view the results of a previous run of this notebook on TensorBoard.dev.

Conclusions

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.

Two important approaches not covered in this guide are:

Remember that each method can help on its own, but often combining them can be even more effective.