AI Logic

Pooling

Spatial Pyramid Pooling (SPP)

Updated:

Diagram of spatial pyramid pooling. Left: the overall flow, where convolutional layers turn the input image into a feature map of variable size, spatial pyramid pooling makes it fixed-length, and it is passed to fully connected layers. Right: a numerical example that divides a 6×6 feature map into 3×3, 2×2 and 1×1 bins and concatenates the per-bin maxima (9, 4 and 1 values) into 14 values

What is spatial pyramid pooling?

Spatial pyramid pooling (SPP) divides a feature map into grids at several levels of coarseness, takes the maximum in each bin, and concatenates them into a single vector. Because the bin size is proportional to the feature map size, the resulting vector has the same length whatever the feature map's dimensions. It has no learnable parameters.

He et al. proposed SPP-net in 2014, a network that inserts an SPP layer into a CNN. CNNs at the time could only accept images of a fixed size such as 224×224. Images were therefore cropped or warped to fit, but cropping cuts off parts of the object and warping distorts its shape.

The paper pointed out that the fixed size requirement comes not from the convolutional layers but from the fully connected layers at the end. Convolutional layers can be computed on images of any size, but fully connected layers need an input of fixed length. The paper therefore replaced the last pooling layer, between the last convolutional layer and the fully connected layers, with an SPP layer, so that a vector of the same length can be produced from a feature map of any size.

In the example in the top figure, a 6×6 feature map is divided into 3×3, 2×2 and 1×1 bins, and their maxima (9, 4 and 1 values) are concatenated into 14 values. Whether the feature map is 13×13 or 10×10, only the bin size changes; the output stays at 14 values.

The idea comes from spatial pyramid matching (Grauman and Darrell 2005, Lazebnik et al. 2006), widely used in image recognition before deep learning. It adds grids that coarsely preserve spatial information to Bag-of-Words, which summarizes the features of a whole image into one, and SPP-net applied this to the feature maps of a CNN.

Computation steps

Let the output of the last convolutional layer be a feature map with height hh, width ww and kk channels (filters).

  1. Choose the pyramid levels. The paper's classification experiments used 4 levels, {6×6, 3×3, 2×2, 1×1}\{6 \times 6,\ 3 \times 3,\ 2 \times 2,\ 1 \times 1\} (50 bins in total).
  2. At an n×nn \times n level, divide the feature map into nn equal parts both vertically and horizontally. Appendix A of the paper defines the range of the (i,j)(i, j)-th bin (counting from 1) as follows. When the division is not exact, the left and top boundaries are floored and the right and bottom boundaries are ceiled.
[⌊i−1nw⌋, ⌈inw⌉]×[⌊j−1nh⌋, ⌈jnh⌉]\left[ \left\lfloor \frac{i-1}{n} w \right\rfloor,\ \left\lceil \frac{i}{n} w \right\rceil \right] \times \left[ \left\lfloor \frac{j-1}{n} h \right\rfloor,\ \left\lceil \frac{j}{n} h \right\rceil \right]
  1. In each bin, apply max pooling per channel.
  2. Concatenate the values of all bins at all levels. With MM bins in total, the output length is kMkM. In the paper's object detection, k=256k = 256 and M=50M = 50, giving 12,800 dimensions.
  3. Feed this vector into the fully connected layer (fc6).

The coarsest 1×11 \times 1 level is "global pooling", which takes the maximum over the whole feature map. The paper notes that this corresponds to the traditional Bag-of-Words, and that work using global average pooling had appeared around the same time. SPP can also be viewed as global pooling with a little spatial information added by the finer levels.

When the feature map size is fixed, each level can be written as ordinary max pooling. For an a×aa \times a feature map, the n×nn \times n level is max pooling with window size ⌈a/n⌉\lceil a/n \rceil and stride ⌊a/n⌋\lfloor a/n \rfloor. In Figure 4 of the paper, conv5 is 13×13, so the 3×3 level has window 5 and stride 4, the 2×2 level window 7 and stride 6, and the 1×1 level window 13 and stride 13.

Why it works

The paper lists three advantages that SPP brings to CNNs.

  1. Fixed-length output regardless of input size: Images can be fed as they are, without cropping or warping. Objects can be recognized whole and without distortion.
  2. Pooling at several levels of coarseness makes it robust to object deformations: Fine bins capture "what is where", while coarse bins capture "what is in the whole image". With only one max pooling window size, the representation leans toward one or the other. It was already known from the original spatial pyramid matching that representations at several levels of coarseness are robust to object deformations and differences in layout.
  3. Features can be extracted at various scales: Because the input size can be changed freely, the same network can extract features from images at various scales.

In object detection there is an even bigger advantage. The earlier R-CNN cropped about 2,000 candidate regions from each image, warped each to 227×227, and passed them through the CNN. Computing the convolution thousands of times over overlapping regions of the same image made it very slow. SPP-net computes the feature map of the whole image only once and applies SPP to the part of the feature map corresponding to each candidate region, producing a fixed-length feature for each region. Since the heavy convolution is done only once, it became much faster.

As an analogy, instead of cutting a photo into 2,000 pieces and sending each one for appraisal, the whole photo is appraised once and the part for each region is read from that appraisal.

How it is trained

In theory, SPP-net can be trained by backpropagation on images of any size. However, GPU implementations of the time (cuda-convnet and Caffe) assumed inputs of a fixed size. The paper therefore trained it in the following two ways.

Single-size training

The network is trained on images cropped to 224×224. Because the feature map size is fixed, each level can be implemented as max pooling with a fixed window and stride, as in the TIP above. This method still gains the effect of pooling at several levels of coarseness.

Multi-size training

In addition to 224×224, images of the same region shrunk to 180×180 are also used. With a 180×180 input, conv5 becomes 10×10, but the SPP output has the same length as for 224×224, so the setup can be treated as two networks that share all weights. Training alternates between 224 and 180 every epoch, and the paper reports that convergence was about as fast as with single-size training.

Training is limited to a few sizes, but at test time images of any size can be used as they are.

Use in object detection

Object detection with SPP-net follows the R-CNN pipeline, changing only how features are extracted.

  1. Generate about 2,000 candidate regions per image with Selective Search.
  2. Resize the image so that its shorter side is ss, and compute the conv5 feature map of the whole image only once.
  3. Convert the candidate regions to coordinates on the feature map.
  4. Apply 4-level SPP (1×1, 2×2, 3×3, 6×6) to the corresponding part of the feature map to obtain a 12,800-dimensional feature.
  5. Pass it through the fully connected layers and classify the region with per-class SVMs.

The coordinate conversion in step 3 is described in Appendix A of the paper. Let SS be the product of all strides up to conv5 (16 for the network called ZF-5). The left (top) boundary xx of a region in the image is converted to ⌊x/S⌋+1\lfloor x/S \rfloor + 1, and the right (bottom) boundary to ⌈x/S⌉−1\lceil x/S \rceil - 1. This process of dividing image coordinates by SS and rounding to integers was carried over into the later RoI pooling, and led to the improvement in RoIAlign that eliminates rounding.

When using multiple scales (s∈{480,576,688,864,1200}s \in \{480, 576, 688, 864, 1200\}), for each candidate region the single scale at which the resized region is closest to 224×224 is chosen, and the feature is extracted from the feature map at that scale.

Experimental results

ImageNet 2012 classification (validation top-1 error %, Table 2 of the paper)

The convolutional layers are kept the same, and only the last pooling layer is replaced with SPP (4 levels, 50 bins). Testing averages 10 crops.

NetworkNo SPPSPP (single-size training)SPP (multi-size training)
ZF-535.9934.9834.60
Convnet*-534.9334.3833.94
Overfeat-534.1332.8732.26
Overfeat-732.0130.3629.68

The error dropped for all four networks with different architectures, and multi-size training lowered it further. Since the input cropping is the same as without SPP, the improvement with single-size training comes solely from pooling at several levels of coarseness.

The paper also confirms that the gain is not due to more parameters. With ZF-5 and levels {4×4,3×3,2×2,1×1}\{4 \times 4, 3 \times 3, 2 \times 2, 1 \times 1\} (30 bins), the input to the fully connected layer is shorter than without SPP (6×6 = 36 bins), yet the top-1 error was 35.06%, lower than without SPP (35.99%) and almost the same as with 50 bins (34.98%).

The paper also examines the effect of feeding the whole image as is. In single-view testing with Overfeat-7 (multi-size training), the top-1 error was 32.57% with the center 224×224 crop and 31.25% with the whole image (shorter side resized to 256) (Table 3).

PASCAL VOC 2007 object detection (mAP %, Table 10 of the paper)

The same pretrained network (ZF-5) is used to compare with R-CNN.

MethodmAP (with bounding box regression)Convolution time per image (GPU)Total time (GPU)
R-CNN59.214.37 s14.46 s
SPP-net (1 scale)58.00.053 s0.142 s
SPP-net (5 scales)59.20.293 s0.382 s

The 5-scale SPP-net matched R-CNN's accuracy and was 38 times faster overall; with 1 scale it was 102 times faster at the cost of 1.2 points of accuracy. Compared with R-CNN run with AlexNet as in its original paper, it is 24–64 times faster (Table 9).

Caveats

In object detection, the convolutional layers before the SPP layer are not fine-tuned. For simplicity, the SPP-net paper limited fine-tuning for detection to the fully connected layers. The later Fast R-CNN paper explains that the cause is that backpropagating through the SPP layer to the convolutional layers is very inefficient when each training sample (candidate region) comes from a different image. It then showed that fine-tuning only the fully connected layers of the deep VGG16 lowers VOC 2007 mAP from 66.9% to 61.4%. Fast R-CNN removed this limitation with a training scheme that takes many regions from each image and with RoI pooling.

  • Images in the same mini-batch must have the same size: Tensors can only be batched if they share the same shape. As in the paper, change the size per mini-batch (per epoch in the paper), or compute one image at a time.
  • Finer levels retain more spatial information but also increase length: The 6×66 \times 6 level alone has 36 bins, and the weights of the fully connected layer grow accordingly. Matching the finest level to the output of the original last pooling layer (6×6 in the paper) avoids changing the shape of the fully connected layer.
  • If the feature map is smaller than the number of bins in a level, bins overlap: For example, using a 6×6 level on a 4×4 feature map puts the same position into several bins. It can still be computed, but the fine level loses its meaning.
  • PyTorch has no dedicated layer: It can be built by applying nn.AdaptiveMaxPool2d(n) for each level and concatenating the results. The bin ranges of AdaptiveMaxPool2d (left and top floored, right and bottom ceiled) are the same as the definition in Appendix A of the paper.

Comparison with other methods and how to choose

The table lists methods that summarize a feature map into a fixed size, from the same viewpoints.

MethodHow values are summarizedOutput sizeSpatial informationMain use
Cropping / warpingResizes the input image to fitSet by the networkKept (but with missing parts or distortion)Early CNNs (AlexNet, etc.)
Max poolingMaximum in each fixed windowProportional to input sizeKeptDownsampling inside the network
Global average poolingAverage over the whole feature mapCCLostRight before classification (ResNet, etc.)
Spatial pyramid poolingMaximum in each bin of grids at several levelsC×C \times number of binsCoarsely keptFixed length from images or regions of different sizes
RoI poolingMaximum in each bin of a single-level gridC×H×WC \times H \times W (e.g. 7×7)Kept at grid resolutionPer-region features in object detection (Fast R-CNN)
RoIAlignSingle-level grid, interpolated without rounding coordinatesC×H×WC \times H \times WAccurately kept at grid resolutionDetection and segmentation (Mask R-CNN)

The Fast R-CNN paper itself states that RoI pooling is the special case of SPP with a single level (e.g. 7×7). On that basis, Fast R-CNN made it possible to train through RoI pooling all the way to the convolutional layers.

Rough guidelines for choosing:

  • For classification, when you only want to allow any input size: Global average pooling is enough. Most current classification networks take this form.
  • For classification, when you want to allow any input size while keeping some spatial information: Spatial pyramid pooling is a candidate.
  • For object detection, when you want to extract features for each candidate region: Use RoI pooling or the more accurate RoIAlign. They are built into torchvision and can be trained together with the convolutional layers.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Spatial pyramid pooling: apply AdaptiveMaxPool2d(n) for each level and concatenate
# AdaptiveMaxPool2d bin ranges are [floor(i*h/n), ceil((i+1)*h/n)) (same definition as Appendix A of the paper)
class SpatialPyramidPooling(nn.Module):
  def __init__(self, levels=(6, 3, 2, 1)):  # The 4 levels (50 bins) of the paper's classification experiments
    super().__init__()
    self.pools = nn.ModuleList([nn.AdaptiveMaxPool2d(n) for n in levels])
    self.num_bins = sum(n * n for n in levels)

  def forward(self, x):                       # x: [B, C, h, w] (h, w are arbitrary)
    return torch.cat([p(x).flatten(1) for p in self.pools], dim=1)  # [B, C * number of bins]


# Same values as the top figure (1 channel × 6 × 6). Levels are 3×3, 2×2, 1×1
x = torch.tensor([[[[1., 0, 2, 4, 1, 0],
                    [3, 2, 0, 1, 5, 2],
                    [0, 6, 1, 0, 2, 1],
                    [2, 1, 3, 2, 0, 4],
                    [1, 0, 2, 7, 1, 0],
                    [4, 2, 0, 1, 3, 2]]]])
spp = SpatialPyramidPooling(levels=(3, 2, 1))
print(spp(x))  # 14 values: [3, 4, 5, 6, 3, 4, 4, 7, 3,  6, 5, 4, 7,  7]

# Output length is the same even when the feature map size differs
print(spp(torch.randn(1, 256, 13, 13)).shape)  # torch.Size([1, 3584]) = 256 × 14
print(spp(torch.randn(1, 256, 10, 17)).shape)  # torch.Size([1, 3584])


# SPP-net form: conv layers → SPP (in place of the last pooling layer) → fully connected layers
class SPPNet(nn.Module):
  def __init__(self, num_classes=1000, levels=(6, 3, 2, 1)):
    super().__init__()
    self.features = nn.Sequential(            # Smallish conv layers as an example
      nn.Conv2d(3, 96, 7, stride=2, padding=1), nn.ReLU(), nn.MaxPool2d(3, 2),
      nn.Conv2d(96, 256, 5, stride=2, padding=1), nn.ReLU(), nn.MaxPool2d(3, 2),
      nn.Conv2d(256, 256, 3, padding=1), nn.ReLU(),
    )
    self.spp = SpatialPyramidPooling(levels)
    self.classifier = nn.Sequential(
      nn.Linear(256 * self.spp.num_bins, 4096), nn.ReLU(), nn.Dropout(0.5),  # fc6
      nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(0.5),                     # fc7
      nn.Linear(4096, num_classes),
    )

  def forward(self, x):
    return self.classifier(self.spp(self.features(x)))


model = SPPNet()
model.eval()  # eval() for inference because of Dropout; SPP itself is the same in train/eval
with torch.no_grad():
  # Images of different sizes can be fed as is (sizes must match within a mini-batch)
  print(model(torch.randn(2, 3, 224, 224)).shape)  # torch.Size([2, 1000])
  print(model(torch.randn(1, 3, 180, 300)).shape)  # torch.Size([1, 1000])

FAQ

Q. How does spatial pyramid pooling differ from global average pooling?
A.

Both produce a fixed-length vector regardless of the feature map size. Global average pooling reduces the whole feature map to one value, so all spatial information is lost. Spatial pyramid pooling uses finer levels such as 2×2 and 6×6 in addition to the 1×1 level (global maximum), so it coarsely retains "what is roughly where in the image". In exchange, the output is longer and the weights of the next fully connected layer increase.

Q. How should the pyramid levels be chosen?
A.

The paper's classification experiments used {6×6,3×3,2×2,1×1}\{6 \times 6, 3 \times 3, 2 \times 2, 1 \times 1\} (50 bins), with the output of the original last pooling layer (6×6) as the finest level. Using {4×4,3×3,2×2,1×1}\{4 \times 4, 3 \times 3, 2 \times 2, 1 \times 1\} (30 bins) gave almost the same error. Adding finer levels retains more spatial information but increases the output length and the weights of the fully connected layer.

Q. What is the difference between SPP-net and Fast R-CNN?
A.

Both compute the feature map of the whole image only once and extract a fixed-length feature for each candidate region. SPP-net uses a multi-level pyramid and fine-tuned only the fully connected layers when training for detection. Fast R-CNN uses RoI pooling, a single-level version, and made it possible to train everything jointly, including the convolutional layers.

References

  1. K. He, X. Zhang, S. Ren, and J. Sun, "Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition," ECCV, 2014 / IEEE TPAMI, vol. 37, no. 9, 2015.
  2. S. Lazebnik, C. Schmid, and J. Ponce, "Beyond Bags of Features: Spatial Pyramid Matching for Recognizing Natural Scene Categories," CVPR, 2006.
  3. K. Grauman and T. Darrell, "The Pyramid Match Kernel: Discriminative Classification with Sets of Image Features," ICCV, 2005.
  4. R. Girshick, J. Donahue, T. Darrell, and J. Malik, "Rich feature hierarchies for accurate object detection and semantic segmentation," CVPR, 2014.
  5. PyTorch Documentation, "torch.nn.AdaptiveMaxPool2d."