Stochastic pooling picks one value from each pooling window with probability proportional to its magnitude. Whereas max pooling always picks the maximum, stochastic pooling favors larger values but can also pick the second or third largest. The random choice is made only during training; at inference time it outputs the probability-weighted sum. It has no learnable parameters.
Zeiler and Fergus proposed it in 2013 as a regularization method to curb overfitting in the convolutional layers of a CNN. At the time, Dropout worked well in fully connected layers, but the paper notes that Dropout did not seem to work as well in convolutional layers, and considered randomizing pooling as an alternative.
In the example in the top figure, the values of a 3ร3 window (sum 10) are divided by their sum, so the position of 4 is chosen with probability 0.4, the position of 3 with probability 0.3, and so on. During training, the single value chosen according to these probabilities (2 in the figure) becomes the output as is. At inference time no choice is made, and 0.1โ 1+0.3โ 3+0.2โ 2+0.4โ 4=3 is output.
Computation (training and inference)
Let aiโ be the activations (values after ReLU) in window Rjโ.
During training
Divide the values in the window by the window's sum to get probabilities (Equation (4) of the paper).
piโ=โkโRjโโakโaiโโ
Choose one position l in the window according to these probabilities p1โ,โฆ,pโฃRjโโฃโ.
Output the value at the chosen position as is (Equation (5)).
sjโ=alโ,lโผP(p1โ,โฆ,pโฃRjโโฃโ)
The choice is made separately for each channel, each window, and each training example.
In backpropagation, the gradient is passed only to the chosen position l. This is the same treatment as max pooling, which passes the gradient only to the position of the maximum.
At inference time
Choosing randomly at inference time would make predictions fluctuate and reduce accuracy, so the paper uses the probability-weighted sum instead (Equation (6)).
sjโ=iโRjโโโpiโaiโ
This is different from average pooling. Average pooling divides by the number of cells โฃRjโโฃ in the window, whereas in Equation (6) piโ has the window's sum โakโ as its denominator, so larger values count more heavily. In the example in the top figure, average pooling gives 10/9โ1.11, while Equation (6) gives 3, close to the maximum (4).
Equation (6) is the expected value of the training-time output sjโ. During training, 4 is output with probability 0.4, 3 with probability 0.3, and so on, so the average is โpiโaiโ. Because training and inference outputs have the same scale, no correction factor is needed at inference time.
Why it curbs overfitting
The paper explains why stochastic pooling works from three viewpoints.
It averages over many models: Each choice of position in each window changes how the network is connected, giving a different model. With window size n (9 for 3ร3) and d windows, there are nd possible models. According to the paper, d is on the order of 104 to 106, far more than Dropout (n=2), which has only two options per neuron: keep or drop. Equation (6) at inference time can be seen as an approximation of averaging these models in a single computation.
It resembles training on slightly deformed inputs: Changing the chosen position within a window is similar to shifting part of the image slightly. The paper views stochastic pooling as equivalent to "training with max pooling on many copies of the input with small local deformations". Since each layer chooses independently, the combinations of deformations grow exponentially as layers are stacked.
It uses values other than the maximum: Max pooling passes only the strongest response in the window to the next layer. Stochastic pooling occasionally passes the second and later strong responses in the same window as well. The paper contrasts this with Dropout: Dropout throws information away, while stochastic pooling chooses among the information the network already produces.
The combination with ReLU is also important. To turn values into probabilities with Equation (4), they must be non-negative. In addition, ReLU sets negative values to 0, so many positions in a window become 0 and the choice is made among a few strongly responding positions. The paper says these two points make ReLU especially well suited to stochastic pooling.
As an analogy, it is like choosing a representative by lottery. Max pooling always makes "the person with the most votes" the representative, while stochastic pooling draws the representative by lottery with probability proportional to votes. Since the representative changes a little in every training step, the network cannot rely on the response at one particular position alone.
Experimental results
The paper's experiments use a small network with three convolutional layers (5ร5 filters, 64 maps, ReLU) and one fully connected layer, swapping only the pooling (3ร3, stride 2). No data augmentation is used.
Error rate by pooling method (%, Tables 1โ4 of the paper)
Stochastic pooling had the lowest test error on all four datasets. On CIFAR-10, the training error of max pooling drops to 0.0% (the training data is memorized completely), while stochastic pooling stays at 3.40%, and its test error is correspondingly more than 4 points lower. This clearly shows how regularization works: it deliberately weakens the fit to the training data and improves the fit to new data.
The paper also compares window sizes from 2ร2 to 5ร5. Stochastic pooling was best with 3ร3 (CIFAR-10 test error 15.13%) and outperformed max and average pooling at every size. The paper suggests that small windows overfit while large windows add too much noise during training.
Combinations of training and inference methods (CIFAR-10 test error %, excerpt from Table 5 of the paper)
Training
Inference
Test error
Stochastic pooling
Probability weighting (Equation (6))
15.20
Stochastic pooling
Stochastic pooling (one sample)
17.49
Stochastic pooling
Average of predictions over 100 samples
15.12
Stochastic pooling
Max pooling
17.66
Stochastic pooling
Average pooling
53.50
Probability weighting
Probability weighting
19.40
Max pooling
Stochastic pooling
32.75
Probability weighting at inference achieves almost the same accuracy as averaging 100 samples, in a single computation. On the other hand, switching to average pooling at inference makes results much worse, and using probability weighting from training onward (without random choice) leads to overfitting. The combination of random choice in training and weighting at inference is what matters.
Caveats
Switch the computation between training and inference. Choose randomly during training and use the weighting of Equation (6) at inference. Choosing randomly at inference too raises the error (15.20% โ 17.49% on CIFAR-10), and switching to ordinary average pooling at inference makes it as bad as 53.50%. When implementing it yourself in PyTorch, branch on self.training and call model.eval() before inference.
Values must be non-negative: Equation (4) treats values as probabilities, so negative values do not form a probability distribution. Place it after ReLU, as in the paper.
Decide how to handle windows that are all zero: After ReLU, every value in a window can be 0, making Equation (4) 0 รท 0. The paper does not mention this, but setting the output to 0 in that case gives the same result whichever position is chosen.
PyTorch has no built-in layer: Write it yourself by extracting windows, as in the implementation example below. Choosing positions with random numbers is heavier than taking the maximum, and with overlapping windows (3ร3, stride 2) the extracted data is also larger.
Window size remains a hyperparameter: The paper says it is "hyperparameter-free", meaning that stochastic pooling itself adds no values to tune. Window size and stride must still be chosen as for ordinary pooling, and 3ร3 gave the best results in the paper's experiments.
It can be combined with other regularizers: The paper says it can be combined with weight decay, Dropout, data augmentation and so on. The paper's own experiments also use it together with weight decay (0.001).
Comparison with other methods and how to choose
The table lists ways of summarizing window values and regularizers used for convolutional layers, from the same viewpoints.
Stochastic pooling turns the pooling layer itself into a regularizer. Whereas the Dropout family "sets values to 0 and throws them away", stochastic pooling only randomizes "which value in the window is passed on" and does not throw values away.
Rough guidelines for choosing:
A CNN with max pooling is overfitting on a small dataset: Replacing it with stochastic pooling is a candidate. In the paper's experiments with reduced training data, it was also less prone to overfitting than the other pooling methods in most cases.
A design that already uses no pooling (e.g. strided convolutions): Stochastic pooling cannot be used because there is no pooling layer. Consider Spatial Dropout or DropBlock.
Adding regularization to a recent large CNN: Well-established options with built-in support, such as DropBlock, Stochastic Depth and data augmentation, are the first candidates. Stochastic pooling must be implemented by hand and is also more expensive than max pooling.
PyTorch example
โถShow code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
# PyTorch has no built-in layer, so write it following Equations (4)โ(6) of the paper
class StochasticPool2d(nn.Module):
"""Stochastic pooling (Zeiler & Fergus, 2013). Assumes non-negative values (after ReLU)"""
def __init__(self, kernel_size=3, stride=2):
super().__init__()
self.k = kernel_size
self.s = stride
def forward(self, x):
B, C, H, W = x.shape
k, s = self.k, self.s
H_out, W_out = (H - k) // s + 1, (W - k) // s + 1
# Extract windows: [B, C*k*k, L] -> [B, C, L, k*k] (L is the number of windows)
win = F.unfold(x, kernel_size=k, stride=s)
win = win.view(B, C, k * k, -1).transpose(2, 3)
a = win.clamp(min=0) # Clamp negatives to 0 just in case (assumption of Eq. (4))
total = a.sum(dim=-1, keepdim=True) # Window sum ฮฃ a_k
if self.training:
# Eq. (4): p_i = a_i / ฮฃ a_k. All-zero windows give 0 whichever is chosen, so use uniform
p = torch.where(total > 0, a / total.clamp_min(1e-12), torch.full_like(a, 1.0 / (k * k)))
# Eq. (5): choose one position according to p (separately per window, channel and example)
idx = torch.multinomial(p.reshape(-1, k * k), num_samples=1).view(B, C, -1, 1)
out = win.gather(-1, idx).squeeze(-1) # Gradient flows only to the chosen position
else:
# Eq. (6): ฮฃ p_i a_i = ฮฃ a_i^2 / ฮฃ a_k (0 for all-zero windows)
out = (a * a).sum(dim=-1) / total.squeeze(-1).clamp_min(1e-12)
return out.view(B, C, H_out, W_out)
# Same 3ร3 window as the top figure. Shape is [batch, channels, height, width]
x = torch.tensor([[[[0., 1., 0.],
[3., 0., 2.],
[0., 4., 0.]]]])
pool = StochasticPool2d(kernel_size=3, stride=2)
pool.eval()
print(pool(x).item()) # 3.0 (= 0.1ยท1 + 0.3ยท3 + 0.2ยท2 + 0.4ยท4)
pool.train()
samples = torch.stack([pool(x).flatten() for _ in range(10000)]).flatten()
for v in [1., 2., 3., 4.]:
print(v, (samples == v).float().mean().item()) # About 0.1, 0.2, 0.3, 0.4
print(samples.mean().item()) # Expected value is about 3.0 (matches the inference value)
# Close to the paper's experiments: conv (5ร5, 64 maps) โ ReLU โ stochastic pooling (3ร3, stride 2), three times
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
layers, c_in = [], 3
for _ in range(3):
layers += [nn.Conv2d(c_in, 64, kernel_size=5, padding=2), nn.ReLU(),
StochasticPool2d(kernel_size=3, stride=2)]
c_in = 64
self.features = nn.Sequential(*layers)
self.fc = nn.LazyLinear(num_classes)
def forward(self, x):
return self.fc(self.features(x).flatten(1))
model = SmallCNN()
images = torch.randn(8, 3, 32, 32) # Same size as CIFAR-10
model.train() # Training: random choice per window
print(model(images).shape) # torch.Size([8, 10])
model.eval() # Inference: probability-weighted sum (same result every time)
with torch.no_grad():
print(torch.equal(model(images), model(images))) # True
FAQ
Q. How does stochastic pooling differ from Dropout?
A.
Both are regularizers that add randomness only during training and use a computation corresponding to an average at inference. The difference is that Dropout sets values to 0 and throws them away, while stochastic pooling only chooses which value in the window to pass on and does not throw values away. Also, there are as many choices as there are cells in the window (9 for 3ร3), so the paper explains that it averages over more models than Dropout, which has only two options: keep or drop.
Q. Can ordinary average pooling be used at inference time?
A.
No. Average pooling divides by the number of cells in the window, so its values are much smaller than the training-time outputs. In the paper's CIFAR-10 experiments, switching only inference to average pooling made the error as bad as 53.50%. Use โiโpiโaiโ (the expected value of the training-time output).
Q. Can it be combined with activation functions that output negative values?
A.
Not as is. To form the probabilities piโ=aiโ/โkโakโ, the values in the window must be non-negative. The paper places it after ReLU, and also cites as an advantage that ReLU sets negative values to 0, which makes the few strongly responding positions more likely to be chosen.