第14章コンピュータビジョン
14.7.1. Model14.7.1 モデル
Fig. 14.7.1 provides an overview of the design of single-shot multibox detection. This model mainly consists of a base network followed by several multiscale feature map blocks. The base network is for extracting features from the input image, so it can use a deep CNN. For example, the original single-shot multibox detection paper adopts a VGG network truncated before the classification layer (Liu et al., 2016), while ResNet has also been commonly used. Through our design we can make the base network output larger feature maps so as to generate more anchor boxes for detecting smaller objects. Subsequently, each multiscale feature map block reduces (e.g., by half) the height and width of the feature maps from the previous block, and enables each unit of the feature maps to increase its receptive field on the input image.
英語のヒント
図14.7.1は、シングルショット・マルチボックス検出の設計の概観を示している。このモデルは主に、ベースネットワークと、その後に続くいくつかのマルチスケールの特徴マップのブロックからなる。ベースネットワークは入力画像から特徴を抽出するためのものなので、深いCNNを使える。たとえば、元のシングルショット・マルチボックス検出の論文は、分類層の前で切り詰めたVGGネットワークを採用しており(Liu et al., 2016)、ResNetもよく使われてきた。設計によって、ベースネットワークにもっと大きな特徴マップを出力させ、小さな物体を検出するためにもっと多くのアンカーボックスを生成できる。その後、各マルチスケールの特徴マップのブロックは、前のブロックからの特徴マップの高さと幅を(たとえば半分に)減らし、特徴マップの各ユニットが入力画像上の受容野を広げられるようにする。
Recall the design of multiscale object detection through layerwise representations of images by deep neural networks in Section 14.5. Since multiscale feature maps closer to the top of Fig. 14.7.1 are smaller but have larger receptive fields, they are suitable for detecting fewer but larger objects.
英語のヒント
In a nutshell, via its base network and several multiscale feature map blocks, single-shot multibox detection generates a varying number of anchor boxes with different sizes, and detects varying-size objects by predicting classes and offsets of these anchor boxes (thus the bounding boxes); thus, this is a multiscale object detection model.
英語のヒント
手短に言えば、シングルショット・マルチボックス検出は、ベースネットワークといくつかのマルチスケールの特徴マップのブロックを通じて、大きさの異なるアンカーボックスをさまざまな数だけ生成し、それらのアンカーボックス(したがって境界ボックス)のクラスとオフセットを予測して、大きさの異なる物体を検出する。したがって、これはマルチスケールの物体検出モデルである。
Fig. 14.7.1図14.7.1
As a multiscale object detection model, single-shot multibox detection mainly consists of a base network followed by several multiscale feature map blocks.
英語のヒント
マルチスケールの物体検出モデルとして、シングルショット・マルチボックス検出は主に、ベースネットワークと、その後に続くいくつかのマルチスケールの特徴マップのブロックからなる。
In the following, we will describe the implementation details of different blocks in Fig. 14.7.1. To begin with, we discuss how to implement the class and bounding box prediction.
英語のヒント
以下では、図14.7.1のさまざまなブロックの実装の詳細を説明する。まず、クラスと境界ボックスの予測をどう実装するかを論じる。
14.7.1.1. Class Prediction Layer14.7.1.1 クラス予測層
Let the number of object classes be . Then anchor boxes have classes, where class 0 is background. At some scale, suppose that the height and width of feature maps are and , respectively. When anchor boxes are generated with each spatial position of these feature maps as their center, a total of anchor boxes need to be classified. This often makes classification with fully connected layers infeasible due to likely heavy parametrization costs. Recall how we used channels of convolutional layers to predict classes in Section 8.3. Single-shot multibox detection uses the same technique to reduce model complexity.
英語のヒント
物体のクラスの数をとする。するとアンカーボックスには個のクラスがあり、クラス0は背景である。あるスケールで、特徴マップの高さと幅がそれぞれとだとする。これらの特徴マップの各空間の位置を中心として個のアンカーボックスを生成すると、合計個のアンカーボックスを分類する必要がある。このため、パラメータ化のコストが重くなりそうなので、全結合層での分類はしばしば実行できない。8.3節で、畳み込み層のチャネルを使ってクラスを予測した方法を思い出そう。シングルショット・マルチボックス検出は、同じ技法を使ってモデルの複雑さを減らす。
Specifically, the class prediction layer uses a convolutional layer without altering width or height of feature maps. In this way, there can be a one-to-one correspondence between outputs and inputs at the same spatial dimensions (width and height) of feature maps. More concretely, channels of the output feature maps at any spatial position (, ) represent class predictions for all the anchor boxes centered on (, ) of the input feature maps. To produce valid predictions, there must be output channels, where for the same spatial position the output channel with index represents the prediction of the class () for the anchor box ().
英語のヒント
具体的には、クラス予測層は、特徴マップの幅や高さを変えない畳み込み層を使う。こうすると、特徴マップの同じ空間の次元(幅と高さ)で、出力と入力のあいだに1対1の対応ができる。もっと具体的には、任意の空間の位置(, )での出力の特徴マップのチャネルは、入力の特徴マップの(, )を中心とするすべてのアンカーボックスについてのクラスの予測を表す。有効な予測を出すには、出力チャネルが個なければならない。そこでは、同じ空間の位置について、添字の出力チャネルが、アンカーボックス()についてのクラス()の予測を表す。
Below we define such a class prediction layer, specifying and via arguments
num_anchors and num_classes, respectively. This layer uses a convolutional layer with a padding of 1. The width and height of the input and output of this convolutional layer remain unchanged.英語のヒント
下では、そのようなクラス予測層を定義し、引数
num_anchorsとnum_classesでそれぞれとを指定する。この層は、パディング1のの畳み込み層を使う。この畳み込み層の入力と出力の幅と高さは変わらない。%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)14.7.1.2. Bounding Box Prediction Layer14.7.1.2 境界ボックス予測層
The design of the bounding box prediction layer is similar to that of the class prediction layer. The only difference lies in the number of outputs for each anchor box: here we need to predict four offsets rather than classes.
英語のヒント
境界ボックス予測層の設計は、クラス予測層の設計と似ている。唯一の違いは、各アンカーボックスについての出力の数にある。ここでは、個のクラスではなく、四つのオフセットを予測する必要がある。
def bbox_predictor(num_inputs, num_anchors):
return nn.Conv2d(num_inputs, num_anchors * 4, kernel_size=3, padding=1)14.7.1.3. Concatenating Predictions for Multiple Scales14.7.1.3 複数のスケールの予測を連結する
As we mentioned, single-shot multibox detection uses multiscale feature maps to generate anchor boxes and predict their classes and offsets. At different scales, the shapes of feature maps or the numbers of anchor boxes centered on the same unit may vary. Therefore, shapes of the prediction outputs at different scales may vary.
英語のヒント
述べたように、シングルショット・マルチボックス検出は、マルチスケールの特徴マップを使ってアンカーボックスを生成し、そのクラスとオフセットを予測する。異なるスケールでは、特徴マップの形状や、同じユニットを中心とするアンカーボックスの数が異なることがある。したがって、異なるスケールでの予測の出力の形状は異なることがある。
In the following example, we construct feature maps at two different scales,
Y1 and Y2, for the same minibatch, where the height and width of Y2 are half of those of Y1. Let’s take class prediction as an example. Suppose that 5 and 3 anchor boxes are generated for every unit in Y1 and Y2, respectively. Suppose further that the number of object classes is 10. For feature maps Y1 and Y2 the numbers of channels in the class prediction outputs are and , respectively, where either output shape is (batch size, number of channels, height, width).英語のヒント
次の例では、同じミニバッチについて、二つの異なるスケールの特徴マップ
Y1とY2を作る。ここで、Y2の高さと幅はY1の半分である。クラスの予測を例にとろう。Y1とY2の各ユニットについて、それぞれ5個と3個のアンカーボックスが生成されるとする。さらに、物体のクラスの数は10だとする。特徴マップY1とY2について、クラスの予測の出力のチャネル数はそれぞれとであり、どちらの出力の形状も(バッチの大きさ、チャネル数、高さ、幅)である。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]))As we can see, except for the batch size dimension, the other three dimensions all have different sizes. To concatenate these two prediction outputs for more efficient computation, we will transform these tensors into a more consistent format.
英語のヒント
見てのとおり、バッチの大きさの次元を除いて、ほかの三つの次元はどれも大きさが異なる。計算をもっと効率的にするためにこれら二つの予測の出力を連結するには、これらのテンソルをもっと一貫した形式に変換する。
Note that the channel dimension holds the predictions for anchor boxes with the same center. We first move this dimension to the innermost. Since the batch size remains the same for different scales, we can transform the prediction output into a two-dimensional tensor with shape (batch size, height width number of channels). Then we can concatenate such outputs at different scales along dimension 1.
英語のヒント
チャネルの次元には、中心が同じアンカーボックスについての予測が入っていることに注意してほしい。まず、この次元を最も内側に移す。バッチの大きさは異なるスケールで同じなので、予測の出力を、形状が(バッチの大きさ、高さ幅チャネル数)の2次元テンソルに変換できる。それから、異なるスケールでのそうした出力を、次元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)In this way, even though
Y1 and Y2 have different sizes in channels, heights, and widths, we can still concatenate these two prediction outputs at two different scales for the same minibatch.英語のヒント
こうすると、
Y1とY2はチャネル、高さ、幅の大きさが異なっていても、同じミニバッチについて、二つの異なるスケールでのこれら二つの予測の出力を連結できる。concat_preds([Y1, Y2]).shapetorch.Size([2, 25300])14.7.1.4. Downsampling Block14.7.1.4 ダウンサンプリングのブロック
In order to detect objects at multiple scales, we define the following downsampling block
down_sample_blk that halves the height and width of input feature maps. In fact, this block applies the design of VGG blocks in Section 8.2.1. More concretely, each downsampling block consists of two convolutional layers with padding of 1 followed by a max-pooling layer with stride of 2. As we know, convolutional layers with padding of 1 do not change the shape of feature maps. However, the subsequent max-pooling reduces the height and width of input feature maps by half. For both input and output feature maps of this downsampling block, because , each unit in the output has a receptive field on the input. Therefore, the downsampling block enlarges the receptive field of each unit in its output feature maps.英語のヒント
複数のスケールで物体を検出するため、入力の特徴マップの高さと幅を半分にする、次のダウンサンプリングのブロック
down_sample_blkを定義する。実際、このブロックは8.2.1節のVGGブロックの設計を当てはめている。もっと具体的には、各ダウンサンプリングのブロックは、パディング1の二つのの畳み込み層と、その後に続くストライド2のの最大プーリング層からなる。知ってのとおり、パディング1のの畳み込み層は特徴マップの形状を変えない。しかし、後に続くの最大プーリングは、入力の特徴マップの高さと幅を半分にする。このダウンサンプリングのブロックの入力と出力の特徴マップの両方について、なので、出力の各ユニットは入力上での受容野をもつ。したがって、ダウンサンプリングのブロックは、その出力の特徴マップの各ユニットの受容野を広げる。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)In the following example, our constructed downsampling block changes the number of input channels and halves the height and width of the input feature maps.
英語のヒント
次の例では、作ったダウンサンプリングのブロックが、入力チャネルの数を変え、入力の特徴マップの高さと幅を半分にする。
forward(torch.zeros((2, 3, 20, 20)), down_sample_blk(3, 10)).shapetorch.Size([2, 10, 10, 10])14.7.1.5. Base Network Block14.7.1.5 ベースネットワークのブロック
The base network block is used to extract features from input images. For simplicity, we construct a small base network consisting of three downsampling blocks that double the number of channels at each block. Given a input image, this base network block outputs feature maps ().
英語のヒント
ベースネットワークのブロックは、入力画像から特徴を抽出するのに使われる。簡単のため、各ブロックでチャネル数を2倍にする三つのダウンサンプリングのブロックからなる、小さなベースネットワークを作る。の入力画像が与えられると、このベースネットワークのブロックはの特徴マップを出力する()。
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()).shapetorch.Size([2, 64, 32, 32])14.7.1.6. The Complete Model14.7.1.6 完全なモデル
The complete single shot multibox detection model consists of five blocks. The feature maps produced by each block are used for both (i) generating anchor boxes and (ii) predicting classes and offsets of these anchor boxes. Among these five blocks, the first one is the base network block, the second to the fourth are downsampling blocks, and the last block uses global max-pooling to reduce both the height and width to 1. Technically, the second to the fifth blocks are all those multiscale feature map blocks in Fig. 14.7.1.
英語のヒント
完全なシングルショット・マルチボックス検出のモデルは、五つのブロックからなる。各ブロックが生み出す特徴マップは、(i)アンカーボックスを生成すること、(ii)それらのアンカーボックスのクラスとオフセットを予測すること、の両方に使われる。これら五つのブロックのうち、最初のものはベースネットワークのブロックで、2番目から4番目はダウンサンプリングのブロックであり、最後のブロックは大域最大プーリングを使って高さと幅をどちらも1に減らす。技術的には、2番目から5番目のブロックはすべて、図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 blkNow we define the forward propagation for each block. Different from in image classification tasks, outputs here include (i) CNN feature maps
Y, (ii) anchor boxes generated using Y at the current scale, and (iii) classes and offsets predicted (based on Y) for these anchor boxes.英語のヒント
では、各ブロックの順伝播を定義する。画像分類の課題とは違って、ここでの出力には、(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)Recall that in Fig. 14.7.1 a multiscale feature map block that is closer to the top is for detecting larger objects; thus, it needs to generate larger anchor boxes. In the above forward propagation, at each multiscale feature map block we pass in a list of two scale values via the
sizes argument of the invoked multibox_prior function (described in Section 14.4). In the following, the interval between 0.2 and 1.05 is split evenly into five sections to determine the smaller scale values at the five blocks: 0.2, 0.37, 0.54, 0.71, and 0.88. Then their larger scale values are given by , , and so on.英語のヒント
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]) - 1Now we can define the complete model
TinySSD as follows.英語のヒント
これで、完全なモデル
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_predsWe create a model instance and use it to perform forward propagation on a minibatch of images
X.英語のヒント
モデルのインスタンスを作り、それを使っての画像のミニバッチ
Xで順伝播を行う。As shown earlier in this section, the first block outputs feature maps. Recall that the second to fourth downsampling blocks halve the height and width and the fifth block uses global pooling. Since 4 anchor boxes are generated for each unit along spatial dimensions of feature maps, at all the five scales a total of anchor boxes are generated for each image.
英語のヒント
この節の前のほうで示したように、最初のブロックはの特徴マップを出力する。2番目から4番目のダウンサンプリングのブロックは高さと幅を半分にし、5番目のブロックは大域プーリングを使うことを思い出そう。特徴マップの空間の次元に沿って各ユニットについて4個のアンカーボックスが生成されるので、五つのスケールすべてで、各画像について合計個のアンカーボックスが生成される。
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])