我们知道,网络越深,咱们能获取的信息越多,而且特征也越丰富。但是根据实验表明,随着网络的加深,优化效果反而越差,测试数据和训练数据的准确率反而降低了。这是由于网络的加深会造成梯度爆炸和梯度消失的问题。
针对梯度爆炸和梯度消失的问题,我们通常会对输入数据和中间层的数据进行归一化操作(nn.BatchNorm2d()),从而让网络收敛,但是这个方法只会对几十层的网络有用,当网络层数越来越深,这一方法的效果会越来越差。因此这个时候引入了残差网络(ResNet)来有效的解决这一问题。
ResNet的block有俩种,分别是BasicBlock和Bottleneck,它们的结构如下图所示:
代码如下 :
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = 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)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
首先conv3×3是一个输入维度in_planes,输出维度为out_planes,卷积核3×3,步长为1的卷积层。定义该函数是为了简化代码的书写,以免多次调用nn.Conv2d()函数。
BasicBlock函数:
如图所示,输入通道inplanes,调用conv3×3(即由3×3大小的卷积核卷积一次),随即归一化后通过ReLU函数激活,此时输出通道数为planes,作为下一个3×3卷积层的输入通道数,且输出的通道数仍然为planes。之后判断是否需要下采样操作,如果不需要则将第二个3×3卷积层的输出与最初的输入数据相加并由ReLU函数激活。
Bottleneck函数:
如图所示,init()函数是预定义网络架构,forward函数是进行前向传播。该block中有三个卷积,分别是1x1,3x3,1x1,分别完成的功能就是维度压缩,卷积,恢复维度。故bottleneck实现的功能就是对通道数进行压缩,再放大。注意:这里的plane不再是输出的通道数,输出通道数应该就是plane*expansion,即4*plane。
ResNet函数:
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AdaptiveAvgPool2d((1,1))
#self.avgpool = nn.AdaptativeAvgPool((1,1), stride=1)
self.fc1 = nn.Linear(512 * block.expansion, 1000)
self.fc2 = nn.Linear(1000, 3)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
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)
feat_D = self.layer2(x)
x = self.layer3(feat_D)
x = self.layer4(x)
#print('Size at output',x.size())
x = self.avgpool(x)
x = x.view(x.size(0), -1)
#x = nn.Dropout()(x)
x = nn.ReLU()(self.fc1(x))
x = self.fc2(x)
return x
首先我们需要清楚该函数传递的各个参数所代表的意思。
block:即上方所定义的bottleneck或basicblock。
layers:是一个数组,一般情况下由四个整数组成,表示该残差网络四个layer中每个layer包含多少个block。
num_classes:问题类别数。
resnet一共有5个阶段,第一阶段是一个7x7的卷积,stride=2,然后再经过池化层,得到的特征图大小变为原图的1/4。_make_layer()函数用来产生4个layer,可以根据输入的layers列表来创建网络。
这三个函数讲清楚后,后面的网络主体架构就很好理解,5种架构之间的不同在于使用的基础块是basicblock和bottlenek之间的不同以及每个layer里的堆叠的block参数的不同。因为ResNet一般有4个layer,每一个layer里面都是block的堆叠,所以以ResNet34举例,传入的[3, 4, 6, 3]就是每一个stack里面堆叠block的个数,故而造就了不同深度的ResNet。
downsample模块含义
在ResNet网络中有一个显眼的操作就是降采样操作,我们将ResNet函数中的相关部分抽出来看:
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
从代码中我们可以看到当步长不为1、输入维度不等于输出维度*4(expansion)时,表明需要建立一个 1 X 1 的卷积层,来改变通道数和改变图片大小。在resnet函数中的四层layer中只有第一层的stride为1,其余都为2。
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
因为当stride=2时会改变输出的shape,为了保证相加操作正常进行,所以使用 1 X 1 的卷积改变大小和通道。