14.7. 单发多框检测¶ 在 SageMaker Studio Lab 中打开 Notebook
在 第 14.3 节–第 14.6 节中,我们介绍了边界框、锚框、多尺度目标检测和目标检测数据集。现在我们已经准备好利用这些背景知识来设计一个目标检测模型:单发多框检测(SSD) (Liu et al., 2016)。这个模型简单、快速且被广泛使用。尽管这只是众多目标检测模型中的一个,但本节中的一些设计原则和实现细节也适用于其他模型。
14.7.1. 模型¶
图 14.7.1 概述了单发多框检测的设计。该模型主要由一个基础网络和几个多尺度特征图块组成。基础网络用于从输入图像中提取特征,因此可以使用一个深度卷积神经网络。例如,最初的单发多框检测论文采用了在分类层之前截断的VGG网络 (Liu et al., 2016),而ResNet也已普遍使用。通过我们的设计,我们可以使基础网络输出更大的特征图,以便生成更多的锚框来检测较小的物体。随后,每个多尺度特征图块将前一个块的特征图的高度和宽度减小(例如,减半),并使特征图的每个单元在输入图像上增加其感受野。
回顾一下在 第 14.5 节 中通过深度神经网络对图像进行分层表示来实现多尺度目标检测的设计。由于 图 14.7.1 中越靠近顶部的多尺度特征图越小,但具有更大的感受野,因此它们适合于检测更少但更大的物体。
简而言之,通过其基础网络和几个多尺度特征图块,单发多框检测会生成不同数量、不同大小的锚框,并通过预测这些锚框的类别和偏移量(从而得到边界框)来检测不同大小的物体;因此,这是一个多尺度目标检测模型。
图 14.7.1 作为一个多尺度目标检测模型,单发多框检测主要由一个基础网络和随后的几个多尺度特征图块组成。¶
接下来,我们将描述 图 14.7.1 中不同模块的实现细节。首先,我们讨论如何实现类别和边界框的预测。
14.7.1.1. 类别预测层¶
设物体类别的数量为 \(q\)。那么锚框有 \(q+1\) 个类别,其中类别0是背景。在某个尺度上,假设特征图的高度和宽度分别为 \(h\) 和 \(w\)。当以这些特征图的每个空间位置为中心生成 \(a\) 个锚框时,总共需要对 \(hwa\) 个锚框进行分类。由于可能带来巨大的参数开销,这通常使得使用全连接层进行分类变得不可行。回想一下我们在 第 8.3 节 中如何使用卷积层的通道来预测类别。单发多框检测使用相同的技术来降低模型复杂度。
具体来说,类别预测层使用一个卷积层,而不改变特征图的宽度或高度。这样,在特征图的相同空间维度(宽度和高度)上,输出和输入之间可以存在一一对应的关系。更具体地说,在任何空间位置(\(x\), \(y\))上,输出特征图的通道代表了以输入特征图的(\(x\), \(y\))为中心的所有锚框的类别预测。为了产生有效的预测,必须有 \(a(q+1)\) 个输出通道,其中对于相同的空间位置,索引为 \(i(q+1) + j\) 的输出通道代表了对锚框 \(i\) (\(0 \leq i < a\)) 的类别 \(j\) (\(0 \leq j \leq q\)) 的预测。
下面我们定义这样一个类别预测层,通过参数 num_anchors
和 num_classes
分别指定 \(a\) 和 \(q\)。该层使用一个填充为1的 \(3\times3\) 卷积层。这个卷积层的输入和输出的宽度和高度保持不变。
%matplotlib inline
import torch
import torchvision
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
def cls_predictor(num_inputs, num_anchors, num_classes):
return nn.Conv2d(num_inputs, num_anchors * (num_classes + 1),
kernel_size=3, padding=1)
%matplotlib inline
from mxnet import autograd, gluon, image, init, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
def cls_predictor(num_anchors, num_classes):
return nn.Conv2D(num_anchors * (num_classes + 1), kernel_size=3,
padding=1)
14.7.1.2. 边界框预测层¶
边界框预测层的设计与类别预测层类似。唯一的区别在于每个锚框的输出数量:这里我们需要预测四个偏移量,而不是 \(q+1\) 个类别。
def bbox_predictor(num_inputs, num_anchors):
return nn.Conv2d(num_inputs, num_anchors * 4, kernel_size=3, padding=1)
def bbox_predictor(num_anchors):
return nn.Conv2D(num_anchors * 4, kernel_size=3, padding=1)
14.7.1.3. 连接多尺度预测¶
正如我们所提到的,单发多框检测使用多尺度特征图来生成锚框并预测它们的类别和偏移量。在不同的尺度上,特征图的形状或以同一单元为中心的锚框数量可能会有所不同。因此,不同尺度下的预测输出的形状可能会不同。
在下面的例子中,我们为同一个小批量构建了两个不同尺度的特征图 Y1
和 Y2
,其中 Y2
的高度和宽度是 Y1
的一半。以类别预测为例。假设在 Y1
和 Y2
的每个单元上分别生成了5个和3个锚框。再假设物体类别的数量是10。对于特征图 Y1
和 Y2
,类别预测输出中的通道数分别为 \(5\times(10+1)=55\) 和 \(3\times(10+1)=33\),其中任一输出的形状都是(批量大小,通道数,高度,宽度)。
def forward(x, block):
return block(x)
Y1 = forward(torch.zeros((2, 8, 20, 20)), cls_predictor(8, 5, 10))
Y2 = forward(torch.zeros((2, 16, 10, 10)), cls_predictor(16, 3, 10))
Y1.shape, Y2.shape
(torch.Size([2, 55, 20, 20]), torch.Size([2, 33, 10, 10]))
def forward(x, block):
block.initialize()
return block(x)
Y1 = forward(np.zeros((2, 8, 20, 20)), cls_predictor(5, 10))
Y2 = forward(np.zeros((2, 16, 10, 10)), cls_predictor(3, 10))
Y1.shape, Y2.shape
[22:46:32] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU
((2, 55, 20, 20), (2, 33, 10, 10))
正如我们所见,除了批量大小维度外,其他三个维度的大小都不同。为了将这两个预测输出连接起来以进行更高效的计算,我们将把这些张量转换成更一致的格式。
请注意,通道维度保存着具有相同中心的锚框的预测。我们首先将这个维度移动到最内层。由于不同尺度的批量大小保持不变,我们可以将预测输出转换成一个形状为(批量大小,高 \(\times\) 宽 \(\times\) 通道数)的二维张量。然后我们可以在维度1上连接不同尺度的这些输出。
def flatten_pred(pred):
return torch.flatten(pred.permute(0, 2, 3, 1), start_dim=1)
def concat_preds(preds):
return torch.cat([flatten_pred(p) for p in preds], dim=1)
def flatten_pred(pred):
return npx.batch_flatten(pred.transpose(0, 2, 3, 1))
def concat_preds(preds):
return np.concatenate([flatten_pred(p) for p in preds], axis=1)
通过这种方式,即使 Y1
和 Y2
在通道、高度和宽度上有不同的尺寸,我们仍然可以为同一个小批量在两个不同尺度上连接这两个预测输出。
concat_preds([Y1, Y2]).shape
torch.Size([2, 25300])
concat_preds([Y1, Y2]).shape
(2, 25300)
14.7.1.4. 下采样块¶
为了在多个尺度上检测物体,我们定义了以下下采样块 down_sample_blk
,它将输入特征图的高度和宽度减半。实际上,这个块应用了 第 8.2.1 节 中VGG块的设计。更具体地说,每个下采样块由两个填充为1的 \(3\times3\) 卷积层,后跟一个步幅为2的 \(2\times2\) 最大池化层组成。正如我们所知,填充为1的 \(3\times3\) 卷积层不改变特征图的形状。然而,随后的 \(2\times2\) 最大池化将输入特征图的高度和宽度减半。对于这个下采样块的输入和输出特征图,由于 \(1\times 2+(3-1)+(3-1)=6\),输出中的每个单元在输入上都有一个 \(6\times6\) 的感受野。因此,下采样块扩大了其输出特征图中每个单元的感受野。
def down_sample_blk(in_channels, out_channels):
blk = []
for _ in range(2):
blk.append(nn.Conv2d(in_channels, out_channels,
kernel_size=3, padding=1))
blk.append(nn.BatchNorm2d(out_channels))
blk.append(nn.ReLU())
in_channels = out_channels
blk.append(nn.MaxPool2d(2))
return nn.Sequential(*blk)
def down_sample_blk(num_channels):
blk = nn.Sequential()
for _ in range(2):
blk.add(nn.Conv2D(num_channels, kernel_size=3, padding=1),
nn.BatchNorm(in_channels=num_channels),
nn.Activation('relu'))
blk.add(nn.MaxPool2D(2))
return blk
在下面的例子中,我们构建的下采样块改变了输入通道的数量,并将输入特征图的高度和宽度减半。
forward(torch.zeros((2, 3, 20, 20)), down_sample_blk(3, 10)).shape
torch.Size([2, 10, 10, 10])
forward(np.zeros((2, 3, 20, 20)), down_sample_blk(10)).shape
(2, 10, 10, 10)
14.7.1.5. 基础网络块¶
基础网络块用于从输入图像中提取特征。为简单起见,我们构建一个由三个下采样块组成的小型基础网络,每个块将通道数加倍。给定一个 \(256\times256\) 的输入图像,这个基础网络块输出 \(32 \times 32\) 的特征图 (\(256/2^3=32\))。
def base_net():
blk = []
num_filters = [3, 16, 32, 64]
for i in range(len(num_filters) - 1):
blk.append(down_sample_blk(num_filters[i], num_filters[i+1]))
return nn.Sequential(*blk)
forward(torch.zeros((2, 3, 256, 256)), base_net()).shape
torch.Size([2, 64, 32, 32])
def base_net():
blk = nn.Sequential()
for num_filters in [16, 32, 64]:
blk.add(down_sample_blk(num_filters))
return blk
forward(np.zeros((2, 3, 256, 256)), base_net()).shape
(2, 64, 32, 32)
14.7.1.6. 完整模型¶
完整的单发多框检测模型由五个块组成。每个块产生的特征图都用于(i)生成锚框和(ii)预测这些锚框的类别和偏移量。在这五个块中,第一个是基础网络块,第二到第四个是下采样块,最后一个块使用全局最大池化将高度和宽度都减为1。从技术上讲,第二到第五个块都是 图 14.7.1 中的多尺度特征图块。
def get_blk(i):
if i == 0:
blk = base_net()
elif i == 1:
blk = down_sample_blk(64, 128)
elif i == 4:
blk = nn.AdaptiveMaxPool2d((1,1))
else:
blk = down_sample_blk(128, 128)
return blk
def get_blk(i):
if i == 0:
blk = base_net()
elif i == 4:
blk = nn.GlobalMaxPool2D()
else:
blk = down_sample_blk(128)
return blk
现在我们为每个块定义前向传播。与图像分类任务不同,这里的输出包括(i)CNN特征图 Y
,(ii)在当前尺度下使用 Y
生成的锚框,以及(iii)为这些锚框预测的类别和偏移量(基于 Y
)。
def blk_forward(X, blk, size, ratio, cls_predictor, bbox_predictor):
Y = blk(X)
anchors = d2l.multibox_prior(Y, sizes=size, ratios=ratio)
cls_preds = cls_predictor(Y)
bbox_preds = bbox_predictor(Y)
return (Y, anchors, cls_preds, bbox_preds)
def blk_forward(X, blk, size, ratio, cls_predictor, bbox_predictor):
Y = blk(X)
anchors = d2l.multibox_prior(Y, sizes=size, ratios=ratio)
cls_preds = cls_predictor(Y)
bbox_preds = bbox_predictor(Y)
return (Y, anchors, cls_preds, bbox_preds)
回想一下,在 图 14.7.1 中,越靠近顶部的多尺度特征图块用于检测更大的物体;因此,它需要生成更大的锚框。在上述前向传播中,在每个多尺度特征图块,我们通过调用的 multibox_prior
函数(在 第 14.4 节 中描述)的 sizes
参数传入一个包含两个尺度值的列表。在下面,将0.2到1.05之间的区间均匀地分成五个部分,以确定五个块的较小尺度值:0.2、0.37、0.54、0.71和0.88。然后它们的较大尺度值由 \(\sqrt{0.2 \times 0.37} = 0.272\)、\(\sqrt{0.37 \times 0.54} = 0.447\) 等给出。
sizes = [[0.2, 0.272], [0.37, 0.447], [0.54, 0.619], [0.71, 0.79],
[0.88, 0.961]]
ratios = [[1, 2, 0.5]] * 5
num_anchors = len(sizes[0]) + len(ratios[0]) - 1
sizes = [[0.2, 0.272], [0.37, 0.447], [0.54, 0.619], [0.71, 0.79],
[0.88, 0.961]]
ratios = [[1, 2, 0.5]] * 5
num_anchors = len(sizes[0]) + len(ratios[0]) - 1
现在我们可以如下定义完整的模型 TinySSD
。
class TinySSD(nn.Module):
def __init__(self, num_classes, **kwargs):
super(TinySSD, self).__init__(**kwargs)
self.num_classes = num_classes
idx_to_in_channels = [64, 128, 128, 128, 128]
for i in range(5):
# Equivalent to the assignment statement `self.blk_i = get_blk(i)`
setattr(self, f'blk_{i}', get_blk(i))
setattr(self, f'cls_{i}', cls_predictor(idx_to_in_channels[i],
num_anchors, num_classes))
setattr(self, f'bbox_{i}', bbox_predictor(idx_to_in_channels[i],
num_anchors))
def forward(self, X):
anchors, cls_preds, bbox_preds = [None] * 5, [None] * 5, [None] * 5
for i in range(5):
# Here `getattr(self, 'blk_%d' % i)` accesses `self.blk_i`
X, anchors[i], cls_preds[i], bbox_preds[i] = blk_forward(
X, getattr(self, f'blk_{i}'), sizes[i], ratios[i],
getattr(self, f'cls_{i}'), getattr(self, f'bbox_{i}'))
anchors = torch.cat(anchors, dim=1)
cls_preds = concat_preds(cls_preds)
cls_preds = cls_preds.reshape(
cls_preds.shape[0], -1, self.num_classes + 1)
bbox_preds = concat_preds(bbox_preds)
return anchors, cls_preds, bbox_preds
class TinySSD(nn.Block):
def __init__(self, num_classes, **kwargs):
super(TinySSD, self).__init__(**kwargs)
self.num_classes = num_classes
for i in range(5):
# Equivalent to the assignment statement `self.blk_i = get_blk(i)`
setattr(self, f'blk_{i}', get_blk(i))
setattr(self, f'cls_{i}', cls_predictor(num_anchors, num_classes))
setattr(self, f'bbox_{i}', bbox_predictor(num_anchors))
def forward(self, X):
anchors, cls_preds, bbox_preds = [None] * 5, [None] * 5, [None] * 5
for i in range(5):
# Here `getattr(self, 'blk_%d' % i)` accesses `self.blk_i`
X, anchors[i], cls_preds[i], bbox_preds[i] = blk_forward(
X, getattr(self, f'blk_{i}'), sizes[i], ratios[i],
getattr(self, f'cls_{i}'), getattr(self, f'bbox_{i}'))
anchors = np.concatenate(anchors, axis=1)
cls_preds = concat_preds(cls_preds)
cls_preds = cls_preds.reshape(
cls_preds.shape[0], -1, self.num_classes + 1)
bbox_preds = concat_preds(bbox_preds)
return anchors, cls_preds, bbox_preds
我们创建一个模型实例,并用它对一个小批量的 \(256 \times 256\) 图像 X
执行前向传播。
如本节前面所示,第一个块输出 \(32 \times 32\) 的特征图。回想一下,第二到第四个下采样块将高度和宽度减半,第五个块使用全局池化。由于在特征图的空间维度上,每个单元生成4个锚框,所以在所有五个尺度上,每张图像总共生成 \((32^2 + 16^2 + 8^2 + 4^2 + 1)\times 4 = 5444\) 个锚框。
net = TinySSD(num_classes=1)
X = torch.zeros((32, 3, 256, 256))
anchors, cls_preds, bbox_preds = net(X)
print('output anchors:', anchors.shape)
print('output class preds:', cls_preds.shape)
print('output bbox preds:', bbox_preds.shape)
output anchors: torch.Size([1, 5444, 4])
output class preds: torch.Size([32, 5444, 2])
output bbox preds: torch.Size([32, 21776])
net = TinySSD(num_classes=1)
net.initialize()
X = np.zeros((32, 3, 256, 256))
anchors, cls_preds, bbox_preds = net(X)
print('output anchors:', anchors.shape)
print('output class preds:', cls_preds.shape)
print('output bbox preds:', bbox_preds.shape)
output anchors: (1, 5444, 4)
output class preds: (32, 5444, 2)
output bbox preds: (32, 21776)
14.7.2. 训练¶
现在我们将解释如何为目标检测训练单发多框检测模型。
14.7.2.1. 读取数据集和初始化模型¶
首先,让我们读取在 第 14.6 节 中描述的香蕉检测数据集。
batch_size = 32
train_iter, _ = d2l.load_data_bananas(batch_size)
read 1000 training examples
read 100 validation examples
batch_size = 32
train_iter, _ = d2l.load_data_bananas(batch_size)
read 1000 training examples
read 100 validation examples
香蕉检测数据集中只有一个类别。定义模型后,我们需要初始化其参数并定义优化算法。
device, net = d2l.try_gpu(), TinySSD(num_classes=1)
trainer = torch.optim.SGD(net.parameters(), lr=0.2, weight_decay=5e-4)
device, net = d2l.try_gpu(), TinySSD(num_classes=1)
net.initialize(init=init.Xavier(), ctx=device)
trainer = gluon.Trainer(net.collect_params(), 'sgd',
{'learning_rate': 0.2, 'wd': 5e-4})
[22:46:43] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for GPU
14.7.2.2. 定义损失和评估函数¶
目标检测有两种类型的损失。第一种损失涉及锚框的类别:其计算可以简单地重用我们用于图像分类的交叉熵损失函数。第二种损失涉及正(非背景)锚框的偏移量:这是一个回归问题。然而,对于这个回归问题,我们在这里不使用 第 3.1.3 节 中描述的平方损失。相反,我们使用 \(\ell_1\) 范数损失,即预测值和真实值之间差的绝对值。掩码变量 bbox_masks
在损失计算中过滤掉负锚框和非法(填充的)锚框。最后,我们将锚框类别损失和锚框偏移损失相加,得到模型的损失函数。
cls_loss = nn.CrossEntropyLoss(reduction='none')
bbox_loss = nn.L1Loss(reduction='none')
def calc_loss(cls_preds, cls_labels, bbox_preds, bbox_labels, bbox_masks):
batch_size, num_classes = cls_preds.shape[0], cls_preds.shape[2]
cls = cls_loss(cls_preds.reshape(-1, num_classes),
cls_labels.reshape(-1)).reshape(batch_size, -1).mean(dim=1)
bbox = bbox_loss(bbox_preds * bbox_masks,
bbox_labels * bbox_masks).mean(dim=1)
return cls + bbox
cls_loss = gluon.loss.SoftmaxCrossEntropyLoss()
bbox_loss = gluon.loss.L1Loss()
def calc_loss(cls_preds, cls_labels, bbox_preds, bbox_labels, bbox_masks):
cls = cls_loss(cls_preds, cls_labels)
bbox = bbox_loss(bbox_preds * bbox_masks, bbox_labels * bbox_masks)
return cls + bbox
我们可以使用准确率来评估分类结果。由于对偏移量使用了 \(\ell_1\) 范数损失,我们使用*平均绝对误差*来评估预测的边界框。这些预测结果是从生成的锚框和为其预测的偏移量中获得的。
def cls_eval(cls_preds, cls_labels):
# Because the class prediction results are on the final dimension,
# `argmax` needs to specify this dimension
return float((cls_preds.argmax(dim=-1).type(
cls_labels.dtype) == cls_labels).sum())
def bbox_eval(bbox_preds, bbox_labels, bbox_masks):
return float((torch.abs((bbox_labels - bbox_preds) * bbox_masks)).sum())
def cls_eval(cls_preds, cls_labels):
# Because the class prediction results are on the final dimension,
# `argmax` needs to specify this dimension
return float((cls_preds.argmax(axis=-1).astype(
cls_labels.dtype) == cls_labels).sum())
def bbox_eval(bbox_preds, bbox_labels, bbox_masks):
return float((np.abs((bbox_labels - bbox_preds) * bbox_masks)).sum())
14.7.2.3. 训练模型¶
在训练模型时,我们需要在前向传播中生成多尺度锚框 (anchors
) 并预测它们的类别 (cls_preds
) 和偏移量 (bbox_preds
)。然后,我们根据标签信息 Y
标记这些生成的锚框的类别 (cls_labels
) 和偏移量 (bbox_labels
)。最后,我们使用类别和偏移量的预测值和标签值计算损失函数。为了实现简洁,这里省略了对测试数据集的评估。
num_epochs, timer = 20, d2l.Timer()
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
legend=['class error', 'bbox mae'])
net = net.to(device)
for epoch in range(num_epochs):
# Sum of training accuracy, no. of examples in sum of training accuracy,
# Sum of absolute error, no. of examples in sum of absolute error
metric = d2l.Accumulator(4)
net.train()
for features, target in train_iter:
timer.start()
trainer.zero_grad()
X, Y = features.to(device), target.to(device)
# Generate multiscale anchor boxes and predict their classes and
# offsets
anchors, cls_preds, bbox_preds = net(X)
# Label the classes and offsets of these anchor boxes
bbox_labels, bbox_masks, cls_labels = d2l.multibox_target(anchors, Y)
# Calculate the loss function using the predicted and labeled values
# of the classes and offsets
l = calc_loss(cls_preds, cls_labels, bbox_preds, bbox_labels,
bbox_masks)
l.mean().backward()
trainer.step()
metric.add(cls_eval(cls_preds, cls_labels), cls_labels.numel(),
bbox_eval(bbox_preds, bbox_labels, bbox_masks),
bbox_labels.numel())
cls_err, bbox_mae = 1 - metric[0] / metric[1], metric[2] / metric[3]
animator.add(epoch + 1, (cls_err, bbox_mae))
print(f'class err {cls_err:.2e}, bbox mae {bbox_mae:.2e}')
print(f'{len(train_iter.dataset) / timer.stop():.1f} examples/sec on '
f'{str(device)}')
class err 3.27e-03, bbox mae 3.08e-03
4279.7 examples/sec on cuda:0
num_epochs, timer = 20, d2l.Timer()
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
legend=['class error', 'bbox mae'])
for epoch in range(num_epochs):
# Sum of training accuracy, no. of examples in sum of training accuracy,
# Sum of absolute error, no. of examples in sum of absolute error
metric = d2l.Accumulator(4)
for features, target in train_iter:
timer.start()
X = features.as_in_ctx(device)
Y = target.as_in_ctx(device)
with autograd.record():
# Generate multiscale anchor boxes and predict their classes and
# offsets
anchors, cls_preds, bbox_preds = net(X)
# Label the classes and offsets of these anchor boxes
bbox_labels, bbox_masks, cls_labels = d2l.multibox_target(anchors,
Y)
# Calculate the loss function using the predicted and labeled
# values of the classes and offsets
l = calc_loss(cls_preds, cls_labels, bbox_preds, bbox_labels,
bbox_masks)
l.backward()
trainer.step(batch_size)
metric.add(cls_eval(cls_preds, cls_labels), cls_labels.size,
bbox_eval(bbox_preds, bbox_labels, bbox_masks),
bbox_labels.size)
cls_err, bbox_mae = 1 - metric[0] / metric[1], metric[2] / metric[3]
animator.add(epoch + 1, (cls_err, bbox_mae))
print(f'class err {cls_err:.2e}, bbox mae {bbox_mae:.2e}')
print(f'{len(train_iter._dataset) / timer.stop():.1f} examples/sec on '
f'{str(device)}')
class err 3.48e-03, bbox mae 3.78e-03
1968.6 examples/sec on gpu(0)
14.7.3. 预测¶
在预测期间,目标是检测图像上所有感兴趣的物体。下面我们读取并调整一张测试图像的大小,将其转换为卷积层所需的四维张量。
X = torchvision.io.read_image('../img/banana.jpg').unsqueeze(0).float()
img = X.squeeze(0).permute(1, 2, 0).long()
img = image.imread('../img/banana.jpg')
feature = image.imresize(img, 256, 256).astype('float32')
X = np.expand_dims(feature.transpose(2, 0, 1), axis=0)
使用下面的 multibox_detection
函数,从锚框及其预测的偏移量中获得预测的边界框。然后使用非极大值抑制来移除相似的预测边界框。
def predict(X):
net.eval()
anchors, cls_preds, bbox_preds = net(X.to(device))
cls_probs = F.softmax(cls_preds, dim=2).permute(0, 2, 1)
output = d2l.multibox_detection(cls_probs, bbox_preds, anchors)
idx = [i for i, row in enumerate(output[0]) if row[0] != -1]
return output[0, idx]
output = predict(X)
def predict(X):
anchors, cls_preds, bbox_preds = net(X.as_in_ctx(device))
cls_probs = npx.softmax(cls_preds).transpose(0, 2, 1)
output = d2l.multibox_detection(cls_probs, bbox_preds, anchors)
idx = [i for i, row in enumerate(output[0]) if row[0] != -1]
return output[0, idx]
output = predict(X)
最后,我们显示所有置信度为0.9或更高的预测边界框作为输出。
def display(img, output, threshold):
d2l.set_figsize((5, 5))
fig = d2l.plt.imshow(img)
for row in output:
score = float(row[1])
if score < threshold:
continue
h, w = img.shape[:2]
bbox = [row[2:6] * torch.tensor((w, h, w, h), device=row.device)]
d2l.show_bboxes(fig.axes, bbox, '%.2f' % score, 'w')
display(img, output.cpu(), threshold=0.9)
def display(img, output, threshold):
d2l.set_figsize((5, 5))
fig = d2l.plt.imshow(img.asnumpy())
for row in output:
score = float(row[1])
if score < threshold:
continue
h, w = img.shape[:2]
bbox = [row[2:6] * np.array((w, h, w, h), ctx=row.ctx)]
d2l.show_bboxes(fig.axes, bbox, '%.2f' % score, 'w')
display(img, output, threshold=0.9)
14.7.4. 小结¶
单发多框检测是一种多尺度目标检测模型。通过其基础网络和几个多尺度特征图块,单发多框检测生成不同数量、不同大小的锚框,并通过预测这些锚框的类别和偏移量(从而得到边界框)来检测不同大小的物体。
在训练单发多框检测模型时,损失函数是根据锚框类别和偏移量的预测值和标签值计算的。
14.7.5. 练习¶
你能通过改进损失函数来改进单发多框检测吗?例如,将预测偏移量的 \(\ell_1\) 范数损失替换为平滑 \(\ell_1\) 范数损失。该损失函数在零点附近使用一个平方函数以保证平滑性,这由超参数 \(\sigma\) 控制
当 \(\sigma\) 非常大时,这个损失类似于 \(\ell_1\) 范数损失。当它的值较小时,损失函数更平滑。
def smooth_l1(data, scalar):
out = []
for i in data:
if abs(i) < 1 / (scalar ** 2):
out.append(((scalar * i) ** 2) / 2)
else:
out.append(abs(i) - 0.5 / (scalar ** 2))
return torch.tensor(out)
sigmas = [10, 1, 0.5]
lines = ['-', '--', '-.']
x = torch.arange(-2, 2, 0.1)
d2l.set_figsize()
for l, s in zip(lines, sigmas):
y = smooth_l1(x, scalar=s)
d2l.plt.plot(x, y, l, label='sigma=%.1f' % s)
d2l.plt.legend();
sigmas = [10, 1, 0.5]
lines = ['-', '--', '-.']
x = np.arange(-2, 2, 0.1)
d2l.set_figsize()
for l, s in zip(lines, sigmas):
y = npx.smooth_l1(x, scalar=s)
d2l.plt.plot(x.asnumpy(), y.asnumpy(), l, label='sigma=%.1f' % s)
d2l.plt.legend();
此外,在实验中我们使用交叉熵损失进行类别预测:记 \(p_j\) 为真实类别 \(j\) 的预测概率,交叉熵损失为 \(-\log p_j\)。我们也可以使用焦点损失 (Lin et al., 2017):给定超参数 \(\gamma > 0\) 和 \(\alpha > 0\),该损失定义为
正如我们所看到的,增加 \(\gamma\) 可以有效地减少分类良好样本(例如,\(p_j > 0.5\))的相对损失,这样训练就可以更专注于那些被错误分类的困难样本。
def focal_loss(gamma, x):
return -(1 - x) ** gamma * torch.log(x)
x = torch.arange(0.01, 1, 0.01)
for l, gamma in zip(lines, [0, 1, 5]):
y = d2l.plt.plot(x, focal_loss(gamma, x), l, label='gamma=%.1f' % gamma)
d2l.plt.legend();
def focal_loss(gamma, x):
return -(1 - x) ** gamma * np.log(x)
x = np.arange(0.01, 1, 0.01)
for l, gamma in zip(lines, [0, 1, 5]):
y = d2l.plt.plot(x.asnumpy(), focal_loss(gamma, x).asnumpy(), l,
label='gamma=%.1f' % gamma)
d2l.plt.legend();
由于篇幅限制,我们在本节中省略了单发多框检测模型的一些实现细节。你能在以下方面进一步改进模型吗
当一个物体与图像相比非常小时,模型可以把输入图像放大。
通常有大量的负锚框。为了使类别分布更均衡,我们可以对负锚框进行下采样。
在损失函数中,为类别损失和偏移损失分配不同的权重超参数。
使用其他方法来评估目标检测模型,例如单发多框检测论文 (Liu et al., 2016) 中的那些方法。