文章目录
- 代码实现
- 参考
代码实现
本文实现 ResNet原论文 Deep Residual Learning for Image Recognition 中的50层,101层和152层残差连接。
代码中使用基础残差块这个概念,这里的基础残差块指的是上图中红色矩形圈出的内容:从上到下分别使用3, 4, 6, 3个基础残差块,每个基础残差块由三个卷积层组成,核大小分别为1x1, 3x3, 1x1 。
残差连接的结构
复现代码如下:
import torch
import torch.nn as nn
# 基础残差块,后面ResNet要多次重复使用该块
class block(nn.Module):
def __init__(self, in_channels, out_channels, identity_downsample=None, stride=1):
super(block, self).__init__()
self.expansion = 4
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1)
self.bn2 = nn.BatchNorm2d(out_channels)
self.conv3 = nn.Conv2d(out_channels, out_channels*self.expansion, kernel_size=1, stride=1, padding=0)
self.bn3 = nn.BatchNorm2d(out_channels*self.expansion)
self.relu = nn.ReLU()
self.identity_downsample = identity_downsample
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.identity_downsample is not None:
identity = self.identity_downsample(identity)
x += identity
x = self.relu(x)
return x
class ResNet(nn.Module):
def __init__(self, block, layers, image_channels, num_classes):
super(ResNet, self).__init__()
# 初始化的层
self.in_channels = 64
self.conv1 = nn.Conv2d(image_channels, 64, kernel_size=7, stride=2, padding=3)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
# ResNet layers
self.layer1 = self._make_layer(block, layers[0], out_channels=64, stride=1)
self.layer2 = self._make_layer(block, layers[1], out_channels=128, stride=2)
self.layer3 = self._make_layer(block, layers[2], out_channels=256, stride=2)
self.layer4 = self._make_layer(block, layers[3], out_channels=512, stride=2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512*4, num_classes)
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)
x = self.avgpool(x)
x = x.reshape(x.shape[0], -1)
x = self.fc(x)
return x
# 核心函数:调用block基础残差块,构造ResNet的每一层
def _make_layer(self, block, num_residual_blocks, out_channels, stride):
identity_downsample = None
layers = []
if stride != 1 or self.in_channels != out_channels * 4:
identity_downsample = nn.Sequential(nn.Conv2d(self.in_channels, out_channels*4, kernel_size=1,
stride=stride),
nn.BatchNorm2d(out_channels*4))
layers.append(block(self.in_channels, out_channels, identity_downsample, stride))
self.in_channels = out_channels * 4
for i in range(num_residual_blocks - 1):
layers.append(block(self.in_channels, out_channels)) # 256 -> 64, 64*4(256) again
return nn.Sequential(*layers)
# 构造ResNet50层:默认图像通道3,分类类别为1000
def resnet50(img_channels=3, num_classes=1000):
return ResNet(block, [3, 4, 6, 3], img_channels, num_classes)
# 构造ResNet101层
def resnet101(img_channels=3, num_classes=1000):
return ResNet(block, [3, 4, 23, 3], img_channels, num_classes)
# 构造ResNet152层
def resnet152(img_channels=3, num_classes=1000):
return ResNet(block, [3, 8, 36, 3], img_channels, num_classes)
# 测试输出y的形状是否满足1000类
def test():
net = resnet152()
x = torch.randn(2, 3, 224, 224)
y = net(x)
print(y.shape) # [2, 1000]
test()
参考
[1] Deep Residual Learning for Image Recognition
[2] https://www.youtube.com/watch?v=DkNIBBBvcPs&list=PLhhyoLH6IjfxeoooqP9rhU3HJIAVAJ3Vz&index=19