AI Logic

Regularization

Spatial Dropout

Updated:

Comparison of Dropout and Spatial Dropout on a 4-channel feature map. On the left, Dropout zeroes pixels one at a time independently, so pixels with similar values remain around each dropped pixel. On the right, Spatial Dropout decides per channel whether to keep it and zeroes every pixel of channel 2. At inference, both use everything and multiply by p

Background and Overview

Spatial Dropout is a form of Dropout that zeroes out the output of a convolutional layer (the feature maps) one whole channel at a time. Ordinary Dropout, which drops pixels one by one, can be ineffective in convolutional layers. Spatial Dropout avoids this problem by making the channel the unit that is dropped.

Tompson and colleagues proposed it in 2015 as part of their work on estimating the positions of human joints in images (pose estimation) (CVPR 2015). When they added ordinary Dropout to a fully convolutional network, training only became slower and overfitting was not prevented. The paper attributed this to the following.

  • In natural images, the values of neighboring pixels are strongly correlated.
  • As a result, neighboring pixels in a convolutional layer's feature maps are also strongly correlated.
  • Dropping one pixel does little, because its neighbor passes almost the same information to the next layer, so Dropout has no effect.

As an analogy, erasing a single pixel from a photo hardly matters, because the surrounding pixels immediately reveal what was there. Spatial Dropout erases an entire feature map, which trains the network to make predictions without relying on that feature (channel).

Theory (Training and Inference)

The explanation follows Section 3.2 of the paper. Let the convolutional layer's output be a feature tensor y\boldsymbol{y} with CC channels, height HH, and width WW, and let pp be the probability of keeping a channel (the paper's pdropp_{\text{drop}} is the probability of dropping, so p=1−pdropp = 1 - p_{\text{drop}}).

  1. During training, decide for each channel whether to keep it, with probability pp. Whereas ordinary Dropout makes C×H×WC \times H \times W draws, Spatial Dropout makes only CC. rc∼Bernoulli(p)(c=1,…,C)r_c \sim \mathrm{Bernoulli}(p) \qquad (c = 1, \dots, C)
  2. Broadcast that value over the entire feature map of the channel and multiply. Every pixel of a dropped channel becomes 0. y~c,h,w=rc yc,h,w\tilde{y}_{c,h,w} = r_c \, y_{c,h,w}
  3. Repeat steps 1 and 2 with a fresh draw for each training example (each example in the mini-batch).
  4. At inference, use all channels and multiply the output by pp. This matches the average output during training, just as in ordinary Dropout. y~=p y\tilde{\boldsymbol{y}} = p \, \boldsymbol{y}

The only difference from ordinary Dropout is step 1: the unit for which the keep decision is made. Inference is handled the same way.

Why Ordinary Dropout Fails

Using a 1D convolution as an example, the paper explains what happens during backpropagation (Figures 3 and 5).

  • The convolution kernel W2W_2 is slid across the previous layer's features F2F_2. So the center weight of W2W_2 receives gradients from the features at two neighboring positions, f2af_{2a} and f2bf_{2b}.
  • If ordinary Dropout drops only f2bf_{2b}, the gradient from f2bf_{2b} becomes 0. But because f2af_{2a} and f2bf_{2b} are strongly correlated (f2a≈f2bf_{2a} \approx f_{2b}), nearly the same gradient arrives from f2af_{2a}.
  • As a result, the effective learning rate merely shrinks, and no decorrelating effect on the features emerges. This matches the early experimental finding that training took longer but overfitting was not prevented.

With Spatial Dropout, the whole feature map containing f2af_{2a} and f2bf_{2b} is dropped, so the gradients from both become 0 at the same time. As a result, the network cannot rely on any particular channel, and the channels learn independent features.

Experimental Results

The original paper inserted Spatial Dropout before the first 1×1 convolutional layer of a convolutional network for joint localization. According to the paper, it was especially effective on the FLIC dataset, which has little training data: in the plot of wrist detection rate (Figure 14b), the version with Spatial Dropout was clearly higher at larger tolerances from the ground truth. The paper attributes this to fewer predictions with large errors. However, the original paper does not report the difference with and without Spatial Dropout in a numerical table.

A numerical comparison was later reported by the DropBlock paper (Ghiasi et al., 2018) for ImageNet image classification. The table shows top-1 validation accuracy when each method is inserted into the convolutional branches of ResNet-50 (higher is better; pp is the best value for each).

MethodKeep probability ppTop-1 accuracy
None—76.51%
Dropout0.776.80%
Spatial Dropout0.977.41%
DropBlock (block_size = 7)0.978.13%
  • Better than Dropout: Accuracy was 0.6 points higher than with Dropout, which drops pixels one at a time.
  • Falls short of DropBlock: Ghiasi et al. report that using Spatial Dropout on high-resolution feature maps (the third group of ResNet-50) can drop too aggressively (entire channels disappear).

Practical Considerations

The p in PyTorch's nn.Dropout2d(p) is the probability of dropping a channel. It points the same way as the paper's pdropp_{\text{drop}}, the opposite of this article's pp (the keep probability). Also, if nn.Dropout2d receives a 3D tensor, it treats it not as an unbatched (C,H,W)(C, H, W) but as (N,C,L)(N, C, L) and performs 1D Spatial Dropout (the same behavior as nn.Dropout1d). Always pass image feature maps with a batch dimension as (N,C,H,W)(N, C, H, W).

  • Behavior differs between training and inference: Like Dropout, PyTorch's nn.Dropout2d scales the kept channels by 1/(1−p)1/(1-p) during training and does nothing at inference (equivalent to the paper's "multiply by pp at inference"). Call model.eval() before evaluation or inference.
  • Can be too strong in high-resolution layers: Because whole channels are erased, a lot of information is lost at once. Start with a small drop probability (the DropBlock paper's experiments used a keep probability of 0.9).
  • Choose by data dimensionality: Use nn.Dropout1d for sequence data ((N,C,L)(N, C, L)) and nn.Dropout3d for 3D data (video or medical images, (N,C,D,H,W)(N, C, D, H, W)). All of them drop whole channels.
  • Where to insert it: The original paper inserted it at one place, before the 1×1 convolutional layer that produces the final output from the convolutional features.

Comparison with Other Methods

The table lines up Dropout and three of its variants from the same viewpoints.

MethodWhat is droppedNumber of keep decisions per sampleMain layer typeAt inference
DropoutUnits (output elements), one at a timeNumber of unitsFully connected layersUse all, scale weights by pp
DropConnectWeights (connections), one at a timeNumber of weights (inputs × outputs)Fully connected layersApproximate with a Gaussian and average samples
Spatial DropoutWhole channels of the feature mapNumber of channelsConvolutional layersUse all, scale by pp (same as Dropout)
DropBlockSquare regions of the feature mapNumber of pixels (choose seeds, expand into blocks)Convolutional layersNothing (scale is matched during training)

(In every case pp is the probability of keeping. PyTorch's Dropout-family layers are implemented by scaling by 1/(1−pdrop)1/(1-p_{\text{drop}}) during training and doing nothing at inference.)

  • To add regularization to convolutional layers with minimal effort, Spatial Dropout, built into PyTorch as nn.Dropout2d, is a convenient choice.
  • When erasing whole channels is too strong on high-resolution feature maps, choose DropBlock, whose region size is adjustable. Setting DropBlock's block to the size of the whole feature map makes it behave like Spatial Dropout.
  • For fully connected layers, use ordinary Dropout or DropConnect.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# PyTorch's Spatial Dropout is nn.Dropout2d. p is the probability of *dropping* a channel
drop = nn.Dropout2d(p=0.5)
x = torch.ones(1, 4, 3, 3)       # (batch N, channels C, height H, width W)

drop.train()
print(drop(x)[0, :, 0, 0])   # e.g., tensor([2., 0., 2., 0.]). Per channel, all pixels are 0 or 2.0 (= 1/(1 − 0.5))
drop.eval()
print(drop(x)[0, :, 0, 0])   # does nothing at inference: all 1.0


# Implementation following the paper's equations: decide once per channel, broadcast over the feature map
def spatial_dropout(y, keep_prob, training=True):
    if not training:
        return keep_prob * y                      # multiply by p at inference (the paper's approach)
    n, c = y.shape[:2]
    r = torch.bernoulli(torch.full((n, c, 1, 1), keep_prob, device=y.device))  # r_c ~ Bernoulli(p)
    return r * y                                  # broadcast (N, C, 1, 1) over H × W


# Example: a fully convolutional network with Spatial Dropout before a 1×1 convolution
model = nn.Sequential(
    nn.Conv2d(3, 128, 5, padding=2), nn.ReLU(), nn.MaxPool2d(2),
    nn.Conv2d(128, 512, 9, padding=4), nn.ReLU(),
    nn.Dropout2d(p=0.1),            # drop probability 0.1 per channel (keep probability 0.9)
    nn.Conv2d(512, 256, 1), nn.ReLU(),
    nn.Conv2d(256, 14, 1),          # e.g., heatmaps for 14 joints
)

model.train()                       # training: randomly drop channels
heatmaps = model(torch.randn(8, 3, 64, 64))
model.eval()                        # inference: no dropping
with torch.no_grad():
    heatmaps = model(torch.randn(8, 3, 64, 64))

FAQ

Q. What is the difference between nn.Dropout and nn.Dropout2d?
A.

nn.Dropout zeroes the pixels (elements) of a feature map one at a time, independently. nn.Dropout2d decides per channel whether to zero it and zeroes all pixels of that channel together. Because neighboring pixels in a convolutional layer's output have similar values, with nn.Dropout the information in dropped pixels is filled in by their neighbors, weakening the effect. Use nn.Dropout2d for convolutional layers.

Q. What drop probability should I use?
A.

Start with a small value. Because whole channels are erased, more information is lost at once than with Dropout, which drops pixels one at a time. In the DropBlock paper's ImageNet experiments, Spatial Dropout performed best with a keep probability of 0.9 (p = 0.1 in PyTorch). If the validation data shows overfitting, raise it gradually.

Q. Should I use Spatial Dropout or DropBlock?
A.

For ease of use, Spatial Dropout. It is built into PyTorch as nn.Dropout2d, and the only setting is the drop probability. To push accuracy further, try DropBlock. In the DropBlock paper's ResNet-50 experiments, DropBlock reached 78.13% versus 77.41% for Spatial Dropout. However, DropBlock requires tuning the block size and a schedule that gradually increases the drop rate.

References

  1. J. Tompson, R. Goroshin, A. Jain, Y. LeCun, and C. Bregler, "Efficient Object Localization Using Convolutional Networks," CVPR, 2015.
  2. G. Ghiasi, T.-Y. Lin, and Q. V. Le, "DropBlock: A regularization method for convolutional networks," NeurIPS, 2018.
  3. N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever, and R. Salakhutdinov, "Dropout: A Simple Way to Prevent Neural Networks from Overfitting," Journal of Machine Learning Research, 15(56), 1929–1958, 2014.
  4. PyTorch Documentation, "torch.nn.Dropout2d."