class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channel, out_channel, stride=1, downsample=None, **kwargs): # 虚线对应的 downsample
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
kernel_size=3, stride=stride, padding=1, bias=False) # 有BN层不需要偏置 ,这里的stride需要根据传进来的值对矩阵改变宽高
self.bn1 = nn.BatchNorm2d(out_channel)
self.relu = nn.ReLU()
self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel, # 第一个卷积已经改变宽高
kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channel)
self.downsample = downsample
def forward(self, x):
identity = x # 分支线上的
if self.downsample is not None:
identity = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out) # 先加上捷径分支,再relu激活
out += identity # 加上捷径的再输出
out = self.relu(out)
return out
上面定义了一个两层的卷积层,论文中有用到过。
class Bottleneck(nn.Module):
"""
注意:原论文中,在虚线残差结构的主分支上,第一个1x1卷积层的步距是2,第二个3x3卷积层步距是1。
但在pytorch官方实现过程中是第一个1x1卷积层的步距是1,第二个3x3卷积层步距是2,
这么做的好处是能够在top1上提升大概0.5%的准确率。
可参考Resnet v1.5 https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch
"""
expansion = 4
def __init__(self, in_channel, out_channel, stride=1, downsample=None,
groups=1, width_per_group=64):
super(Bottleneck, self).__init__()
width = int(out_channel * (width_per_group / 64.)) * groups
self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=width, # 这里的out_channel是第一层和第二层的输出矩阵深度
kernel_size=1, stride=1, bias=False) # squeeze channels # 第二层的stride根据传入的来判断
self.bn1 = nn.BatchNorm2d(width)
# -----------------------------------------
self.conv2 = nn.Conv2d(in_channels=width, out_channels=width, groups=groups,
kernel_size=3, stride=stride, bias=False, padding=1) # stride是为了调整矩阵的宽高
self.bn2 = nn.BatchNorm2d(width)
# -----------------------------------------
self.conv3 = nn.Conv2d(in_channels=width, out_channels=out_channel*self.expansion,
kernel_size=1, stride=1, bias=False) # unsqueeze channels
self.bn3 = nn.BatchNorm2d(out_channel*self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
def forward(self, x):
identity = x
if self.downsample is not None:
identity = self.downsample(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
out += identity #先加上再激活
out = self.relu(out)
return out
这个残差块和第一个残差块我觉得唯一的区别就是这个残差块多了一层。
这里提一下一直以来都比较困惑的一个点:虚线残差块有两个作用,一个是改变矩阵深度,如resnet50,101,152的conv_2x的第一层,都是改变输入矩阵的深度,而不改变输入矩阵的宽高。因为输入输出矩阵的宽高是一致的。而且虚线残差块仅出现在每个conv_··x的第一层,因为经过第一层之后,矩阵的深度和宽高都被调整为对应的输出矩阵的宽高,所以后面的都是实线残差结构。这也就是为什么下面的for循环可以直接将剩下的残差块压入。
class ResNet(nn.Module):
def __init__(self,
block, # 根据模型选择bottleneck还是basicmodule
blocks_num,
num_classes=1000,
include_top=True,
groups=1,
width_per_group=64):
super(ResNet, self).__init__()
self.include_top = include_top
self.in_channel = 64
self.groups = groups
self.width_per_group = width_per_group
self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7, stride=2,
padding=3, bias=False) # 设置padding是为了高和宽缩减为原来的一半
self.bn1 = nn.BatchNorm2d(self.in_channel)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) # 设置padding理由同上
self.layer1 = self._make_layer(block, 64, blocks_num[0])
self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
if self.include_top:
self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) # output size = (1, 1) 自适应展平为长宽(1*1)的矩阵
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
def _make_layer(self, block, channel, block_num, stride=1): # channel都是第一层的深度,但是50层和以上都有4倍的最后一层
downsample = None
if stride != 1 or self.in_channel != channel * block.expansion: # 第二个条件是因为resnet50,101,152的conv_2x虽然stride是1(输入输出矩阵同宽高),但是深度不同,所以第一层也得
# 加上虚线残差结构
downsample = nn.Sequential(
nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=1, stride=stride, bias=False), # 对于layer1来说,因为池化过后的长宽和输出的长宽一致,所以也就虚线stride就是1,而对于下面的三层,stride都是2才能改变矩阵的长宽
nn.BatchNorm2d(channel * block.expansion))
layers = []
layers.append(block(self.in_channel,
channel,
downsample=downsample,
stride=stride,
groups=self.groups,
width_per_group=self.width_per_group))
self.in_channel = channel * block.expansion #这里的in_channel是个成员数据,对于每个残差块,输出矩阵深度不一致。对于下面的循环,输入输出矩阵深度应该一致(实线残差结构)。
for _ in range(1, block_num): # 这里剩下的都是实线残差结构了,因此直接加上即可
layers.append(block(self.in_channel,
channel,
groups=self.groups,
width_per_group=self.width_per_group))
return nn.Sequential(*layers)
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)
if self.include_top:
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
给个简单的模型构建传参的例子
def resnet50(num_classes=1000, include_top=True):
# https://download.pytorch.org/models/resnet50-19c8e357.pth
return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)
根据block判断选择几层的残差结构
标签:精读,nn,代码,ResNet,stride,block,self,channel,out From: https://www.cnblogs.com/wl511/p/18170075