AI Logic

Architectures

SENet

Updated:

Architecture of SENet. The left side shows the overall flow of SE-ResNet-50 (7×7 convolution and max pooling, four stages of residual blocks with SE, global average pooling, and a fully connected layer) with the output shape of each stage. The right side shows the inside of a residual block with SE (the output U of the residual branch is multiplied by per-channel weights computed by global average pooling, fully connected, ReLU, fully connected, and sigmoid, and then added to the shortcut x) along with the equations

Background and overview

SENet (Squeeze-and-Excitation Networks) is a convolutional neural network that incorporates "SE blocks", which multiply each channel of a convolution's output by an input-dependent weight (0 to 1), strengthening useful channels and weakening useless ones. It was published by Hu et al. in 2017 and accepted at CVPR 2018 (an extended version appeared in IEEE TPAMI). An ensemble of models using SE blocks won first place in image classification at ILSVRC 2017.

An ordinary convolution creates new channels by mixing nearby pixels across all input channels. The relationships between channels are implicitly contained in the weights, but only a local neighborhood is seen. Much earlier work, such as the multi-scale convolutions of GoogLeNet (Inception), focused on improving spatial representations. SENet instead focused on explicitly learning the relationships between channels using information from the whole image.

An SE block consists of the following two operations.

  • Squeeze: each channel of the feature map is reduced to a single value with global average pooling, producing a vector that represents "how strongly each channel responded over the whole image".
  • Excitation: that vector is passed through a small two-layer fully connected network and a sigmoid function to produce per-channel weights, which are multiplied into the original feature map.

SE blocks can be inserted afterward into existing networks such as ResNet, ResNeXt, Inception, and MobileNet. The main results of the paper are as follows.

  • On ImageNet, it lowered the top-5 error of ResNet-50 from 7.48% to 6.62%, approaching ResNet-101 (6.52%), which needs nearly twice the computation. The increase in computation is 0.26%.
  • The error rate dropped whichever of ResNet, ResNeXt, VGG, Inception, MobileNet, and ShuffleNet it was added to.
  • In the ILSVRC 2017 classification task, it achieved a top-5 error of 2.251% on the test data, about 25% lower in relative terms than the previous year's winner (2.991%).

Theory: Squeeze and Excitation

An SE block takes the output U∈RH×W×C\mathbf{U} \in \mathbb{R}^{H \times W \times C} of some transformation FtrF_{tr} (a convolution, the residual branch of a ResNet, etc.), reweights it channel by channel, and returns it. Let the cc-th channel of U\mathbf{U} be uc∈RH×W\mathbf{u}_c \in \mathbb{R}^{H \times W}.

A convolution output channel uc\mathbf{u}_c is the sum of all input channels xs\mathbf{x}_s, each convolved with its own kernel vcs\mathbf{v}_c^s (equation 1 of the paper).

uc=vc∗X=∑s=1C′vcs∗xs\mathbf{u}_c = \mathbf{v}_c * \mathbf{X} = \sum_{s=1}^{C'} \mathbf{v}_c^s * \mathbf{x}_s

The relationships between channels are contained in vc\mathbf{v}_c, but they are entangled with local spatial relationships, and only what lies within the receptive field is visible. The SE block compensates for this in the following three steps.

  1. Squeeze: average each channel spatially to produce one value per channel, z∈RC\mathbf{z} \in \mathbb{R}^{C} (equation 2). This makes information from the whole image available in every layer.
  2. Excitation: pass z\mathbf{z} through a fully connected layer that reduces the number of channels to C/rC/r, a ReLU, and a fully connected layer that restores it to CC, then apply the sigmoid function σ\sigma to obtain weights s\mathbf{s} between 0 and 1 (equation 3).
  3. Scale: multiply uc\mathbf{u}_c by the scalar weight scs_c (equation 4).
zc=Fsq(uc)=1H×W∑i=1H∑j=1Wuc(i,j)z_c = F_{sq}(\mathbf{u}_c) = \frac{1}{H \times W} \sum_{i=1}^{H} \sum_{j=1}^{W} u_c(i, j) s=Fex(z,W)=σ(W2 δ(W1z)),W1∈RCr×C,  W2∈RC×Cr\mathbf{s} = F_{ex}(\mathbf{z}, \mathbf{W}) = \sigma\big(\mathbf{W}_2\, \delta(\mathbf{W}_1 \mathbf{z})\big), \qquad \mathbf{W}_1 \in \mathbb{R}^{\frac{C}{r} \times C},\ \ \mathbf{W}_2 \in \mathbb{R}^{C \times \frac{C}{r}} x~c=Fscale(uc,sc)=sc⋅uc\tilde{\mathbf{x}}_c = F_{scale}(\mathbf{u}_c, s_c) = s_c \cdot \mathbf{u}_c

δ\delta is the ReLU, and rr is the reduction ratio (16 by default in the paper).

Why Excitation is designed this way

The paper requires two properties of the Excitation function.

  • Flexibility: it must be able to learn nonlinear relationships between channels. Hence two fully connected layers are stacked with a ReLU in between.
  • Non-mutual exclusivity: it must be able to emphasize multiple channels at once, not just one. Hence it uses a sigmoid function that outputs 0 to 1 independently for each channel, rather than a softmax whose outputs sum to 1.

The middle layer is narrowed to C/rC/r to limit parameters and aid generalization.

Since the Excitation output s\mathbf{s} changes with each input image, the paper says the SE block can be regarded as "self-attention over channels". Even in the same network, which channels are emphasized depends on the image.

Integration into existing networks and the overall architecture

An SE block can be integrated into any network once the transformation FtrF_{tr} is chosen.

  • Simple CNNs such as VGG: insert it after the activation function following each convolution.
  • Inception: treat the whole Inception module as FtrF_{tr} and apply the SE block to the module's output (SE-Inception).
  • ResNet: treat the residual branch as FtrF_{tr} and apply the SE block to the output of the residual branch before the addition with the identity shortcut (SE-ResNet; the right side of the figure at the top of the article). ResNeXt, Inception-ResNet, MobileNet, and ShuffleNet can be handled in the same way.

Architecture of SE-ResNet-50 (Table 1 of the paper; the left side of the figure at the top of the article)

It adds an SE block to each bottleneck block of ResNet-50. The output dimensions of the SE fully connected layers (C/rC/r and CC) for each stage are as follows (r=16r = 16).

StageOutput sizeBlocksBottleneck output channels CCSE fully connected outputs
conv2_x56×56325616, 256
conv3_x28×28451232, 512
conv4_x14×146102464, 1024
conv5_x7×732048128, 2048

The initial 7×7 convolution and 3×3 max pooling, and the final global average pooling and 1000-class fully connected layer, are the same as in ResNet-50.

Increase in computation and parameters (Section 4 of the paper)

The computation for one 224×224 image is about 3.87 GFLOPs for SE-ResNet-50 versus about 3.86 GFLOPs for ResNet-50 (a 0.26% increase). The only added parameters are the weights of the two fully connected layers in Excitation, counted by the following equation (equation 5).

2r∑s=1SNs⋅Cs2\frac{2}{r} \sum_{s=1}^{S} N_s \cdot C_s^2

SS is the number of stages, CsC_s is the number of output channels of stage ss, and NsN_s is the number of blocks in stage ss. SE-ResNet-50 adds about 2.5 million parameters, roughly a 10% increase over the approximately 25 million of ResNet-50. Most of them come from the last stage, which has the most channels.

Training settings (ImageNet, Section 5.1 of the paper)

ItemSetting
Data augmentation224×224 crops with random scale and aspect ratio, horizontal flips
OptimizationSynchronous SGD, momentum 0.9, minibatch 1024
Learning rateStarts at 0.6, divided by 10 every 30 epochs (step decay), 100 epochs
Weight initializationHe initialization
Reduction ratior=16r = 16
EvaluationResize the shorter side to 256 and take the center 224×224 crop

The original networks and the SE networks are trained with the same settings and compared.

Why it works

The paper investigates what makes it work through experiments that remove or replace parts of the SE block (ImageNet, SE-ResNet-50).

  • Information from the whole image is needed (Table 16): removing global average pooling and replacing the fully connected layers with 1×1 convolutions with the same number of channels (NoSqueeze) gave a top-1 error of 22.93%, worse than the SE block (22.28%). The computation also grows substantially, to 4.27 GFLOPs. Using a summary of the whole image, not just local information at each position, is what helps.
  • How the weights are produced matters (Table 12): replacing the sigmoid with Tanh made it slightly worse (22.28% → 23.00%), and replacing it with ReLU gave 23.47%, worse than ResNet-50 without SE blocks (23.30%).
  • Average pooling is slightly better than max pooling (Table 11): using max pooling for Squeeze is also effective, but averaging gave slightly better results (22.57% vs 22.28%).

The role changes with depth

The paper examined how the Excitation outputs (per-channel weights) of a trained SE-ResNet-50 vary across classes (Figure 6).

  1. In shallow layers, the distribution of weights was very similar across different classes. Low-level features common to all classes are emphasized in the same way.
  2. In deeper layers, the distribution of weights became increasingly class-specific. Channels useful for distinguishing classes are selected according to the class.
  3. In part of the last stage (SE_5_2), most weights were close to 1, and the SE block did almost nothing (close to an identity mapping).

As an everyday analogy, the SE block is "the volume knobs on a mixer". After listening to the whole song (image) once, it decides which instruments (channels) to turn up and which to turn down. In shallow layers it makes the same adjustment regardless of the song; in deeper layers it adjusts differently for each song.

Based on the third observation, the paper also tries removing the SE blocks in the last stage. The top-5 error on ImageNet worsened by less than 0.1%, while the parameter increase dropped from about 10% to about 4%. This is an option when the number of parameters must be kept down.

Experimental results

ImageNet error rates (validation set, single 224×224 crop, %. Table 2 of the paper)

The values of the original networks retrained by the authors with the same settings (re-implementation) are compared with those with SE blocks added. Numbers in parentheses are the improvements over the re-implementation.

ModelRe-impl. top-1Re-impl. top-5GFLOPsSE top-1SE top-5GFLOPs
ResNet-5024.807.483.8623.29 (1.51)6.62 (0.86)3.87
ResNet-10123.176.527.5822.38 (0.79)6.07 (0.45)7.60
ResNet-15222.426.3411.3021.57 (0.85)5.73 (0.61)11.32
ResNeXt-5022.115.904.2421.10 (1.01)5.49 (0.41)4.25
ResNeXt-10121.185.577.9920.70 (0.48)5.01 (0.56)8.00
VGG-16 (with BN)27.028.8115.4725.22 (1.80)7.70 (1.11)15.48
BN-Inception25.387.892.0324.23 (1.15)7.14 (0.75)2.04
Inception-ResNet-v220.375.2111.7519.80 (0.57)4.79 (0.42)11.76

The following can be read from the table.

  • It works regardless of depth: the error rate dropped for ResNet-50, 101, and 152 alike. SE-ResNet-101 (top-5 6.07%) outperformed the deeper ResNet-152 (6.34%).
  • It is about as effective as going deeper, with almost no extra computation: SE-ResNet-50 (3.87 GFLOPs) approached ResNet-101, which has about twice the computation. SE-ResNeXt-50 (top-5 5.49%) outperformed ResNeXt-101 (5.57%), which has about twice the parameters and computation.
  • It also works for networks without residual connections: the error rate also dropped for VGG-16 and BN-Inception.

Lightweight networks (ImageNet, %. Table 3 of the paper)

ModelRe-impl. top-1MFLOPsParamsSE top-1MFLOPsParams
MobileNet28.45694.2M25.3 (3.1)5724.7M
ShuffleNet32.61401.8M31.0 (1.6)1422.4M

CIFAR error rates (%. Tables 4 and 5 of the paper)

ModelCIFAR-10With SECIFAR-100With SE
ResNet-1106.375.2126.8823.85
ResNet-1645.464.3924.3321.31
WRN-16-84.273.8820.4319.14
Shake-Shake + Cutout2.562.1215.8515.41

On CIFAR-10 and 100 too, the SE version had a lower error rate in every combination (Shake-Shake on CIFAR-100 is Shake-Even 29 2x4x64d).

Object detection (COCO minival, swapping the backbone of Faster R-CNN, %. Table 7 of the paper)

BackboneAP@IoU=0.5AP
ResNet-5057.938.0
SE-ResNet-5061.040.4
ResNet-10160.139.9
SE-ResNet-10162.741.9

Even on tasks other than classification, simply switching to an SE backbone raised AP by 2.0–2.4 points.

ILSVRC 2017

The authors combined models such as SENet-154, which integrates SE blocks into an improved ResNeXt, and won first place with a top-5 error of 2.251% on the test data. On its own, SENet-154 achieved top-1 18.68% and top-5 4.47% with a single 224×224 crop on the validation set (Table 8).

Practical notes

Keep the following points in mind when using SE blocks.

  • A reduction ratio rr of 16 is a good default: in Table 10 of the paper, the error rate barely changed for rr from 2 to 16 (top-1 22.25–22.29%) and became slightly worse at r=32r = 32 (22.72%). Smaller rr greatly increases the parameters (45.7M at r=2r = 2, 28.1M at r=16r = 16). The paper also notes that varying rr per layer might improve results further.
  • Time increases more than the computation suggests: the computation increases by only 0.26%, but one forward-backward pass in training on 8 Titan X GPUs with a minibatch of 256 went from 190 ms to 209 ms (about 10%). The paper expects this gap to shrink as global average pooling and small fully connected layers are further optimized in GPU libraries. Inference on CPU went from 164 ms to 167 ms.
  • Parameters increase by about 10%: most come from the last stage. Removing the SE blocks in the last stage, or placing the SE block right after the 3×3 convolution (where there are fewer channels), reduces parameters while keeping accuracy almost the same (Table 15).
  • Biases in the fully connected layers: the paper writes that for ResNet, removing the biases of the Excitation fully connected layers made it easier to learn channel relationships (the setting used in the ablation experiments).

When integrating into a ResNet, place the SE block on the residual branch before the addition with the shortcut. Placing it after the addition and ReLU (SE-POST) increased the error rate in Table 14 of the paper (top-1 22.28% → 22.78%). As long as it is before the addition, placing it before the residual branch (SE-PRE) or on the shortcut side (SE-Identity) gave nearly the same accuracy.

Comparison with other methods

Comparing the SE block with other mechanisms that change features or weights depending on the input, from the same viewpoints, gives the following.

MechanismWhat it produces from the inputWhat it multipliesWhole-image informationExtra computation
SE blockPer-channel weights (sigmoid, 0–1)Channels of the output feature mapUsed (global average pooling)Very small (2 fully connected layers)
NoSqueeze (SE ablation)Per-position, per-channel weightsOutput feature mapNot used (1×1 convolutions)Large (3.86 → 4.27 GFLOPs)
Residual Attention Network (Wang et al.)Spatial and channel weights (masks from hourglass modules)Feature maps between ResNet stagesUsedNot compared in the SE paper
Dynamic convolutionWeights for KK kernels (softmax, summing to 1)Convolution kernelsUsed (global average pooling)Small
CondConvWeights per expert (kernel) (sigmoid)Convolution kernelsUsed (global average pooling)Small

The distinctive feature of the SE block is that it uses whole-image information while being computationally very light. The paper positions the SE block as a lightweight mechanism focused only on channel relationships, in contrast to the Residual Attention Network, which builds spatial and channel attention with hourglass modules. Dynamic convolution and CondConv produce weights in the same "global average pooling → fully connected" form as the SE block, but they multiply the convolution kernels rather than the output features.

Rough guidelines for choosing:

  • To raise the accuracy of an existing CNN with almost no extra computation: adding SE blocks to the residual branches is the easy option. It can be tried without major changes to a trained architecture.
  • When inference speed is critical (especially on GPUs): time can increase more than the computation figures suggest, so measure on the actual hardware before deciding.
  • When spatial attention is also needed: the SE block handles only channels and applies the same weight at every position. To vary the weights by position, consider methods that combine it with spatial attention.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.ops import SqueezeExcitation

"""
1. Build an SE block exactly as in equations (2)-(4) of the paper and insert it into a ResNet bottleneck (an SE-ResNet module)
2. Use torchvision.ops.SqueezeExcitation (the same computation written with 1×1 convolutions)
"""


class SEBlock(nn.Module):
  def __init__(self, channels, reduction=16):
    super().__init__()
    self.fc1 = nn.Linear(channels, channels // reduction, bias=False)   # W1: C -> C/r (the paper found no bias better for ResNet)
    self.fc2 = nn.Linear(channels // reduction, channels, bias=False)   # W2: C/r -> C

  def forward(self, u):                                   # u: [N, C, H, W]
    z = u.mean(dim=(2, 3))                                # Squeeze: global average pooling -> [N, C]
    s = torch.sigmoid(self.fc2(F.relu(self.fc1(z))))      # Excitation: σ(W2 δ(W1 z)) -> 0 to 1
    return u * s[:, :, None, None]                        # Scale: multiply channel c by s_c


class SEBottleneck(nn.Module):
  """SE-ResNet bottleneck: SE block after 1×1 -> 3×3 -> 1×1, before the addition with the shortcut"""
  def __init__(self, in_ch, mid_ch, stride=1, reduction=16):
    super().__init__()
    out_ch = mid_ch * 4
    self.residual = nn.Sequential(
      nn.Conv2d(in_ch, mid_ch, 1, bias=False), nn.BatchNorm2d(mid_ch), nn.ReLU(inplace=True),
      nn.Conv2d(mid_ch, mid_ch, 3, stride=stride, padding=1, bias=False), nn.BatchNorm2d(mid_ch), nn.ReLU(inplace=True),
      nn.Conv2d(mid_ch, out_ch, 1, bias=False), nn.BatchNorm2d(out_ch),
    )
    self.se = SEBlock(out_ch, reduction)
    self.shortcut = nn.Identity()
    if stride != 1 or in_ch != out_ch:                    # 1×1 convolution shortcut only when the shape changes
      self.shortcut = nn.Sequential(nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=False), nn.BatchNorm2d(out_ch))

  def forward(self, x):
    return F.relu(self.se(self.residual(x)) + self.shortcut(x))   # SE before the addition (not SE-POST)


block = SEBottleneck(in_ch=256, mid_ch=64)                # conv2_x block: SE fully connected 256 -> 16 -> 256
x = torch.randn(8, 256, 56, 56)
block.train()                                             # BN uses minibatch statistics
y = block(x)
print(y.shape)                                            # [8, 256, 56, 56]
print(sum(p.numel() for p in block.se.parameters()))      # 2 × 256 × 16 = 8192 (one block's share of eq. (5))

# --- torchvision component ---
# squeeze_channels takes the number of channels in the middle layer (C/r), not the ratio r. The 1×1 convolutions have biases
se = SqueezeExcitation(input_channels=256, squeeze_channels=256 // 16)
se.eval()
with torch.no_grad():
  print(se(x).shape)                                      # [8, 256, 56, 56]

FAQ

Q. Where should the SE block be inserted?
A.

For ResNet-style networks, the paper's form inserts it at the end of the residual branch (after the third convolution and BN), before the addition with the shortcut. In the paper's comparison (Table 14), as long as it is before the addition, placing it before the residual branch or on the shortcut side gave nearly the same accuracy, but placing it after the addition and ReLU increased the error rate (top-1 22.28% → 22.78%). In Inception it goes at the module output, and in simple CNNs like VGG it goes after the activation function of each convolution.

Q. What value should the reduction ratio r be?
A.

The paper's default is r=16r = 16. For SE-ResNet-50, changing rr among 2, 4, 8, and 16 barely changed the top-1 error (22.25–22.29%), and r=32r = 32 was slightly worse at 22.72%. Meanwhile, the parameters grow substantially as rr gets smaller: 45.7M at r=2r = 2 versus 28.1M at r=16r = 16. Balancing accuracy and size, trying 16 first is a good rule of thumb.

Q. Why use a sigmoid function instead of a softmax?
A.

To allow multiple channels to be emphasized at the same time. With a softmax, the weights sum to 1, so strengthening one channel weakens the others. The sigmoid function outputs 0 to 1 independently for each channel, so however many channels are useful, each can be strengthened. In the paper's comparison, replacing the sigmoid with Tanh or ReLU lowered accuracy, and with ReLU it was worse than ResNet-50 without SE blocks.

References

  1. Hu, J., Shen, L., Albanie, S., Sun, G., & Wu, E. (2018). Squeeze-and-Excitation Networks. CVPR 2018 (extended version in IEEE TPAMI). arXiv:1709.01507.
  2. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  3. Xie, S., Girshick, R., Dollár, P., Tu, Z., & He, K. (2017). Aggregated Residual Transformations for Deep Neural Networks. CVPR 2017. arXiv:1611.05431.
  4. Official implementation (Caffe) and pretrained models: hujie-frank/SENet.
  5. PyTorch. torchvision.ops.SqueezeExcitation (documentation).