Forge
Skip to main content

Tutorial: PyTorch Dropout for regularization

Learn how to regularize your PyTorch model and reduce overfitting with Dropout, complete with a code tutorial and interactive visualizations.
Last updated: February 26, 2026
In this report, we'll see an example of adding dropout regularization to a PyTorch model and observe its effect on the model's performance by tracking it in Weights & Biases.
Dropout is a staple in deep learning because it’s a simple code change that drastically improves how your model handles unseen data. If you’re already familiar with dropout, feel free to jump straight to the tutorial.
Jump to the tutorial


What we'll be covering



What is Dropout regularization in machine learning?

Dropout regularization is a machine learning technique in which units are removed (or "dropped out") from a neural network to simulate training multiple architectures simultaneously. Importantly, dropout can drastically reduce the chance of overfitting during training.

Overfitting occurs when a neural network learns the training data too well, including its noise and specific patterns, leading to poor performance on new, unseen data. Dropout addresses this by introducing randomness during training. By randomly "dropping out" (setting to zero) a fraction of neurons in each training iteration, you prevent the network from relying too heavily on any single neuron or feature. This encourages the network to learn more distributed and robust representations.
This also mitigates co-adaptation, in which neurons become overly specialized to work together, hindering generalization. The concept of dropout was introduced by Hinton et al. in the 2012 paper Improving neural networks by preventing co-adaptation of feature detectors, and has since become a staple in deep learning, significantly impacting the field by improving the generalization capabilities of models.

Run an example of dropout in PyTorch in this Colab →



Why dropout matters in PyTorch neural networks

Dropout regularization randomly disables neurons during training. The purpose in PyTorch is to prevent overfitting and coadaptation, improving generalization with a tiny code change. In the context of a NeuralNet, a Dropout Function masks a fraction of activations in hidden layers so the model cannot rely on any single path.
The idea was introduced in the paper Improving neural networks by preventing coadaptation of feature detectors, and it remains a default choice for regularization in many architectures. In this tutorial, you will build models with and without Hidden Layers Dropout, compare runs in W&B, and optionally view them through W&B Models or create an interactive analysis with W&B Weave.

How dropout regularization works

Dropout regularization works by randomly dropping units on each forward pass. For every minibatch, each unit is independently dropped with probability p, and surviving activations are scaled to keep their expected magnitude stable. This breaks coadaptation, where neurons rely too strongly on specific peers, and encourages redundant, distributed representations. The result is an implicit ensemble: training many subnetworks that share weights and collectively improve robustness. Dropout is conceptually different from L1 or L2 weight penalties. L1 and L2 act directly on parameters through deterministic penalties, while dropout stochastically perturbs activations during training.

PyTorch dropout layers: The core API you need

PyTorch implements dropout through a family of layers:
  • (p=0.5, inplace=False): pointwise dropout for dense activations.
  • nn.Dropout1d, nn.Dropout2d, nn.Dropout3d: structured variants that often operate channelwise for 1D, 2D, or 3D feature maps.
  • (p): tailored for self-normalizing networks using SELU, preserving mean and variance.
During training mode (()), dropout zeroes elements with probability p and rescales the rest by 1/(1p). During evaluation (()), dropout is disabled and tensors pass through unchanged. The purpose of using dropout in PyTorch during training is to reduce overfitting by injecting stochasticity into activations while preserving expected activation scale via rescaling. Alpha Dropout keeps the activation statistics stable under SELU, which expects selfnormalizing behavior.

Understanding the dropout probability p

Dropout probability p is the fraction of elements expected to be set to zero each forward pass. What does dropout 0.5 mean? It means each activation has a 50% chance of being dropped on every training pass. The layer multiplies surviving activations by 1/(1p) so the expected activation magnitude matches evaluation time. Typical ranges:
  • Input layer: p around 0.1 to 0.3 to avoid removing too much signal.
  • Hidden layers: p around 0.3 to 0.7, depending on model size and dataset.
A larger p increases regularization and can reduce overfitting, but it may slow learning and cause underfitting if set too high.

How PyTorch chooses which elements to drop

A dropout layer samples a Bernoulli mask for each forward pass. For standard settings, each element is kept with probability p and dropped with probability 1-p. Variants like Dropout1d can sample masks per feature channel. Randomness is per batch and per call, so outcomes differ across minibatches and epochs.
You can make runs reproducible by setting seeds for torch, numpy, and Python’s random.

Where to place dropout: Before or after activation?

The placement of dropout layers within a neural network is crucial for its effectiveness. While dropout can be applied in various locations, it's commonly used after activation functions in hidden layers and sometimes in the input layer. The strategic placement of dropout can significantly impact the model's performance.
Applying dropout after activation functions in hidden layers is a common practice. This helps prevent overfitting by reducing co-adaptation among neurons within those layers. However, the optimal placement can vary depending on the specific architecture and task.
For example, in deeper networks, dropout might be more beneficial in the earlier layers. Applying dropout to the input layer can be useful for feature selection, as it forces the model to learn more robust representations by not relying on any single input feature. However, it's important to note that applying too much dropout in the input layer can lead to underfitting.
The decision of where to apply dropout is often empirical, requiring experimentation to find the best configuration for a given task.

Does dropout actually reduce overfitting?

Yes, when correctly used, Dropout regularization typically reduces overfitting. It narrows the performance gap between training and validation by acting as an implicit ensemble and reducing variance. It encourages robust features that do not depend on specific neurons. Dropout can hurt if the dataset is extremely small, the model is tiny, or the rate is too high, leading to underfitting.
Dropout is neither L1 nor L2; it often complements early stopping, data augmentation, and weight decay (L2).

Comparing dropout to L1 and L2 regularization

Dropout is neither L1 nor L2. L1 adds an absolute-value penalty that promotes sparsity in the weights. L2 (weight decay) adds a squared penalty that discourages large weights. Both are deterministic penalties on parameters. Dropout is a stochastic activation masking and rescaling technique. Many practitioners combine dropout with L2 weight decay in optimizers to jointly control parameter magnitude and activation-level coadaptation. They target different aspects of complexity and can work together.

Understanding PyTorch's torch.nn.Dropout

PyTorch provides a convenient way to implement dropout using the torch.nn.Dropout class. This class randomly zeroes elements of an input tensor during training, effectively "dropping out" neurons. The key parameters are p, which defines the probability of zeroing an element, and inplace, which determines whether the operation is performed in-place.
The p parameter, often called the dropout rate, controls the fraction of neurons randomly deactivated at each training step. A higher p value means more neurons are dropped, leading to stronger regularization. Typical values for p range from 0.2 to 0.5, but the optimal value depends on the specific network and dataset.
The inplace parameter, when set to True, modifies the input tensor directly, saving memory. However, it's important to note that in-place operations can sometimes be less flexible and may not be suitable for all situations.
Here's a simple code example demonstrating how to instantiate and use nn.Dropout

Impact of using Dropout regularization in PyTorch

You may be asking, "What is the impact of using Dropout regularization?" With it you'll see:
  • An unregularized network quickly overfits on the training dataset. Notice how the validation loss for without-dropout run diverges a lot after just a few epochs. This accounts for the higher generalization error.
  • Training with two dropout layers with a dropout probability of 25% prevents the model from overfitting. However, this reduces training accuracy, so a regularized network must be trained longer.
  • Dropout improves the model's generalization. Even though the training accuracy is lower than the unregularized network, the overall validation accuracy has improved. This results in lower generalization error.

Tutorial: Adding Dropout to a PyTorch model

Here are simple step-by-step instructions for adding dropout regularization to a PyTorch model.

1. Add Dropout to a PyTorch model

Adding dropout to your PyTorch models is very straightforward with the torch.nn.Dropout class, which takes in the dropout rate – the probability of a neuron being deactivated – as a parameter.
self.dropout = nn.Dropout(0.25)
We can apply dropout after any non-output layer.

2. Observe the effect of Dropout on odel performance

To observe the dropout effect, train a model to do image classification. We'll first train an unregularized network, followed by a regularized network using Dropout. The models are trained on the Cifar-10 dataset for 15 epochs each.

A complete example of adding dropout to a PyTorch model:

class Net(nn.Module):
def __init__(self, input_shape=(3,32,32)):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3)
self.conv2 = nn.Conv2d(32, 64, 3)
self.conv3 = nn.Conv2d(64, 128, 3)
self.pool = nn.MaxPool2d(2,2)

n_size = self._get_conv_output(input_shape)
self.fc1 = nn.Linear(n_size, 512)
self.fc2 = nn.Linear(512, 10)

# Define proportion or neurons to dropout
self.dropout = nn.Dropout(0.25)
def forward(self, x):
x = self._forward_features(x)
x = x.view(x.size(0), -1)
x = self.dropout(x)
x = F.relu(self.fc1(x))
# Apply dropout
x = self.dropout(x)
x = self.fc2(x)
return x
By using wandb.log() in your training function, you can automatically track the performance of your model. See docs for full details.
def train(model, device, train_loader, optimizer, criterion, epoch, steps_per_epoch=20):

# Log gradients and model parameters
wandb.watch(model)

# loop over the data iterator, and feed the inputs to the network and adjust the weights.
for batch_idx, (data, target) in enumerate(train_loader, start=0):
# ...
acc = round((train_correct / train_total) * 100, 2)
# Log metrics to visualize performance
wandb.log({'Train Loss': train_loss/train_total, 'Train Accuracy': acc})



2 selected runs


Advanced dropout techniques and considerations

While standard dropout is effective, advanced techniques and considerations can further improve its performance. These include adaptive dropout rates and dropout variants.
Adaptive dropout rates dynamically adjust the dropout rate during training based on the model's performance. This can help fine-tune the regularization strength and improve the model's generalization. Other dropout variants, such as variational dropout, introduce more sophisticated mechanisms for randomly dropping neurons. These variants can sometimes lead to better performance than standard dropout, especially in complex models.
Choosing the appropriate dropout rate for different layers is also crucial. It's often beneficial to experiment with different dropout rates for different layers to find the optimal configuration for a given task.

Try our dropout colab yourself →

Try Weights & Biases

Weights & Biases helps you keep track of your machine learning experiments. Try our tool to log hyperparameters and output metrics from your runs, then visualize and compare results, and quickly share findings with your colleagues.
To run 2 quick experiments on Replit and see how W&B can help organise your work foloow the instructions below:
Instructions:
  1. Click the green "Run" button below (the first time you click Run, Replit will take approx 30-45 seconds to allocate a machine)
  2. Follow the prompts in the terminal window (the bottom right pane below)
  3. You can resize the terminal window (bottom right) for a larger view