ResNet 通过建立短路连接，实现了一般神经网络难以模拟的恒等映射，其常用的具体架构一般有 resnet18，resnet34，resnet50，resnet101 和 resnet152 这五种，本文将从代码层面详细分析如何搭建这些结构。

class ResNet(nn.Module):
def __init__(self):
self.conv1 = nn.Conv2d()
self.bn1 = nn.BatchNorm2d()
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d()
self.layer1 = res_layer()
self.layer2 = res_layer()
self.layer3 = res_layer()
self.layer4 = res_layer()
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)

x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)

return x

layer1 layer2 layer3 layer4
resnet18 2 2 2 2
resnet34 3 4 6 3
resnet50 3 4 6 3
resnet101 3 4 23 3
resnet152 3 8 36 3

class BasicBlock(nn.Module):
def __init__(self, in_channels, out_channels):
self.conv1 = conv3x3(in_channels, out_channels)
self.bn1 = nn.BatchNorm2d()
self.relu = nn.ReLU()
self.conv2 = conv3x3(out_channels, out_channels)
self.bn2 = nn.BatchNorm2d()
if in_channels == out_channels:
self.shortcut=nn.Sequential(
nn.Conv2d(out_channels, out_channels),
nn.BatchNorm2d()
)

def forward(self, x):
identity = x
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
if self.shortcut:
identity = self.shortcut(identity)

x = x + identity
x = self.relu(x)
return x

bottleneck block 的实现也大同小异， 只不过需要注意最后一层的通道扩展

class Bottleneck(nn.Module):
expansion = 4 ## 最后一层的输出通道扩展倍数
def __init__(self, in_channels, out_channels):
self.conv1 = conv1x1(in_channels, out_channels)
self.bn1 = nn.BatchNorm2d()
self.conv2 = conv3x3(out_channels, out_channels)
self.bn2 = nn.BatchNorm2d()
self.conv3 = conv1x1(out_channels, out_channels * self.expansion)
self.bn3 = nn.BatchNorm2d()
self.relu = nn.ReLU()
if in_channels != out_channenls * self.expansion
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels * self.expansion),
nn.BatchNorm2d(out_channels * self.expansion)
)
def forward(self, x):
identity = x
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)

x = self.conv3(x)
x = self.bn3(x)
if self.shortcut:
identity = self.shortcut(x)

x = x + identity
x = self.relu(x)
return x

def res_layer(in_channel, out_channel, num_layers):
layers = []
for _ in range(num_layers):
layer=BasicBlock(in_channel, out_channel)
layers.append(block)
in_channel = out_channel
return nn.Sequential(*layers)

layer1 = res_layer(64, 64, 2)
layer2 = res_layer(64, 128, 2)

def res_layer(in_channel, out_channel, num_layers):
layers = []
for _ in range(num_layers):
layer = Bottleneck(in_channel, out_channel)
layers.append(layer)
in_channel = 4 * out_channel
return nn.Sequential(*layers)
layers1 = res_layer(64, 64, 3)
in_channel = 64 * 4
layers2 = res_layer(in_channel, 128, 4)

def res_layer(block, in_channel, out_channel, num_layers):
layers = []
for _ in range(len(num_layers)):
layer = block(in_channel, out_channel)
layers.append(layer)
in_channel = block.expansion * out_channel
return nn.Sequential(*layers)

1. in_channel 从 64 开始；

1. 每个 layer 的第一个 block 的 out_channel 依次为 64，128，256，512；

1. 后层 in_channel 等于前层 out_channel。

1. 第一个卷积层使图片尺寸减半；

1. 第一个池化层使图片尺寸减半；

1. 对于 res_layer，如果输入输出通道一样，则不改变特征图尺寸，否则特征图尺寸减半。

[ M = \frac {N + 2 p – k}{s} + 1 ]

class BasicBlock(torch.nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(BasicBlock, self).__init__()
self.conv1=torch.nn.Conv2d(in_channels, out_channels, kernel_size =3, stride=stride, padding=1)
self.bn1=torch.nn.BatchNorm2d(out_channels)
self.relu=torch.nn.ReLU()
self.bn2=torch.nn.BatchNorm2d(out_channels)

if in_channels != out_channels:
self.shortcut = torch.nn.Sequential(
torch.nn.BatchNorm2d(out_channels)
)
else:
self.shortcut = None

class Bottleneck(torch.nn.Module):
expansion = 4
def __init__(self, in_channels, out_channels, stride):
super(Bottleneck, self).__init__()
self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size = 1, stride=1)
self.bn1 = torch.nn.BatchNorm2d(out_channels)
self.conv2 = torch.nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1)
self.bn2 = torch.nn.BatchNorm2d(out_channels)
self.conv3 = torch.nn.Conv2d(out_channels, out_channels * self.expansion, kernel_size=1, stride=1)
self.bn3 = torch.nn.BatchNorm2d(out_channels * self.expansion)
self.relu = torch.nn.ReLU()
if in_channels != out_channels * self.expansion:
self.shortcut = torch.nn.Sequential(
torch.nn.Conv2d(in_channels, out_channels * self.expansion, kernel_size=1, stride=stride),
torch.nn.BatchNorm2(out_channels * self.expansion)
)
else:
self.shortcut = None

BasicBlock 和 Bottleneck 的完整定义后，我们就可以完成 res_layer 的编写了。res_layer 由多个 Block 组成，我们使用第一个 Block 来实现特征图尺寸的变化，因此后续 Block 的 stride 均为 1。之所以将 stride 作为参数传入，是因为是否让第一个 block 将特征图尺寸减半由上层代码来确定

def res_layer(block, in_channels, out_channels, num_layer, stride):
layers = []
layers.append(
block(in_channels, out_channels, stride=stride)
)
in_channels = out_channels * block.expansion
for _ in range(1, len(num_layer)):
layer = block(in_channels, out_channels, stride=1)
layers.append(layer)
in_channels = block.expansion * out_channels
return nn.Sequential(*layers)

class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = torch.nn.BatchNorm2d(64)
self.relu = torch.nn.ReLU()
self.layer1=res_layer(BasicBlock, 64, 64, num_layer=2, stride=1) ## 第一个 block 不改变特征图尺寸
self.layer2=res_layer(BasicBlock, 64, 128, num_layer=2, stride=2)
self.layer3=res_layer(BasicBlock, 128, 256, num_layer=2, stride=2)
self.layer4=res_layer(BasicBlock, 256, 512, num_layer=2, stride=2)
class ResNet50(nn.Module):
def __init__(self):
super(ResNet50, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = torch.nn.BatchNorm2d(64)
self.relu = torch.nn.ReLU()
self.layer1=res_layer(Bottleneck, 64, 64, num_layer=2, stride=1) ## 第一个 block 不改变特征图尺寸
self.layer2=res_layer(Bottleneck, 64 * 4, 128, num_layer=2, stride=2)
self.layer3=res_layer(Bottleneck, 128 * 4, 256, num_layer=2, stride=2)
self.layer4=res_layer(Bottleneck, 256 * 4, 512, num_layer=2, stride=2)

class ResNet(nn.Module):
def __init__(self, block, num_layers):
super(ResNet, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = torch.nn.BatchNorm2d(64)
self.relu = torch.nn.ReLU()
self.layer1=self._make_layer(block, 64, 64, num_layers[0], 1)
self.layer2=self._make_layer(block, 64 * block.expansion, 128, num_layers[1], 2)
self.layer3=self._make_layer(block, 128 * block.expansion, 256, num_layers[2], 2)
self.layer4=self._make_layer(block, 256 * block.expansion, 512, num_layers[3], 2)

def resnet18():
return ResNet(BasicBlock, [2,2,2,2])
def resnet34():
return ResNet(BasicBlock, [3, 4, 6, 3])
def resnet50():
return ResNet(Bottleneck, [3, 4, 6, 3])
def resnet101():
return ResNet(Bottleneck, [3, 4, 23, 3])
def resnet152():
return ResNet(Bottleneck, [3, 8, 36, 3])