🔎大家好,我是Sonhhxg_柒,希望你看完之后,能对你有所帮助,不足请指正!共同学习交流🔎
📝个人主页-Sonhhxg_柒的博客_CSDN博客 📃
🎁欢迎各位→点赞👍 + 收藏⭐️ + 留言📝
📣系列专栏 - 机器学习【ML】 自然语言处理【NLP】 深度学习【DL】
🖍foreword
✔说明⇢本人讲解主要包括Python、机器学习(ML)、深度学习(DL)、自然语言处理(NLP)等内容。
如果你对这个系列感兴趣的话,可以关注订阅哟👋
1. 扩张卷积
为了简单起见,我仅引用了DilatedNet结构中的公式:
标准卷积(左),扩张卷积(右)
左边是标准卷积。右边是扩张卷积。我们可以看到在求和时,需要满足s+l*t=p,索引我们在卷积操作过程中的会跳过一些点。
当l=1时,上式表示标准卷积。
当l>1时, 上式表示扩张卷积。
标准卷积(l=1)(左),扩张卷积(l=2)(右) 上面的例子说明了l=2时的卷积过程。我们可以看到感知野比标准卷积大。
l=1(左),l=2(中),l=4(右) 上面的图显示了更多不同感知野的例子。
2. 需要扩张卷积的原因
研究结果表明,在网络末端得到的较小输出特征map,降低了语义分割的精度。
在全卷积网络(FCN,https://towardsdatascience.com/review-fcn-semantic-segmentation-eb8c9b50d2d1)中,当需要32倍的上采样时,我们只能得到非常粗略的分割结果。因此,需要更大的输出特征map。
一种简单的方法是删除网络中的下采样(跨步)步骤,以提高特征map的分辨率。然而,这也减少了感知野,从而严重减少了获得的上下文信息。因为更高的分辨率而产生的感知野减少的代价是不值得的。
因此,扩张卷积用于增加后面网络层的感知野,补偿去除下采样而引起的感知野减少。
研究发现,使用扩张卷积也有助于这篇文章中的图像分类任务。
3. 扩张残差网络 (DRN)
本文采用d作为扩张因子。
当d=1时,为标准卷积。
当d>为1时,为扩张卷积。
原始的残差网络(https://towardsdatascience.com/review-resnet-winner-of-ilsvrc-2015-image-classification-localization-detection-e39402bfa5d8)
在原残差网络中,最后两组卷积层G4和G5使用3×3标准卷积(d=1):
由于最大池化层的存在,特征map变得越来越小。
输出特征map的大小只有7×7。这并没有前面提到的那样好。
扩张残差网络(DRN)
在DRN中,在G4层,卷积采用d=2:
在G5层,对于第一次卷积(i=1),仍然采用d=2:
在G5层,对于剩余的卷积(i>1),采用d=4:
最后,DRN中G5层的输出为28×28,远远大于原始的ResNet(https://towardsdatascience.com/review-resnet-winner-of-ilsvrc-2015-image-classification-localization-detection-e39402bfa5d8)。
4. 定位
对于图像分类任务,最后是一个全局平均池化,然后是1×1卷积层和softmax层。要将模型用于定位,只需删除平均池化。不涉及任何训练或参数调优。准确的分类DRN可以直接用于定位。
5. 去网格化
当特征图的频率比扩张卷积的采样率高时,就会出现网格化效应,如上所示。
DRN-A(上),DRN-B(中),DRN-C(下) DRN-A:仅有膨胀卷积的网络,有网格效应。
DRN-B: 研究发现,第一个最大池化操作会导致高幅度高频率的激活值。因此,将第一个最大池化层替换为2个残差块(4个3×3卷积层),以减少网格效应。在网络的末端还添加了2个残差块。
DRN-C: 在网络的末端,扩张率逐渐降低,以消除混叠效应,如先进行2倍膨胀的卷积,再进行1倍膨胀的卷积。然而,混叠效应仍然存在,因为它可以通过残差连接传递。因此,相应的残差连接被删除。
ResNet-18和相应DRNs的激活图
上面展示了一个可视化。
DRN-A-18: 随着卷积的扩张,存在网格效应。
DRN-B-26: 使用卷积代替最大池化,特征map网格效应减少了。
DRN-C-26: 随着扩张卷积的逐步缩小和残差连接的去除,网格效应进一步减小。
DRN-C-26中不同层级的特征map的可视化(显示了每层的最高平均激活值)
6. 结果
6.1. ImageNet图像分类
ImageNet验证集的Top-1和Top-5错误率 DRN-A-18和DRN-A-34的1-crop top-1准确率分别比ResNet-18和ResNet-34高2.43和2.92个百分点。(从ResNet-34到DRN-A-34,相对误差降低了10.5%。)
DRN-A-50在1-crop top-1准确率上超过ResNet-50一个百分点。
将ResNet直接转换为DRN-A,完全不改变模型的深度或容量,但是显著提高了分类精度。 每个DRN-C模型都显著优于相应的DRN-A。
由DRN-A-18衍生而来的DRN-C-26,其精度与较深的DRN-A-34相当。
由DRN-A-34衍生而来的DRN-C-42,其精度与较深的DRN-A-50相当。
DRN-C-42接近ResNet-101的精度,但后者层数是前者的2.4倍。
6.2. ImageNet目标检测
这里基于特征map激活值进行弱监督目标检测。
C=1000,因为ImageNet是一个1000类的ImageNet数据集。
在分辨率为W×H的C响应map中,f(C, W, H)为位置(W, H)的响应,每个位置的最可能的类别为g(W, H),边界框集合为Bi,其中t为激活阈值。bi为在Bi中选择的最小边界框。
与ground-truth的IOU大于0.5的框,被认为是准确的。
ImageNet验证集目标检测Top-1和Top-5错误率
DRN的性能优于相应的ResNet模型,说明了基本DRN结构的优势。DRN-C-26的性能明显优于DRN-A-50,尽管深度要低得多。这表明,去网格化方案对于需要更详细的空间图像分析的应用程序具有特别显著的好处。
DRN-C-26也优于ResNet-101。
深度残差网络Pytorch的实现
-
import torch
-
import torch.nn
as nn
-
import torchvision
-
import torchvision.transforms
as transforms
-
-
-
# 设备配置
-
device
= torch.device(
'cuda'
if torch.cuda.
is_available()
else
'cpu')
-
-
# 超参数
-
num_epochs
=
80
-
batch_
size
=
100
-
learning_rate
=
0.001
-
-
# 图像预处理模块
-
transform
= transforms.Compose([
-
transforms.Pad(
4),
-
transforms.RandomHorizontalFlip(),
-
transforms.RandomCrop(
32),
-
transforms.ToTensor()])
-
-
# CIFAR-
10 数据集
-
train_dataset
= torchvision.datasets.CIFAR
10(root
=
'../../data/',
-
train
=
True,
-
transform
=transform,
-
download
=
True)
-
-
test_dataset
= torchvision.datasets.CIFAR
10(root
=
'../../data/',
-
train
=
False,
-
transform
=transforms.ToTensor())
-
-
# 数据加载器
-
train_loader
= torch.utils.
data.DataLoader(dataset
=train_dataset,
-
batch_
size
=batch_
size,
-
shuffle
=
True)
-
-
test_loader
= torch.utils.
data.DataLoader(dataset
=
test_dataset,
-
batch_
size
=batch_
size,
-
shuffle
=
False)
-
-
#
3x
3 卷积
-
def conv
3x
3(
in_channels, out_channels, stride
=
1):
-
return nn.Conv
2d(
in_channels, out_channels, kernel_
size
=
3,
-
stride
=stride, padding
=
1, bias
=
False)
-
-
# 残差快
-
class ResidualBlock(nn.Module):
-
def __init__(
self,
in_channels, out_channels, stride
=
1, downsample
=None):
-
super(ResidualBlock,
self).__init__()
-
self.conv
1
= conv
3x
3(
in_channels, out_channels, stride)
-
self.bn
1
= nn.BatchNorm
2d(out_channels)
-
self.relu
= nn.ReLU(inplace
=
True)
-
self.conv
2
= conv
3x
3(out_channels, out_channels)
-
self.bn
2
= nn.BatchNorm
2d(out_channels)
-
self.downsample
= downsample
-
-
def forward(
self, x):
-
residual
= x
-
out
=
self.conv
1(x)
-
out
=
self.bn
1(out)
-
out
=
self.relu(out)
-
out
=
self.conv
2(out)
-
out
=
self.bn
2(out)
-
if
self.downsample:
-
residual
=
self.downsample(x)
-
out
+
= residual
-
out
=
self.relu(out)
-
return out
-
-
# ResNet
-
class ResNet(nn.Module):
-
def __init__(
self,
block, layers, num_classes
=
10):
-
super(ResNet,
self).__init__()
-
self.
in_channels
=
16
-
self.conv
= conv
3x
3(
3,
16)
-
self.bn
= nn.BatchNorm
2d(
16)
-
self.relu
= nn.ReLU(inplace
=
True)
-
self.layer
1
=
self.make_layer(
block,
16, layers[
0])
-
self.layer
2
=
self.make_layer(
block,
32, layers[
1],
2)
-
self.layer
3
=
self.make_layer(
block,
64, layers[
2],
2)
-
self.avg_pool
= nn.AvgPool
2d(
8)
-
self.fc
= nn.Linear(
64, num_classes)
-
-
def make_layer(
self,
block, out_channels, blocks, stride
=
1):
-
downsample
= None
-
if (stride !
=
1)
or (
self.
in_channels !
= out_channels):
-
downsample
= nn.
Sequential(
-
conv
3x
3(
self.
in_channels, out_channels, stride
=stride),
-
nn.BatchNorm
2d(out_channels))
-
layers
= []
-
layers.append(
block(
self.
in_channels, out_channels, stride, downsample))
-
self.
in_channels
= out_channels
-
for i
in range(
1, blocks):
-
layers.append(
block(out_channels, out_channels))
-
return nn.
Sequential(
*layers)
-
-
def forward(
self, x):
-
out
=
self.conv(x)
-
out
=
self.bn(out)
-
out
=
self.relu(out)
-
out
=
self.layer
1(out)
-
out
=
self.layer
2(out)
-
out
=
self.layer
3(out)
-
out
=
self.avg_pool(out)
-
out
= out.view(out.
size(
0), -
1)
-
out
=
self.fc(out)
-
return out
-
-
model
= ResNet(ResidualBlock, [
2,
2,
2]).
to(device)
-
-
-
# 损失和优化器
-
criterion
= nn.CrossEntropyLoss()
-
optimizer
= torch.optim.Adam(model.parameters(), lr
=learning_rate)
-
-
# 用于更新学习率
-
def update_lr(optimizer, lr):
-
for param_
group
in optimizer.param_groups:
-
param_
group[
'lr']
= lr
-
-
# 训练模型
-
total_step
= len(train_loader)
-
curr_lr
= learning_rate
-
for epoch
in range(num_epochs):
-
for i, (images, labels)
in enumerate(train_loader):
-
images
= images.
to(device)
-
labels
= labels.
to(device)
-
-
# 前向传播
-
outputs
= model(images)
-
loss
= criterion(outputs, labels)
-
-
# 向后优化
-
optimizer.
zero_grad()
-
loss.backward()
-
optimizer.step()
-
-
if (i
+
1) %
100
=
=
0:
-
print (
"Epoch [{}/{}], Step [{}/{}] Loss: {:.4f}"
-
.
format(epoch
+
1, num_epochs, i
+
1, total_step, loss.item()))
-
-
# 衰减学习率
-
if (epoch
+
1) %
20
=
=
0:
-
curr_lr
/
=
3
-
update_lr(optimizer, curr_lr)
-
-
# 测试模型
-
model.eval()
-
with torch.
no_grad():
-
correct
=
0
-
total
=
0
-
for images, labels
in
test_loader:
-
images
= images.
to(device)
-
labels
= labels.
to(device)
-
outputs
= model(images)
-
_, predicted
= torch.max(outputs.
data,
1)
-
total
+
= labels.
size(
0)
-
correct
+
= (predicted
=
= labels).
sum().item()
-
-
print(
'Accuracy of the model on the test images: {} %'.
format(
100
* correct
/ total))
-
-
# 模型保存
-
torch.save(model.state_dict(),
'resnet.ckpt')