ResNet (Residual Network) is a convolutional neural network that inserts "shortcut connections" that add the input directly to the output every few layers. What the layers learn is not the output itself but "the difference from the input (the residual)". He et al. at Microsoft Research proposed it in 2015, and it made it possible to train networks with more than 100 layers, which had been difficult until then.
At the time, it was known that CNNs such as VGG (16–19 layers) and GoogLeNet (22 layers) became more accurate as they grew deeper. However, simply stacking more layers caused a problem beyond a certain depth: even the error on the training data got worse (the degradation problem). ResNet solved this problem with a simple mechanism, the shortcut connection.
The main results of the paper are as follows.
It trained networks of up to 152 layers on ImageNet. That is 8 times deeper than VGG, yet the computation (FLOPs) is lower than VGG-16/19.
An ensemble of six models of different depths achieved a top-5 error of 3.57% on the test set and won first place in ILSVRC 2015 image classification.
On COCO object detection, simply replacing the backbone network from VGG-16 with ResNet-101 improved the standard metric by 28% relative.
The shortcut connection (residual connection) has since become a standard component of deep networks. The "add the input, then normalize" mechanism in each sublayer of the Transformer follows the same idea.
The problem it addressed: deeper networks have higher training error
The problem ResNet solved is that making a network deeper lowers accuracy, not because of overfitting but because optimization becomes harder.
The paper compared 20-layer and 56-layer "plain" networks (networks with no shortcuts, made only by stacking convolutions) on CIFAR-10 and showed that the 56-layer network had higher error not only on the test data but also on the training data. The same thing happened with 18 and 34 layers on ImageNet. Since the training error is higher, this is not overfitting (fitting the training data but not new data).
This is puzzling. Consider a deep model made by adding layers to a shallow model. If every added layer is a "layer that outputs its input unchanged (identity mapping)", the deep model produces the same output as the shallow one. So the deep model has at least one solution that is no worse than the shallow model. Yet training does not find that solution, so the paper reasoned that "it may be difficult for optimization methods to approximate an identity mapping with many nonlinear layers".
The degradation problem is treated as separate from vanishing gradients. The plain networks in the paper used batch normalization and He initialization, and the paper confirmed that neither the forward signals nor the backward gradients vanished, yet reported that the training error was still hard to reduce. As for the cause, the paper only speculates that "deep plain networks may simply converge very slowly".
Theory: residual learning and shortcut connections
The idea of ResNet is to have the layers learn the difference from the input instead of learning the target function directly.
Let H(x) be the function that a few layers should learn. In ResNet, the layers learn the residual F(x):=H(x)−x, and finally the input x is added to recover the original function F(x)+x. This path that "adds the input unchanged" is the shortcut connection.
One block (a residual block) is computed as follows.
Pass the input x through 2–3 convolutional layers to compute F(x).
Right after each convolution, apply batch normalization (BN), then ReLU (the ReLU after the last convolution is moved to step 3).
Through the shortcut, add the input x unchanged to F(x) element-wise.
Apply ReLU to the sum to produce the block's output.
As an equation (biases omitted):
y=F(x,{Wi})+x
For a two-layer block, F=W2σ(W1x), where σ is ReLU. The shortcut has no weights, so it adds almost no parameters or computation (only the element-wise addition).
For the addition to work, F(x) and x must have the same shape. Where the number of channels or the spatial size changes, a linear projection with weights Ws is inserted into the shortcut to match the shapes.
y=F(x,{Wi})+Wsx
The paper compares three ways of matching shapes.
Option
Where the shape changes
Elsewhere
Extra parameters
A
Identity (missing channels are zero-padded)
Identity
None
B
Projection by 1×1 convolution
Identity
A few
C
Projection by 1×1 convolution
Projection by 1×1 convolution
Many
Where the spatial size is halved, every option computes the shortcut with stride 2. ResNet-50 and deeper use B.
If F has only one layer, the block becomes nearly the same as a linear layer y=W1x+x, and the paper observed no advantage. Put two or more nonlinear layers inside a residual block.
Overall architecture
ResNet is a plain network with a simple, VGG-inspired design, plus shortcuts. In the figure at the head of the article, the left shows the overall flow of ResNet-50 and the right shows the inside of the residual blocks.
An image flows in the following order (for a 224×224 ImageNet image).
A 7×7 convolution (64 channels, stride 2) reduces it to 112×112.
A 1000-class fully connected layer and the softmax function output the class probabilities.
Unlike VGG, there are no large fully connected layers in the middle, so the computation stays low even though the network is deep.
There are two kinds of residual blocks.
Basic block (ResNet-18, 34): stacks two 3×3 convolutions.
Bottleneck block (ResNet-50, 101, 152): stacks three convolutions, 1×1 → 3×3 → 1×1. The first 1×1 reduces the number of channels (256 → 64), the 3×3 is computed on the reduced representation, and the last 1×1 restores it (64 → 256). This adds one more layer at about the same computation as a basic block, which makes it practical to train deep models in a reasonable time.
The number of blocks in each stage and the computation for each depth are as follows (Table 1 of the paper).
Model
Block
conv2_x
conv3_x
conv4_x
conv5_x
FLOPs
ResNet-18
Basic
2
2
2
2
1.8×109
ResNet-34
Basic
3
4
6
3
3.6×109
ResNet-50
Bottleneck
3
4
6
3
3.8×109
ResNet-101
Bottleneck
3
4
23
3
7.6×109
ResNet-152
Bottleneck
3
8
36
3
11.3×109
The number in the name is the number of layers with weights (convolutional and fully connected layers). For example, ResNet-50 has 50 layers: the first convolution, 16 bottleneck blocks × 3 layers, and one fully connected layer. For reference, VGG-16/19 require 15.3 / 19.6×109 FLOPs, more than ResNet-152.
The ImageNet training settings in the paper are as follows.
Randomly resize the shorter side to 256–480 and crop 224×224, horizontal flip, color augmentation
Why it is easier to train
The paper explains why residuals make training easier as follows.
Identity mappings are easy to build: if the optimal function is the identity, a plain network has to build H(x)=x out of many nonlinear layers. A residual block only needs to push its weights toward 0 to get F(x)=0.
It only has to learn "small changes": in practice the optimal function is rarely the identity itself. Still, if it is close to the identity, learning the deviation from the identity should be easier than learning a new function from scratch (the paper likens this to "preconditioning" the optimization problem).
As an everyday analogy, it is like correcting a draft with a red pen instead of rewriting the clean copy from a blank page every time. If there is little to fix, the red pen hardly has to write anything.
As data supporting this explanation, the paper measured the standard deviation of the output of each 3×3 layer (after BN, before ReLU and the addition) on CIFAR-10. The layer outputs of ResNet were generally smaller than those of the plain network, and they were smaller in deeper ResNets. This shows that each layer changes the signal only slightly, that is, the residuals are close to 0.
The shortcuts create a path along which information flows unchanged from the start of the network to the end. Highway Networks, proposed around the same time, also use shortcuts, but with gates (which have parameters) that open and close depending on the data. ResNet's shortcuts never close: the input always passes through unchanged, and the layers only add the difference.
Experimental results
ImageNet: plain vs. ResNet (top-1 error % on the validation set, 10-crop testing; ResNet uses option A and has the same number of parameters as the plain network)
Depth
Plain
ResNet
18 layers
27.94
27.88
34 layers
28.54
25.03
The plain network gets worse at 34 layers than at 18, while ResNet is 2.8 points better at 34 layers. At 18 layers the accuracy is almost the same, but ResNet converged faster in the early stage of training.
ImageNet: shortcut options and depth (validation set, 10-crop testing)
Model
Top-1 error (%)
Top-5 error (%)
VGG-16
28.07
9.33
Plain 34-layer
28.54
10.02
ResNet-34 A
25.03
7.76
ResNet-34 B
24.52
7.46
ResNet-34 C
24.19
7.40
ResNet-50
22.85
6.71
ResNet-101
21.75
6.05
ResNet-152
21.43
5.71
The differences among A, B, and C are small, showing that projection shortcuts are not essential for solving the degradation problem. Meanwhile, increasing the depth from 34 → 50 → 101 → 152 layers kept reducing the error. The single ResNet-152 model had a top-5 error of 4.49%, beating all previous ensemble results.
CIFAR-10 (test error %; small ResNets with 6n+2 layers, all option A)
Model
Layers
Parameters
Error (%)
Highway
19
2.3M
7.54
ResNet
20
0.27M
8.75
ResNet
56
0.85M
6.97
ResNet
110
1.7M
6.43
ResNet
1202
19.4M
7.93
Even with 1202 layers, the training error fell below 0.1%, and no optimization difficulty was observed. However, the test error was worse than with 110 layers, which the paper attributes to overfitting.
Object detection (comparison of swapping the backbone network of Faster R-CNN)
The 6.0-point improvement on COCO corresponds to 28% relative. Since the detection method is the same, the difference comes from the features learned by the network.
Practical notes
Keep the following points in mind when using ResNet.
Tensors cannot be added unless their shapes match: when building blocks yourself, check that F(x) and x have the same number of channels and spatial size. Where they differ, put a 1×1 convolution (and batch normalization) in the shortcut.
Use identity shortcuts by default in bottleneck blocks: the shortcut of a bottleneck block connects the two ends with many channels (such as 256), so making all of them projections roughly doubles the computation and model size (as the paper points out).
Very deep models overfit on small datasets: on CIFAR-10, 1202 layers did worse than 110 layers. The paper did not use strong regularization such as dropout and suggests that combining it might help.
Handle batch normalization carefully in transfer learning: for object detection, the paper froze the BN means and variances learned on ImageNet before fine-tuning. This is because BN statistics are unstable with small batches, as in detection.
In deep models, training may not converge if the learning rate is too large at the start. For the 110-layer model on CIFAR-10 in the paper, a learning rate of 0.1 made it hard to start converging, so it was trained at 0.01 until the training error fell below 80% (about 400 iterations), and then switched back to 0.1. This is the same idea as warmup.
ResNet-50 and similar models in PyTorch's torchvision place the stride 2 that halves the spatial size in a bottleneck block on the 3×3 convolution instead of on the first 1×1 convolution as in the paper (a form called ResNet V1.5). According to the official documentation, this form improves accuracy. Keep this difference in mind when comparing with the numbers in the paper.
Comparison with other models
ResNet became the foundation for many later image models. Comparing them mainly by how they use shortcuts gives the following.
Later layers can reuse the features of earlier layers directly
Building on ResNet's shortcuts, regularization methods have also been proposed, such as Stochastic Depth, which randomly skips blocks during training, and Shake-Shake and ShakeDrop, which mix the shortcut paths. Later models such as MobileNetV2 and ConvNeXt also use residual connections.
Rough guidelines for choosing are as follows.
First thing to try as a backbone for image classification or detection: ResNet-50 is the standard choice, with a good balance of accuracy and computation. Pretrained weights are also widely available.
Limited compute: use ResNet-18 or 34, or a lightweight model such as MobileNet.
Higher accuracy needed: besides ResNet-101 and 152, candidates include ResNeXt, EfficientNet, and ViT.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm
'''
CIFAR-10 image classification. Builds the 6n+2-layer ResNet of Section 4.2 of the paper (ResNet-20 for n=3) following Eqs. (1) and (2)
'''
# Hyperparameters (Section 4.2 of the paper)
batch_size = 128
epochs = 160 # the paper uses 64k iterations (about 164 epochs)
learning_rate = 0.1
n = 3 # number of layers is 6n+2 (20 layers for n=3, 110 layers for n=18)
# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
# Dataset and loaders (pad 4 pixels and crop 32x32, horizontal flip)
mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
test_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=test_transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
# Basic block: 3x3 conv -> BN -> ReLU -> 3x3 conv -> BN -> (add input) -> ReLU
class BasicBlock(nn.Module):
def __init__(self, in_ch, out_ch, stride=1):
super().__init__()
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_ch)
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_ch)
self.relu = nn.ReLU(inplace=True)
# Project with a 1x1 conv only when the shape changes (Eq. (2), option B). Otherwise identity (Eq. (1))
self.shortcut = nn.Identity()
if stride != 1 or in_ch != out_ch:
self.shortcut = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=False),
nn.BatchNorm2d(out_ch),
)
def forward(self, x):
out = self.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out)) # F(x)
out = out + self.shortcut(x) # F(x) + x
return self.relu(out) # the second ReLU comes after the addition
class CifarResNet(nn.Module):
def __init__(self, n=3, num_classes=10):
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1, bias=False), nn.BatchNorm2d(16), nn.ReLU(inplace=True)
)
# 32x32, 16ch -> 16x16, 32ch -> 8x8, 64ch. n blocks per stage (stride 2 at the start of each stage)
layers, in_ch = [], 16
for out_ch, stride in [(16, 1), (32, 2), (64, 2)]:
for i in range(n):
layers.append(BasicBlock(in_ch, out_ch, stride if i == 0 else 1))
in_ch = out_ch
self.layers = nn.Sequential(*layers)
self.pool = nn.AdaptiveAvgPool2d(1) # global average pooling
self.fc = nn.Linear(64, num_classes)
for m in self.modules(): # He initialization
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
def forward(self, x):
x = self.layers(self.stem(x))
return self.fc(torch.flatten(self.pool(x), 1))
# Training and evaluation (SGD, momentum 0.9, weight decay 1e-4; divide the learning rate by 10 partway through)
model = CifarResNet(n=n).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=1e-4)
scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[80, 120], gamma=0.1)
for epoch in tqdm(range(epochs)):
model.train() # BN uses the mini-batch mean and variance
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
loss = criterion(model(images), labels)
loss.backward()
optimizer.step()
scheduler.step()
model.eval() # BN uses the mean and variance accumulated during training
correct = total = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
predicted = model(images).argmax(1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Test Accuracy: {100 * correct / total:.2f}%")
# ResNets for ImageNet are built into torchvision (pretrained weights can also be loaded)
from torchvision.models import resnet50, ResNet50_Weights
imagenet_model = resnet50(weights=ResNet50_Weights.IMAGENET1K_V2) # weights=None gives random weights
imagenet_model.fc = nn.Linear(imagenet_model.fc.in_features, 10) # replace the head for 10-class classification
FAQ
Q. Why is ResNet said to prevent vanishing gradients?
A.
Because the shortcut adds the input directly to the output, it creates a path along which the gradient also skips layers and reaches earlier layers unchanged. However, the original paper treats the degradation problem as an "optimization difficulty" separate from vanishing gradients, and reports that the gradients did not vanish even in the plain networks thanks to BN. The effect of ResNet is often explained by both the ease of gradient flow and the ease of learning functions close to the identity.
Q. What is the difference between ResNet-18/34 and ResNet-50 and deeper?
A.
The shape of the residual block differs. ResNet-18 and 34 use the basic block, which stacks two 3×3 convolutions, while ResNet-50, 101, and 152 use the 1×1 → 3×3 → 1×1 bottleneck block. The bottleneck reduces the number of channels with a 1×1 before computing the 3×3, so the network can be made deeper at about the same computation.
Q. Are residual connections used in models other than image models?
A.
Yes. In the Transformer, the input is added to the output of each attention and feed-forward sublayer. The same holds for MLP-Mixer and others. In models that stack many layers, it has become an almost standard component.