Back to paper library
Paper notesarXiv 2015NeurIPS 2015

STN

Moving Heaven and Earth

Original paper

Spatial Transformer Networks

Paper authors

Max Jaderberg · Karen Simonyan · Andrew Zisserman · Koray Kavukcuoglu

Publication
NeurIPS 2015Conference
First submitted to arXiv
arXiv:1506.02025
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{classiccnnsstn2015,
  title = {{Spatial Transformer Networks}},
  author = {Max Jaderberg and Karen Simonyan and Andrew Zisserman and Koray Kavukcuoglu},
  year = {2015},
  eprint = {1506.02025},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1506.02025}
}
On this page

Show a convolutional network a crooked handwritten digit, and it can usually still recognize it.

Where does that tolerance come from? Partly from max pooling. It takes the maximum within a small 2×22\times2 region, so if a feature shifts by a pixel or two, the output stays the same. Stack many layers, and the network gains a certain tolerance for changes in position.

But this tolerance builds up bit by bit, and its range is fixed. Max Jaderberg, Karen Simonyan, Andrew Zisserman, and Koray Kavukcuoglu of Google DeepMind released this paper in June 2015. They wanted the network to decide for itself how to shift, scale, and rotate a given image so it's easiest to recognize.

Defining the Problem

The authors start by pointing out the limitations of max pooling. Its region is usually small, say 2×22\times2 pixels, so invariance to position has to build up slowly over many layers of convolution and pooling; feature maps in the intermediate layers actually have no invariance to large transformations of the input.

The problem is that the pooling mechanism is hard-coded in advance, so where it pools and over how large a region have nothing to do with what the input looks like.

The authors wanted a different kind of module:

  • Decides how to transform based on the input: each image gets its own transformation, instead of every image sharing the same treatment.
  • Acts on the whole feature map: it can crop, scale, rotate, or even apply non-rigid warps, without being confined to a local region.
  • Needs no extra annotation: nobody tells it the correct rotation angle or box; it learns only from the final task loss.
  • Trains directly with backpropagation: the optimization procedure stays the same, so it can be inserted into existing convolutional networks.

First, let's see what the result looks like:

Three rows of MNIST examples, four columns each. (a) Handwritten digits that have been translated, scaled, rotated, or had noise added; (b) the sampling box predicted by the module, drawn as a colored quadrilateral on the original image; (c) the digit after transformation by the sampling box, straightened and enlarged; (d) the prediction of the classification network that follows: 7, 5, and 6
Figure 1 from the paper, excerpted from page 2 of the v3 PDF. (a) Distorted MNIST inputs; (b) the transformation predicted by the module; (c) the transformed result; (d) the prediction of the classification network that follows. The whole network is trained with class labels only.

The third row is especially clear. The 6 is small, with clutter around it; the module finds the 6 on its own, crops it, enlarges it, and hands it to the classification network. At no point does anyone tell it where the 6 is.

Solving the Problem

Three Components

Architecture of the spatial transformer module. The input feature map U splits into two paths: one goes into the localisation network, which outputs the transformation parameters θ, from which the grid generator computes the sampling grid T_θ(G); the other goes straight to the sampler, which samples from U according to the grid and outputs the feature map V
Figure 2 from the paper, excerpted from page 3 of the v3 PDF. Together, the localisation network, the grid generator, and the sampler make up a spatial transformer.

The module consists of three components in sequence:

  1. Localisation network: reads the feature map UU and outputs the transformation parameters θ\theta. It can be a fully connected network or a convolutional network; all it needs is a final regression layer that outputs θ\theta.
  2. Grid generator: uses θ\theta to compute a set of sampling points Tθ(G)\mathcal{T}_\theta(G), that is, “where in the input each output pixel should take its value from.”
  3. Sampler: takes values from UU at the sampling points, producing the output VV.

For multi-channel input, every channel uses the same transformation, so the spatial correspondence between channels doesn't get scrambled.

There's nothing special about the localisation network; the key parts are the next two steps. Let's walk through them with a small example.

Grid Generator: Working Backward from the Output

Assume for now that the transformation is a 2D affine transformation, which needs only 6 parameters:

(xisyis)=Tθ(Gi)=[θ11θ12θ13θ21θ22θ23](xityit1)\begin{pmatrix} x_i^s \\ y_i^s \end{pmatrix} = \mathcal{T}_\theta(G_i) = \begin{bmatrix} \theta_{11} & \theta_{12} & \theta_{13} \\ \theta_{21} & \theta_{22} & \theta_{23} \end{bmatrix} \begin{pmatrix} x_i^t \\ y_i^t \\ 1 \end{pmatrix}

(xit,yit)(x_i^t, y_i^t) are the coordinates of the ii-th pixel on the output grid, with superscript tt for target; (xis,yis)(x_i^s, y_i^s) is the position in the input it takes its value from, with superscript ss for source.

Note that the formula computes input coordinates from output coordinates. That way every output pixel is guaranteed a source and there are no holes, the same approach used for texture mapping in computer graphics.

All coordinates are normalized to [−1,1][-1, 1], with the top-left corner of both output and input at (−1,−1)(-1, -1) and the bottom-right at (1,1)(1, 1), so the same θ\theta works whatever the size of the feature map.

Suppose the output is 3×33\times3 and we want to zoom in twofold on the input's top-left corner; we can set θ11=θ22=0.5\theta_{11}=\theta_{22}=0.5 and θ13=θ23=−0.5\theta_{13}=\theta_{23}=-0.5. The output grid's xtx^t is −1,0,1-1, 0, 1; multiplying by 0.5 and subtracting 0.5 gives xs=−1,−0.5,0x^s = -1, -0.5, 0, so the 3 output pixels sample only from the left half of the input. The yy direction works the same way. The 3×33\times3 output corresponds to the top-left quarter of the input.

Two diagrams. (a) The green sampling points on the input U form a neat regular grid that maps one-to-one onto the output V, so the output is the same as the input; (b) the sampling points are affinely transformed into a tilted, shrunken parallelogram that covers only part of the digit, and the output V is the digit straightened and enlarged
Figure 3 from the paper, excerpted from page 4 of the v3 PDF. (a) The identity transformation: the sampling grid is the regular grid; (b) the sampling grid after an affine transformation.

This figure draws the same idea. In (a), the sampling points form a regular grid, and the output is the same as the input; in (b), the sampling points are affinely transformed into a tilted parallelogram that covers only part of the input, so the output is the cropped, rotated, and enlarged result.

The 6 affine parameters can express cropping, translation, rotation, scaling, and skew. When the absolute value of the determinant of the left 2×22\times2 submatrix is less than 1, the sampling grid shrinks into a parallelogram of smaller area, which amounts to cropping out a region.

Tθ\mathcal{T}_\theta can take other forms too. The authors' examples include an attention form that allows only cropping, translation, and isotropic scaling (3 parameters, s,tx,tys, t_x, t_y), an 8-parameter plane projective transformation, and the thin plate spline (TPS), which can apply non-rigid warps. The only requirement is that Tθ\mathcal{T}_\theta be differentiable with respect to its parameters, so that gradients can flow from the sampling points back to θ\theta.

Sampler: Taking Values Between Grid Points

Sampling points rarely land exactly on integer grid points, so the sampler needs an interpolation kernel. The authors write it in a general form and then focus on bilinear interpolation:

Vic=∑nH∑mWUnmc max⁡ ⁣(0, 1−∣xis−m∣) max⁡ ⁣(0, 1−∣yis−n∣)V_i^c = \sum_{n}^{H}\sum_{m}^{W} U_{nm}^c\,\max\!\big(0,\ 1-|x_i^s-m|\big)\,\max\!\big(0,\ 1-|y_i^s-n|\big)

Each output value is a weighted average of the four pixels nearest the sampling point, with weights determined by distance.

The key is that this expression has (sub-)gradients with respect to both UU and the sampling coordinates xisx_i^s and yisy_i^s. Once the gradient reaches the sampling coordinates, it can flow back to θ\theta, and finally to the localisation network.

Sampling points usually do not land exactly on grid points. On a 5×55\times5 input whose values are “row × 5 + column,” for example, a sampling point at row 0.6, column 0.6 gets 0.6×5+0.6=3.60.6\times5+0.6=3.6 from bilinear interpolation, a distance-weighted mix of the four surrounding pixels. As the grid shifts, every sampled value changes continuously, so θ\theta receives a gradient that flows all the way back to the localization network.

This path is what lets the whole module be trained end to end. The gradient of the loss with respect to the output VV passes through the sampler to the sampling coordinates, through the grid generator to θ\theta, and finally into the weights of the localisation network. Nobody has to supply the correct transformation.

Putting It into a Network

The module can be inserted anywhere in a convolutional network, and as many times as you like:

  • In series, at different depths: modules deeper in the network see more abstract features, and their localisation networks have more information for deciding how to transform.
  • In parallel: when a feature map contains several objects or parts that need separate handling, several modules can sit side by side, each focusing on one. The authors also note that in a purely feedforward network, the number of parallel modules caps the number of objects the network can handle separately.

The output size H′H', W′W' can also differ from the input's, so the module can downsample along the way. However, an interpolation kernel with small support, such as bilinear, can cause aliasing when downsampling.

Discussion

Distorted MNIST

The authors make four distorted versions of MNIST, namely rotation (R), rotation plus translation and scaling (RTS), projective transformation (P), and elastic warping (E). They compare an ordinary fully connected network (FCN) and a convolutional network (CNN) against versions with a spatial transformer module added at the input (ST-FCN, ST-CNN), using affine (Aff), projective (Proj), and 16-control-point TPS transformations. All models have about the same number of parameters, the classification part always has three weight layers, and the CNN has two max pooling layers.

Table: Error rates (%) excerpted from Table 1 of the paper, omitting the projective version of ST-FCN.
ModelRRTSPE
FCN2.15.23.13.2
CNN1.20.81.51.4
ST-FCN, Aff1.20.81.52.7
ST-FCN, TPS1.10.81.42.4
ST-CNN, Aff0.70.50.81.2
ST-CNN, Proj0.80.60.81.3
ST-CNN, TPS0.70.50.81.1

Under every distortion, the network with the module beats its corresponding baseline. The most interesting column is RTS. ST-FCN, with no convolution or pooling at all, gets 0.8% error, the same as the CNN with two pooling layers. The authors take this to show that a spatial transformer is another way to achieve spatial invariance. ST-CNN does better still than ST-FCN, because pooling provides even more invariance and convolutions are better at modeling local structure.

On a 60×6060\times60 version with translated digits and background clutter, the gaps are larger, with FCN at 13.2%, CNN 3.5%, ST-FCN 2.0%, and ST-CNN 1.7%.

Of the three transformations, TPS is the most powerful. It can mold elastically warped digits back into something close to the standard shape, and it doesn't overfit on the simpler rotation data. The authors also observe that all the models turn digits into an upright “standard” pose, which is the mean pose in the training data.

Street View House Numbers

SVHN consists of about 200,000 real photos of house numbers, each with 1 to 5 digits that vary widely in size and arrangement; the task is to recognize the whole digit sequence. The authors' baseline model has 11 hidden layers, ending in 5 independent softmax classifiers, each predicting the digit at one position.

They extend this baseline in two ways:

  • ST-CNN Single: one module right after the input, with a four-layer convolutional network as its localisation network.
  • ST-CNN Multi: a module before each of the first four convolutional layers, each with a two-layer fully connected localisation network of 32 units per layer; all modules except the first transform feature maps.

All modules use affine transformations and bilinear sampling, and the regression layers of the localisation networks are all initialized to output the identity transformation.

Table: Sequence error rates (%) excerpted from Table 2 of the paper. 64px means 64×6464\times64 crops centered on the digit sequence; 128px means looser 128×128128\times128 crops with more background. DRAM uses model averaging and Monte Carlo averaging; all the others are single models with a single forward pass.
Model64px128px
Maxout CNN4.0—
CNN (the authors' baseline)4.05.6
DRAM*3.94.5
ST-CNN Single3.73.9
ST-CNN Multi3.63.9

At 64px, ST-CNN Multi set the best result at the time, 3.6%. At 128px, with more background, the baseline CNN slips to 5.6% while ST-CNN holds at 3.9%, because the modules crop out and enlarge the region where the digits are, so the network's resolution and capacity are spent on the digits. The cost is small, with a forward plus backward pass of ST-CNN Multi only 6% slower than the baseline CNN.

Fine-Grained Bird Classification

CUB-200-2011 covers 200 bird species, with about 6,000 training images and 5,800 test images. The birds vary in size and orientation, and the images aren't tightly cropped around them; telling species apart means looking at fine textures and shapes.

The authors' baseline, an Inception network with batch normalization pretrained on ImageNet, is already strong, reaching 82.3% after fine-tuning on CUB and beating the previous best of 81.0%. They then add 2 or 4 modules in parallel, applying attention-form transformations to the input image; the patch cropped by each module is described by its own Inception subnetwork, and the results are concatenated for classification. The whole network is trained with class labels only.

Table: Excerpted from Table 3 of the paper.
ModelAccuracy
CNN (baseline), 224px82.3%
2×ST-CNN, 224px83.1%
2×ST-CNN, 448px83.9%
4×ST-CNN, 448px84.1%

The 4-module version reaches 84.1%, 1.8 percentage points above the baseline. The authors also found 22 images overlapping between the ImageNet training set and the CUB test set (out of 5,794); with those removed, the result is 84.0%.

More interesting is the division of labor the modules learn. In the 2-module version, one becomes a bird-head detector while the other keeps its eye on the body. Earlier methods used keypoint annotations to train a separate detector for each part; here there are no part annotations at all, and the modules find the parts in the data on their own.

The input can be 448px without adding computation, because each module's transformed output is downsampled to 224px before being passed to the rest of the network.

Conclusion

The spatial transformer hands “how to look at this image” over to the network to learn as well. The localisation network predicts a transformation, the grid generator computes the sampling positions, and differentiable bilinear sampling lets gradients flow all the way back. The module needs no extra annotation and no change to the loss function.

The experiments cover distorted MNIST, real house-number photos, and fine-grained bird classification, and in every case the results beat baselines under the same conditions. Without any hints, the modules also learned to straighten digits, crop out house numbers, and look at a bird's head and body separately. The authors also point out that the number of parallel modules caps how many objects can be handled separately, and that downsampling may also cause aliasing.

A spatial transformer can be dropped straight into an existing network, with no change to the loss function and no extra annotation. PyTorch already has affine_grid and grid_sample built in; the examples above were written with these two functions, so wiring one up yourself isn't hard.

If your data has a lot of skew or perspective distortion, like signboard text in street scenes, try putting one in front of your network; that's how RARE does text recognition.