Adding Dropout to Neural Networks in PyTorch
Introduction: Why Use Dropout?
Welcome back! In the last lesson, you learned how to build, train, and evaluate a simple neural network in PyTorch. You also saw how to monitor validation loss to check for overfitting — a common problem where a model performs well on training data but struggles with new, unseen data. As a quick reminder, overfitting happens when a model learns the training data too well, including its noise and random details, which makes it less effective on real-world data.
To address overfitting, one of the most popular and easy-to-use techniques is called dropout. Dropout is a regularization method that helps your neural network generalize better, so it can perform well not just on the training data but also on new data it has never seen before. In this lesson, you will learn what dropout is, how it works, and how to add it to your PyTorch models.
How Dropout Works
The main idea behind dropout is simple but powerful. During training, dropout randomly "drops out" (sets to zero) a fraction of the neurons in a layer on each forward pass. This means that each time the model sees a batch of data, it uses a slightly different set of neurons. As a result, the network cannot rely too much on any single neuron and is forced to learn more robust features.
Typically, dropout is applied after the activation function of hidden layers, not on the input or output layers. Applying dropout after the activation function is preferred because the activation function introduces non-linearity and transforms the raw outputs of the neurons. By applying dropout after this transformation, you are zeroing out the actual activated outputs (the features that are passed to the next layer), which is more consistent with the intended effect of dropout: to prevent the network from relying too much on specific activated features. If dropout were applied before the activation, it would zero out the raw, unactivated values, which could change the distribution of inputs to the activation function in unpredictable ways. Empirically, applying dropout after the activation has been shown to work better and is the standard practice.
The most common dropout rate is 0.5, which means that half of the neurons are randomly dropped during each training step. During evaluation (when you are testing or using the model), dropout is turned off, and all neurons are used.
This simple trick helps prevent the network from becoming too specialized to the training data, making it more likely to perform well on new data.
