AI Logic

Architectures

Network In Network

Updated:

Structure of Network In Network. The left shows the overall flow (three mlpconv layers with max pooling and dropout, global average pooling, softmax). The right shows the inside of an mlpconv layer (a k×k convolution followed by two 1×1 convolutions, each with ReLU) and global average pooling, which averages each class's feature map into a score.

Background and overview

Network In Network (NIN) is a convolutional neural network that replaces the linear filters of convolutional layers with small multilayer perceptrons (MLPs) and replaces the final fully connected layers with global average pooling. It was published in 2013 by Lin et al. of the National University of Singapore and accepted at ICLR 2014. The name comes from placing small networks (MLPs) inside a network (CNN).

An ordinary convolutional layer applies a linear filter to a small region of the input (the receptive field) and then passes the result through an activation function. The paper argued that this has limited power to group "the many appearances of the same concept" (limited abstraction ability). It therefore proposed the mlpconv layer, which passes each receptive field through an MLP. An mlpconv layer can be built simply by stacking 1×1 convolutions after an ordinary convolution.

The paper's main results are as follows.

  • It achieved test error rates of 10.41% on CIFAR-10 (8.81% with data augmentation) and 35.68% on CIFAR-100, improving on the state of the art at the time by more than 1 percentage point.
  • Replacing the fully connected layers with global average pooling lowered the error rate of the same network from 11.59% to 10.41%. Global average pooling has no parameters and itself acts to suppress overfitting.

The two components, 1×1 convolution and global average pooling, were widely adopted by later models such as GoogLeNet and ResNet.

Architecture

NIN is a network that stacks mlpconv layers and ends with global average pooling. In the figure at the top of the article, the left shows the overall flow, and the right shows the inside of an mlpconv layer and global average pooling.

The mlpconv layer

An ordinary convolutional layer (with ReLU as the activation function) computes the output of channel kk from the input region xi,j\boldsymbol{x}_{i,j} centered at position (i,j)(i, j) as follows.

fi,j,k=max⁡(wk⊤xi,j, 0)f_{i,j,k} = \max(\boldsymbol{w}_k^\top \boldsymbol{x}_{i,j},\ 0)

An mlpconv layer passes the same region xi,j\boldsymbol{x}_{i,j} through an nn-layer MLP (Eq. (2) of the paper).

fi,j,k11=max⁡(wk11⊤xi,j+bk1, 0)f^{1}_{i,j,k_1} = \max\big({\boldsymbol{w}^{1}_{k_1}}^{\top} \boldsymbol{x}_{i,j} + b_{k_1},\ 0\big) fi,j,knn=max⁡(wknn⊤fi,j n−1+bkn, 0)f^{n}_{i,j,k_n} = \max\big({\boldsymbol{w}^{n}_{k_n}}^{\top} \boldsymbol{f}^{\,n-1}_{i,j} + b_{k_n},\ 0\big)

The MLP's weights are shared across all positions; that is, the same MLP is slid over the input. This is the same computation as the following steps.

  1. Apply an ordinary k×kk \times k convolution and ReLU (the first MLP layer).
  2. Apply a 1×1 convolution and ReLU (the second MLP layer).
  3. Apply another 1×1 convolution and ReLU (the third MLP layer).

A 1×1 convolution computes a weighted sum of the channels at the same position. The paper calls this "cross-channel parametric pooling" and explains that stacking it lets the network learn complex relationships between channels. In the paper's experiments, the MLP in each mlpconv layer has 3 layers.

Global average pooling

The last mlpconv layer outputs as many feature maps as there are classes to classify. Averaging each feature map over all positions gives a vector whose length is the number of classes. This vector goes straight into the softmax function, without any fully connected layer, to produce class probabilities.

If feature map cc has size H×WH \times W, the score of class cc is given by the following equation.

sc=1HW∑i=1H∑j=1Wfi,j,cs_c = \frac{1}{HW} \sum_{i=1}^{H} \sum_{j=1}^{W} f_{i,j,c}

Because each feature map corresponds to one class, the final feature maps can be read as "maps of how much each location looks like that class."

Overall flow

The networks in the paper's experiments have the following form for every dataset.

  1. mlpconv layer → max pooling (halving height and width) → dropout
  2. mlpconv layer → max pooling → dropout
  3. mlpconv layer (outputs one feature map per class) → max pooling
  4. Global average pooling → softmax function

Dropout is applied to the outputs of all mlpconv layers except the last. The number of channels and receptive field size of each layer are given in the paper's supplementary material, not in the main text. In the CIFAR-10 experiments, the channel counts match the corresponding layers of the maxout network, and the receptive field sizes were chosen on validation data.

Training

The paper's training setup follows the procedure of the AlexNet paper.

ItemValue
Mini-batch128
Initial weights and learning rateSet manually to suitable values
Learning rate scheduleDivide by 10 when training accuracy stops improving; done twice, ending at 1/100 of the initial value
RegularizationDropout on the outputs of all mlpconv layers except the last, weight decay
Preprocessing (CIFAR)Global contrast normalization and ZCA whitening (same as the maxout network paper)
Implementationcuda-convnet

On CIFAR-10, two settings, the receptive field size and weight decay, were chosen on validation data (the last 10,000 training images), after which the model was retrained from scratch on the combined training and validation data. CIFAR-100 uses the same settings as CIFAR-10, with only the output of the last mlpconv layer changed to 100 maps.

Why it works

The two components of NIN work for different reasons.

mlpconv: distinguishing finer patterns within the receptive field

A linear filter combined with an activation function can distinguish a concept only when its examples lie together on one side of a plane (a hyperplane). The paper points out that in real data, examples of the same concept are often scattered over curved shapes (nonlinear manifolds).

An ordinary CNN compensates for this by adding more filters. For example, to detect "diagonal lines," it prepares many filters with slightly different angles. But then the next layer has to consider all combinations of them. By passing each receptive field through an MLP, the mlpconv layer builds more abstract features at each position before the upper layers combine them.

The paper also compares NIN with maxout from the same period. Maxout takes the maximum of several linear outputs and can distinguish concepts that lie within convex regions. An MLP can approximate any function, so it can represent more flexible shapes.

Global average pooling: the structure itself acts as a regularizer

Fully connected layers connect the feature maps to the classes through a "black box" and have many parameters, making them prone to overfitting. Global average pooling has the following advantages.

  • It has no learnable parameters, so no overfitting occurs in this layer.
  • Feature maps and classes correspond one to one, so the feature maps can be interpreted as confidence maps for the classes.
  • It averages away spatial information, so the result changes little when objects in the input shift position.

However, since each feature map directly becomes a class score, the last layer must be powerful enough to build features strong enough to tell the classes apart. The paper explains that global average pooling works well precisely because of the mlpconv layers.

In the paper's visualization (Figure 4), in the last mlpconv layer of a trained NIN, the feature map for the correct class responded most strongly, and within it, the region containing the object lit up the most. This means the rough location of the object is revealed even though the model was trained only with class labels. This property was later exploited by methods that visualize the basis of a model's decisions, such as CAM.

Experimental results

Error rates on benchmarks (test data, %; Tables 1-4 of the paper)

DatasetNINMain methods compared at the time
CIFAR-1010.41maxout + dropout 11.68
CIFAR-10 (with data augmentation)8.81DropConnect (12 networks) 9.32, maxout 9.38
CIFAR-10035.68Tree-based priors 36.85, maxout 38.57
SVHN2.35maxout 2.47 (DropConnect 1.94)
MNIST0.47maxout 0.45, stochastic pooling 0.47

On CIFAR-10 and CIFAR-100, NIN surpassed the state of the art at the time. On SVHN and MNIST, it fell short of the best results but came close. The data augmentation consists of translation and horizontal flipping.

Global average pooling vs. fully connected layers (CIFAR-10 test error rate, %; Table 5 of the paper)

Final layerError rate (%)
mlpconv + fully connected11.59
mlpconv + fully connected + dropout10.88
mlpconv + global average pooling10.41

With everything else kept the same and only the final layer changed, global average pooling gave the best result. Without dropout, the fully connected layer overfit and gave the worst result.

The paper runs the same comparison on an ordinary CNN (3 convolutional layers and 1 locally connected layer). The results were 17.56% with fully connected layers alone, 15.99% with dropout added, and 16.46% with global average pooling instead. Global average pooling works as a regularizer, but it did not match dropout. The paper suspects this is because it is hard to build class confidence maps with linear filters alone.

Effect of dropout

Removing the dropout between mlpconv layers gave a CIFAR-10 error rate of 14.51%. Adding dropout reduced the test error rate by more than 20% (relative).

Practical considerations

Keep the following points in mind when using NIN or taking it as a reference.

  • Match the channel count of the last layer to the number of classes: The output of global average pooling directly becomes the class scores, so the number of output channels of the last mlpconv layer must equal the number of classes. To change the number of classes, replace the last 1×1 convolution.
  • The activation function after the last 1×1 convolution: In Eq. (2) of the paper, ReLU is applied to every layer of the MLP. In that form, class scores are 0 or greater and cannot be negative. To allow negative scores, remove the last ReLU. When using other implementations, check which form they use.
  • Channel counts and receptive field sizes are not in the main text: The paper's main text does not give the concrete settings of each layer; they are left to the supplementary material. Settings in other implementations are not necessarily the same as the paper's.
  • No batch normalization: NIN predates batch normalization. When training with modern settings, adding batch normalization after each convolution tends to stabilize training, but it departs from the paper's form.

In an ordinary CNN, global average pooling sometimes fell short of fully connected layers with dropout (16.46% vs. 15.99% on CIFAR-10 in the paper). Simply replacing fully connected layers with global average pooling does not always help; it assumes the last layer can build sufficiently strong features.

Comparison with other methods

The two components of NIN compare with other methods that serve the same roles as follows.

Computation within the receptive field

LayerComputation within the receptive fieldWhat it can separateExtra computation
Ordinary convolutional layerLinear filter + activation functionConcepts lying on one side of a planeNone
Maxout layerMaximum of several linear outputsConcepts lying within a convex regionSeveral linear outputs
mlpconv layerMLP (a k×kk \times k convolution stacked with 1×1 convolutions)Any shape (an MLP is a universal approximator)The 1×1 convolutions

The final classification layer

MethodParametersOverfittingInterpretability
Fully connected layersManyProne to it; needs dropoutHard to see how features relate to classes
Global average poolingNoneDoes not occur in this layerOne feature map = one class

Influence on later models

ModelHow it uses the same components as NIN
GoogLeNetReduces channels with 1×1 convolutions before applying large convolutions; ends with global average pooling (the paper states it borrowed heavily from NIN)
ResNetUses 1×1 convolutions in bottleneck blocks; ends with global average pooling
Highway NetworksIn the CIFAR experiments, replaced the final fully connected layer with a 1×1 convolution and global average pooling (the paper states it followed NIN)

Rough guidelines for choosing:

  • Building a classification layer with few parameters: Use global average pooling. Most modern image classification models adopt this form.
  • Changing the channel count or mixing channels: Use 1×1 convolutions. They suit computationally cheap dimensionality reduction or expansion.
  • Using an image classification model as-is: Rather than NIN itself, it is common to choose a model such as ResNet, which has the same components and can be made deep with batch normalization and residual connections.

PyTorch example

Show code
python
import torch
import torch.nn as nn

"""
An example that builds Network In Network (Lin et al. 2014) following Sections 3.1-3.3 and 4.1 of the paper
- mlpconv layer = k×k conv -> 1×1 conv -> 1×1 conv (each with ReLU; Eq. (2))
- Max pooling (halving height and width) after each mlpconv layer, dropout except after the last
- The last mlpconv layer outputs one feature map per class, then global average pooling -> softmax
Channel counts and receptive field sizes are not in the paper's main text, so the values here are examples (PyTorch has no built-in NIN)
"""


def mlpconv(in_ch, mid_ch, out_ch, kernel_size, padding):
  # Same computation as applying a 3-layer MLP to each receptive field. MLP weights are shared across all positions
  return nn.Sequential(
    nn.Conv2d(in_ch, mid_ch, kernel_size, padding=padding), nn.ReLU(inplace=True),
    nn.Conv2d(mid_ch, mid_ch, 1), nn.ReLU(inplace=True),     # Cross-channel parametric pooling
    nn.Conv2d(mid_ch, out_ch, 1), nn.ReLU(inplace=True),
  )


class NIN(nn.Module):
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      mlpconv(3, 192, 96, 5, 2),                     # 32×32
      nn.MaxPool2d(2), nn.Dropout(0.5),             # → 16×16
      mlpconv(96, 192, 192, 5, 2),
      nn.MaxPool2d(2), nn.Dropout(0.5),             # → 8×8
      mlpconv(192, 192, num_classes, 3, 1),          # The last one outputs one feature map per class
      nn.MaxPool2d(2),                              # -> 4×4 (the paper applies max pooling after each mlpconv)
    )
    self.gap = nn.AdaptiveAvgPool2d(1)               # Global average pooling (no parameters)

  def forward(self, x):
    x = self.features(x)                            # [N, num_classes, 4, 4]
    return self.gap(x).flatten(1)                   # [N, num_classes]; fed directly to softmax


model = NIN(num_classes=10)
x = torch.randn(8, 3, 32, 32)

model.train()                                       # Dropout is active
logits = model(x)
loss = nn.functional.cross_entropy(logits, torch.randint(0, 10, (8,)))   # Softmax + cross-entropy
loss.backward()

model.eval()                                        # Disable dropout
with torch.no_grad():
  probs = model(x).softmax(dim=1)                   # [8, 10]
  class_maps = model.features(x)                    # Each channel is a "map of how much it looks like that class"

# Parameter count: no final fully connected layer, so the classification part has 0 parameters
print(sum(p.numel() for p in model.parameters()))

FAQ

Q. What does a 1×1 convolution do?
A.

At each spatial position, it computes weighted sums of the input channels to create new channels. This is the same computation as applying a fully connected layer to the "vector of channel values" at each position. In NIN, stacking it together with ReLU applies a small MLP to each receptive field. In later models such as GoogLeNet and ResNet, it is also used to reduce the number of channels and lighten computation.

Q. Why does global average pooling make overfitting less likely?
A.

Because global average pooling only takes averages and has no learnable parameters. Fully connected layers connect every value of the feature maps to the classes through weights, so they have many parameters and tend to fit the training data too closely. On CIFAR-10 in the paper, the error rate was 11.59% with fully connected layers, 10.88% with dropout added, and 10.41% when replaced with global average pooling.

Q. How is NIN related to GoogLeNet's Inception?
A.

The GoogLeNet paper states that the name Inception derives from the NIN paper and that it makes heavy use of NIN's 1×1 convolutions. Inception modules place 1×1 convolutions before the 3×3 and 5×5 convolutions to reduce the number of channels, and the end of the network also uses global average pooling instead of stacked fully connected layers. However, whereas NIN used 1×1 convolutions to increase representational power, GoogLeNet uses them mainly to reduce the number of channels and keep computation down.

References

  1. Lin, M., Chen, Q., & Yan, S. (2014). Network In Network. ICLR 2014. arXiv:1312.4400.
  2. Goodfellow, I. J., Warde-Farley, D., Mirza, M., Courville, A., & Bengio, Y. (2013). Maxout Networks. ICML 2013. arXiv:1302.4389.
  3. Szegedy, C., et al. (2015). Going Deeper with Convolutions. CVPR 2015. arXiv:1409.4842.
  4. Srivastava, R. K., Greff, K., & Schmidhuber, J. (2015). Training Very Deep Networks. NeurIPS 2015. arXiv:1507.06228.