如第 14.9 节所述,语义分割在像素级别对图像进行分类。全卷积网络 (fcn) 使用卷积神经网络将图像像素转换为像素类( long et al. , 2015 )。与我们之前在图像分类或目标检测中遇到的 cnn 不同,全卷积网络将中间特征图的高度和宽度转换回输入图像的高度和宽度:这是通过 14.10 节介绍的转置卷积层实现 的. 因此,分类输出和输入图像在像素级别具有一一对应关系:任何输出像素的通道维度都包含相同空间位置的输入像素的分类结果。
%matplotlib inlineimport torchimport torchvisionfrom torch import nnfrom torch.nn import functional as ffrom d2l import torch as d2l
%matplotlib inlinefrom mxnet import gluon, image, init, np, npxfrom mxnet.gluon import nnfrom d2l import mxnet as d2lnpx.set_np()
14.11.1。该模型 在这里,我们描述了全卷积网络模型的基本设计。如图 14.11.1所示,该模型首先使用 cnn 提取图像特征,然后通过1×1卷积层,最后通过 14.10 节介绍的转置卷积将特征图的高度和宽度转换为输入图像的高度和宽度。因此,模型输出与输入图像具有相同的高度和宽度,其中输出通道包含相同空间位置的输入像素的预测类别。
图 14.11.1全卷积网络。
下面,我们使用在 imagenet 数据集上预训练的 resnet-18 模型来提取图像特征并将模型实例表示为 pretrained_net。该模型的最后几层包括全局平均池化层和全连接层:全卷积网络不需要它们。
pretrained_net = torchvision.models.resnet18(pretrained=true)list(pretrained_net.children())[-3:]
[sequential( (0): basicblock( (conv1): conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=false) (bn1): batchnorm2d(512, eps=1e-05, momentum=0.1, affine=true, track_running_stats=true) (relu): relu(inplace=true) (conv2): conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=false) (bn2): batchnorm2d(512, eps=1e-05, momentum=0.1, affine=true, track_running_stats=true) (downsample): sequential( (0): conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=false) (1): batchnorm2d(512, eps=1e-05, momentum=0.1, affine=true, track_running_stats=true) ) ) (1): basicblock( (conv1): conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=false) (bn1): batchnorm2d(512, eps=1e-05, momentum=0.1, affine=true, track_running_stats=true) (relu): relu(inplace=true) (conv2): conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=false) (bn2): batchnorm2d(512, eps=1e-05, momentum=0.1, affine=true, track_running_stats=true) ) ), adaptiveavgpool2d(output_size=(1, 1)), linear(in_features=512, out_features=1000, bias=true)]
pretrained_net = gluon.model_zoo.vision.resnet18_v2(pretrained=true)pretrained_net.features[-3:], pretrained_net.output
(hybridsequential( (0): activation(relu) (1): globalavgpool2d(size=(1, 1), stride=(1, 1), padding=(0, 0), ceil_mode=true, global_pool=true, pool_type=avg, layout=nchw) (2): flatten ), dense(512 -> 1000, linear))
接下来,我们创建全卷积网络实例net。它复制了 resnet-18 中的所有预训练层,除了最终的全局平均池化层和最接近输出的全连接层。
net = nn.sequential(*list(pretrained_net.children())[:-2])
net = nn.hybridsequential()for layer in pretrained_net.features[:-2]: net.add(layer)
给定高度和宽度分别为 320 和 480 的输入,正向传播将net输入高度和宽度减小到原始的 1/32,即 10 和 15。
x = torch.rand(size=(1, 3, 320, 480))net(x).shape
torch.size([1, 512, 10, 15])
x = np.random.uniform(size=(1, 3, 320, 480))net(x).shape
(1, 512, 10, 15)
接下来,我们使用一个1×1卷积层将输出通道的数量转换为 pascal voc2012 数据集的类数 (21)。最后,我们需要将特征图的高度和宽度增加 32 倍,以将它们变回输入图像的高度和宽度。回想一下7.3 节中如何计算卷积层的输出形状。自从 (320−64+16×2+32)/32=10和 (480−64+16×2+32)/32=15,我们构造一个转置卷积层,步幅为32,将内核的高度和宽度设置为64,填充到16. 一般来说,我们可以看到对于 strides, 填充s/2 (假设s/2是一个整数),内核的高和宽2s,转置卷积将使输入的高度和宽度增加s次。
num_classes = 21net.add_module('final_conv', nn.conv2d(512, num_classes, kernel_size=1))net.add_module('transpose_conv', nn.convtranspose2d(num_classes, num_classes, kernel_size=64, padding=16, stride=32))
num_classes = 21net.add(nn.conv2d(num_classes, kernel_size=1), nn.conv2dtranspose( num_classes, kernel_size=64, padding=16, strides=32))
14.11.2。初始化转置卷积层 我们已经知道转置卷积层可以增加特征图的高度和宽度。在图像处理中,我们可能需要对图像进行放大,即上采样。双线性插值是常用的上采样技术之一。它也经常用于初始化转置卷积层。
为了解释双线性插值,假设给定一个输入图像,我们想要计算上采样输出图像的每个像素。为了计算输出图像在坐标处的像素(x,y), 第一张地图(x,y)协调(x′,y′)在输入图像上,例如,根据输入大小与输出大小的比率。请注意,映射x′和y′是实数。然后,找到最接近坐标的四个像素 (x′,y′)在输入图像上。最后,输出图像在坐标处的像素(x,y)是根据输入图像上这四个最接近的像素及其与 (x′,y′).
双线性插值的上采样可以通过转置卷积层实现,内核由以下bilinear_kernel函数构造。限于篇幅,bilinear_kernel下面只给出功能的实现,不讨论其算法设计。
def bilinear_kernel(in_channels, out_channels, kernel_size): factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = (torch.arange(kernel_size).reshape(-1, 1), torch.arange(kernel_size).reshape(1, -1)) filt = (1 - torch.abs(og[0] - center) / factor) * (1 - torch.abs(og[1] - center) / factor) weight = torch.zeros((in_channels, out_channels, kernel_size, kernel_size)) weight[range(in_channels), range(out_channels), :, :] = filt return weight
def bilinear_kernel(in_channels, out_channels, kernel_size): factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = (np.arange(kernel_size).reshape(-1, 1), np.arange(kernel_size).reshape(1, -1)) filt = (1 - np.abs(og[0] - center) / factor) * (1 - np.abs(og[1] - center) / factor) weight = np.zeros((in_channels, out_channels, kernel_size, kernel_size)) weight[range(in_channels), range(out_channels), :, :] = filt return np.array(weight)
让我们试验一下由转置卷积层实现的双线性插值的上采样。我们构建了一个将高度和重量加倍的转置卷积层,并使用该bilinear_kernel函数初始化其内核。
conv_trans = nn.convtranspose2d(3, 3, kernel_size=4, padding=1, stride=2, bias=false)conv_trans.weight.data.copy_(bilinear_kernel(3, 3, 4));
conv_trans = nn.conv2dtranspose(3, kernel_size=4, padding=1, strides=2)conv_trans.initialize(init.constant(bilinear_kernel(3, 3, 4)))
读取图像x并将上采样输出分配给y。为了打印图像,我们需要调整通道维度的位置。
img = torchvision.transforms.totensor()(d2l.image.open('../img/catdog.jpg'))x = img.unsqueeze(0)y = conv_trans(x)out_img = y[0].permute(1, 2, 0).detach()
img = image.imread('../img/catdog.jpg')x = np.expand_dims(img.astype('float32').transpose(2, 0, 1), axis=0) / 255y = conv_trans(x)out_img = y[0].transpose(1, 2, 0)
正如我们所见,转置卷积层将图像的高度和宽度增加了两倍。双线性插值放大后的图像与14.3节打印的原始图像除了坐标比例不同外, 看起来是一样的。
d2l.set_figsize()print('input image shape:', img.permute(1, 2, 0).shape)d2l.plt.imshow(img.permute(1, 2, 0));print('output image shape:', out_img.shape)d2l.plt.imshow(out_img);
input image shape: torch.size([561, 728, 3])output image shape: torch.size([1122, 1456, 3])
d2l.set_figsize()print('input image shape:', img.shape)d2l.plt.imshow(img.asnumpy());print('output image shape:', out_img.shape)d2l.plt.imshow(out_img.asnumpy());
input image shape: (561, 728, 3)output image shape: (1122, 1456, 3)
在全卷积网络中,我们使用双线性插值的上采样来初始化转置卷积层。为了 1×1卷积层,我们使用 xavier 初始化。
w = bilinear_kernel(num_classes, num_classes, 64)net.transpose_conv.weight.data.copy_(w);
w = bilinear_kernel(num_classes, num_classes, 64)net[-1].initialize(init.constant(w))net[-2].initialize(init=init.xavier())
14.11.3。读取数据集 我们阅读了第 14.9 节中介绍的语义分割数据集 。随机裁剪的输出图像形状指定为320×480:高度和宽度都可以被整除32.
batch_size, crop_size = 32, (320, 480)train_iter, test_iter = d2l.load_data_voc(batch_size, crop_size)
read 1114 examplesread 1078 examples
batch_size, crop_size = 32, (320, 480)train_iter, test_iter = d2l.load_data_voc(batch_size, crop_size)
downloading ../data/voctrainval_11-may-2012.tar from http://d2l-data.s3-accelerate.amazonaws.com/voctrainval_11-may-2012.tar...read 1114 examplesread 1078 examples
14.11.4。训练 现在我们可以训练我们构建的全卷积网络了。这里的损失函数和精度计算与前面章节的图像分类没有本质区别。因为我们使用转置卷积层的输出通道来预测每个像素的类别,所以在损失计算中指定了通道维度。此外,准确度是根据所有像素的预测类别的正确性计算的。
def loss(inputs, targets): return f.cross_entropy(inputs, targets, reduction='none').mean(1).mean(1)num_epochs, lr, wd, devices = 5, 0.001, 1e-3, d2l.try_all_gpus()trainer = torch.optim.sgd(net.parameters(), lr=lr, weight_decay=wd)d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
loss 0.441, train acc 0.863, test acc 0.853167.9 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]
num_epochs, lr, wd, devices = 5, 0.1, 1e-3, d2l.try_all_gpus()loss = gluon.loss.softmaxcrossentropyloss(axis=1)net.collect_params().reset_ctx(devices)trainer = gluon.trainer(net.collect_params(), 'sgd', {'learning_rate': lr, 'wd': wd})d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
loss 0.320, train acc 0.894, test acc 0.848144.9 examples/sec on [gpu(0), gpu(1)]
14.11.5。预言 在进行预测时,我们需要对每个通道的输入图像进行标准化处理,将图像转化为cnn需要的四维输入格式。
def predict(img): x = test_iter.dataset.normalize_image(img).unsqueeze(0) pred = net(x.to(devices[0])).argmax(dim=1) return pred.reshape(pred.shape[1], pred.shape[2])
def predict(img): x = test_iter._dataset.normalize_image(img) x = np.expand_dims(x.transpose(2, 0, 1), axis=0) pred = net(x.as_in_ctx(devices[0])).argmax(axis=1) return pred.reshape(pred.shape[1], pred.shape[2])
为了可视化每个像素的预测类别,我们将预测类别映射回其在数据集中的标签颜色。
def label2image(pred): colormap = torch.tensor(d2l.voc_colormap, device=devices[0]) x = pred.long() return colormap[x, :]
def label2image(pred): colormap = np.array(d2l.voc_colormap, ctx=devices[0], dtype='uint8') x = pred.astype('int32') return colormap[x, :]
测试数据集中的图像大小和形状各不相同。由于该模型使用了步长为32的转置卷积层,当输入图像的高度或宽度不能被32整除时,转置卷积层的输出高度或宽度会偏离输入图像的形状。为了解决这个问题,我们可以在图像中裁剪出多个高宽均为32整数倍的矩形区域,分别对这些区域的像素进行前向传播。请注意,这些矩形区域的并集需要完全覆盖输入图像。当一个像素被多个矩形区域覆盖时,可以将同一像素在不同区域的转置卷积输出的平均值输入到 softmax 操作中以预测类别。
为简单起见,我们只读取了一些较大的测试图像,并裁剪了一个 320×480从图像的左上角开始的预测区域。对于这些测试图像,我们逐行打印它们的裁剪区域、预测结果和地面实况。
voc_dir = d2l.download_extract('voc2012', 'vocdevkit/voc2012')test_images, test_labels = d2l.read_voc_images(voc_dir, false)n, imgs = 4, []for i in range(n): crop_rect = (0, 0, 320, 480) x = torchvision.transforms.functional.crop(test_images[i], *crop_rect) pred = label2image(predict(x)) imgs += [x.permute(1,2,0), pred.cpu(), torchvision.transforms.functional.crop( test_labels[i], *crop_rect).permute(1,2,0)]d2l.show_images(imgs[::3] + imgs[1::3] + imgs[2::3], 3, n, scale=2);
voc_dir = d2l.download_extract('voc2012', 'vocdevkit/voc2012')test_images, test_labels = d2l.read_voc_images(voc_dir, false)n, imgs = 4, []for i in range(n): crop_rect = (0, 0, 480, 320) x = image.fixed_crop(test_images[i], *crop_rect) pred = label2image(predict(x)) imgs += [x, pred, image.fixed_crop(test_labels[i], *crop_rect)]d2l.show_images(imgs[::3] + imgs[1::3] + imgs[2::3], 3, n, scale=2);
14.11.6. 概括 全卷积网络首先使用 cnn 提取图像特征,然后通过1×1卷积层,最后通过转置卷积将特征图的高度和宽度转换为输入图像的高度和宽度。
在全卷积网络中,我们可以使用双线性插值的上采样来初始化转置卷积层。
14.11.7. 练习 如果我们在实验中对转置的卷积层使用xavier初始化,结果会有怎样的变化?
你能否通过调整超参数进一步提高模型的准确性?
预测测试图像中所有像素的类别。
最初的全卷积网络论文也使用了一些中间 cnn 层的输出(long et al. , 2015)。尝试实现这个想法。
电瓶修复——把蓄电池比喻成人之后
楼宇自控系统在建筑节能中的关键作用
中国自主FPGA知识产权厂商向国外三大顶尖厂商宣战
航天科技九院研制出飞鸿98大型无人运输机
小米·造梦者战略合作 新风系统将走入千家万户
PyTorch教程-14.11. 全卷积网络
联想zuk edge正式发布:颜值不输小米MIX,配置堪比华为mate9!
锂离子电池聚合物电解质导电机理
应用无处不在,发觉你身边的MEMS传感器
水下机器人如何构建精确的地图
Snapdragon 875及其为下一代智能手机带来的全部功能的所有信息
小鸟音响TRACKAir+真无线降噪耳机评测 值不值得买
人形机器人电机分类(无框电机是人形关节传动主力)
UPF 3.0全新电源设计标准面世
为什么说iphone7在中国卖不出去了,我们应该感到悲哀!
了解PCB布局技巧
【泵类维修】脱硫浆液循环泵防腐耐磨保护方案分享
美国空军大力部署5G网络
工控机的特点
Origin Q一周速览:希腊设立量子计算理学硕士学位