第14章コンピュータビジョン
14.4.3. Labeling Anchor Boxes in Training Data14.4.3 訓練データでアンカーボックスにラベルをつける
In a training dataset, we consider each anchor box as a training example. In order to train an object detection model, we need class and offset labels for each anchor box, where the former is the class of the object relevant to the anchor box and the latter is the offset of the ground-truth bounding box relative to the anchor box. During the prediction, for each image we generate multiple anchor boxes, predict classes and offsets for all the anchor boxes, adjust their positions according to the predicted offsets to obtain the predicted bounding boxes, and finally only output those predicted bounding boxes that satisfy certain criteria.
英語のヒント
訓練データセットでは、各アンカーボックスを一つの訓練事例とみなす。物体検出モデルを訓練するには、各アンカーボックスについてクラスとオフセットのラベルが必要である。前者はアンカーボックスに関係する物体のクラスであり、後者はアンカーボックスに対する正解の境界ボックスのオフセットである。予測のあいだは、各画像について複数のアンカーボックスを生成し、すべてのアンカーボックスのクラスとオフセットを予測し、予測したオフセットに従ってそれらの位置を調整して予測した境界ボックスを得て、最後に、ある基準を満たす予測した境界ボックスだけを出力する。
As we know, an object detection training set comes with labels for locations of ground-truth bounding boxes and classes of their surrounded objects. To label any generated anchor box, we refer to the labeled location and class of its assigned ground-truth bounding box that is closest to the anchor box. In the following, we describe an algorithm for assigning closest ground-truth bounding boxes to anchor boxes.
英語のヒント
知ってのとおり、物体検出の訓練集合には、正解の境界ボックスの位置と、それが囲む物体のクラスのラベルがついている。生成したアンカーボックスにラベルをつけるには、そのアンカーボックスに割り当てられた、最も近い正解の境界ボックスのラベルづけされた位置とクラスを参照する。以下では、最も近い正解の境界ボックスをアンカーボックスに割り当てるアルゴリズムを説明する。
14.4.3.1. Assigning Ground-Truth Bounding Boxes to Anchor Boxes14.4.3.1 正解の境界ボックスをアンカーボックスに割り当てる
Given an image, suppose that the anchor boxes are and the ground-truth bounding boxes are , where . Let’s define a matrix , whose element in the row and column is the IoU of the anchor box and the ground-truth bounding box . The algorithm consists of the following steps:
英語のヒント
画像が与えられたとき、アンカーボックスが、正解の境界ボックスがであるとする。ここでである。行列を定義しよう。そのの行との列にある要素は、アンカーボックスと正解の境界ボックスのIoUである。アルゴリズムは次の手順からなる。
- Find the largest element in matrix and denote its row and column indices as and , respectively. Then the ground-truth bounding box is assigned to the anchor box . This is quite intuitive because and are the closest among all the pairs of anchor boxes and ground-truth bounding boxes. After the first assignment, discard all the elements in the row and the column in matrix .
英語のヒント
行列の最大の要素を見つけ、その行と列の添字をそれぞれとで表す。すると、正解の境界ボックスがアンカーボックスに割り当てられる。とは、アンカーボックスと正解の境界ボックスのすべての組の中で最も近いので、これはかなり直観的である。最初の割り当ての後、行列のの行との列のすべての要素を捨てる。 - Find the largest of the remaining elements in matrix and denote its row and column indices as and , respectively. We assign ground-truth bounding box to anchor box and discard all the elements in the row and the column in matrix .
英語のヒント
行列の残りの要素の中で最大のものを見つけ、その行と列の添字をそれぞれとで表す。正解の境界ボックスをアンカーボックスに割り当て、行列のの行との列のすべての要素を捨てる。 - At this point, elements in two rows and two columns in matrix have been discarded. We proceed until all elements in columns in matrix are discarded. At this time, we have assigned a ground-truth bounding box to each of anchor boxes.
英語のヒント
この時点で、行列の2行と2列の要素が捨てられている。行列の列のすべての要素が捨てられるまで続ける。このとき、個のアンカーボックスのそれぞれに正解の境界ボックスを割り当てたことになる。 - Only traverse through the remaining anchor boxes. For example, given any anchor box , find the ground-truth bounding box with the largest IoU with throughout the row of matrix , and assign to only if this IoU is greater than a predefined threshold.
英語のヒント
残りの個のアンカーボックスだけを順にたどる。たとえば、任意のアンカーボックスが与えられたら、行列のの行全体でとのIoUが最大の正解の境界ボックスを見つけ、このIoUがあらかじめ決めた閾値より大きい場合にだけをに割り当てる。
Let’s illustrate the above algorithm using a concrete example. As shown in Fig. 14.4.2 (left), assuming that the maximum value in matrix is , we assign the ground-truth bounding box to the anchor box . Then, we discard all the elements in row 2 and column 3 of the matrix, find the largest in the remaining elements (shaded area), and assign the ground-truth bounding box to the anchor box . Next, as shown in Fig. 14.4.2 (middle), discard all the elements in row 7 and column 1 of the matrix, find the largest in the remaining elements (shaded area), and assign the ground-truth bounding box to the anchor box . Finally, as shown in Fig. 14.4.2 (right), discard all the elements in row 5 and column 4 of the matrix, find the largest in the remaining elements (shaded area), and assign the ground-truth bounding box to the anchor box . After that, we only need to traverse through the remaining anchor boxes and determine whether to assign them ground-truth bounding boxes according to the threshold.
英語のヒント
具体的な例を使って、上のアルゴリズムを示そう。図14.4.2(左)に示すように、行列の最大値がだとすると、正解の境界ボックスをアンカーボックスに割り当てる。それから、行列の2行目と3列目のすべての要素を捨て、残りの要素(網かけの領域)の中で最大のを見つけ、正解の境界ボックスをアンカーボックスに割り当てる。次に、図14.4.2(中央)に示すように、行列の7行目と1列目のすべての要素を捨て、残りの要素(網かけの領域)の中で最大のを見つけ、正解の境界ボックスをアンカーボックスに割り当てる。最後に、図14.4.2(右)に示すように、行列の5行目と4列目のすべての要素を捨て、残りの要素(網かけの領域)の中で最大のを見つけ、正解の境界ボックスをアンカーボックスに割り当てる。その後は、残りのアンカーボックスを順にたどり、閾値に従ってそれらに正解の境界ボックスを割り当てるかどうかを決めるだけでよい。
Fig. 14.4.2図14.4.2
Assigning ground-truth bounding boxes to anchor boxes.
英語のヒント
正解の境界ボックスをアンカーボックスに割り当てる。
This algorithm is implemented in the following
assign_anchor_to_bbox function.英語のヒント
このアルゴリズムは、次の
assign_anchor_to_bbox関数で実装されている。#@save
def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):
"""Assign closest ground-truth bounding boxes to anchor boxes."""
num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]
# Element x_ij in the i-th row and j-th column is the IoU of the anchor
# box i and the ground-truth bounding box j
jaccard = box_iou(anchors, ground_truth)
# Initialize the tensor to hold the assigned ground-truth bounding box for
# each anchor
anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long,
device=device)
# Assign ground-truth bounding boxes according to the threshold
max_ious, indices = torch.max(jaccard, dim=1)
anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1)
box_j = indices[max_ious >= iou_threshold]
anchors_bbox_map[anc_i] = box_j
col_discard = torch.full((num_anchors,), -1)
row_discard = torch.full((num_gt_boxes,), -1)
for _ in range(num_gt_boxes):
max_idx = torch.argmax(jaccard) # Find the largest IoU
box_idx = (max_idx % num_gt_boxes).long()
anc_idx = (max_idx / num_gt_boxes).long()
anchors_bbox_map[anc_idx] = box_idx
jaccard[:, box_idx] = col_discard
jaccard[anc_idx, :] = row_discard
return anchors_bbox_map14.4.3.2. Labeling Classes and Offsets14.4.3.2 クラスとオフセットのラベルづけ
Now we can label the class and offset for each anchor box. Suppose that an anchor box is assigned a ground-truth bounding box . On the one hand, the class of the anchor box will be labeled as that of . On the other hand, the offset of the anchor box will be labeled according to the relative position between the central coordinates of and together with the relative size between these two boxes. Given varying positions and sizes of different boxes in the dataset, we can apply transformations to those relative positions and sizes that may lead to more uniformly distributed offsets that are easier to fit. Here we describe a common transformation. Given the central coordinates of and as and , their widths as and , and their heights as and , respectively. We may label the offset of as
英語のヒント
これで、各アンカーボックスのクラスとオフセットにラベルをつけられる。アンカーボックスに正解の境界ボックスが割り当てられたとする。一方では、アンカーボックスのクラスはのクラスとしてラベルづけされる。他方では、アンカーボックスのオフセットは、との中心座標のあいだの相対的な位置と、この二つのボックスのあいだの相対的な大きさに従ってラベルづけされる。データセットの中のボックスの位置と大きさがさまざまであることを考えると、それらの相対的な位置と大きさに変換を当てはめて、もっと一様に分布し当てはめやすいオフセットにできる。ここでは、よく使われる変換を説明する。との中心座標をそれぞれと、幅をと、高さをととする。のオフセットは次のようにラベルづけできる。
(14.4.3)
where default values of the constants are , and . This transformation is implemented below in the
offset_boxes function.英語のヒント
ここで定数のデフォルト値はとである。この変換は、下の
offset_boxes関数で実装されている。#@save
def offset_boxes(anchors, assigned_bb, eps=1e-6):
"""Transform for anchor box offsets."""
c_anc = d2l.box_corner_to_center(anchors)
c_assigned_bb = d2l.box_corner_to_center(assigned_bb)
offset_xy = 10 * (c_assigned_bb[:, :2] - c_anc[:, :2]) / c_anc[:, 2:]
offset_wh = 5 * torch.log(eps + c_assigned_bb[:, 2:] / c_anc[:, 2:])
offset = torch.cat([offset_xy, offset_wh], axis=1)
return offsetIf an anchor box is not assigned a ground-truth bounding box, we just label the class of the anchor box as “background”. Anchor boxes whose classes are background are often referred to as negative anchor boxes, and the rest are called positive anchor boxes. We implement the following
multibox_target function to label classes and offsets for anchor boxes (the anchors argument) using ground-truth bounding boxes (the labels argument). This function sets the background class to zero and increments the integer index of a new class by one.英語のヒント
アンカーボックスに正解の境界ボックスが割り当てられていなければ、単にアンカーボックスのクラスを「背景」とラベルづけする。クラスが背景のアンカーボックスはしばしば負のアンカーボックスと呼ばれ、残りは正のアンカーボックスと呼ばれる。正解の境界ボックス(
labels引数)を使って、アンカーボックス(anchors引数)のクラスとオフセットにラベルをつける、次のmultibox_target関数を実装する。この関数は、背景のクラスをゼロに設定し、新しいクラスの整数の添字を1ずつ増やす。#@save
def multibox_target(anchors, labels):
"""Label anchor boxes using ground-truth bounding boxes."""
batch_size, anchors = labels.shape[0], anchors.squeeze(0)
batch_offset, batch_mask, batch_class_labels = [], [], []
device, num_anchors = anchors.device, anchors.shape[0]
for i in range(batch_size):
label = labels[i, :, :]
anchors_bbox_map = assign_anchor_to_bbox(
label[:, 1:], anchors, device)
bbox_mask = ((anchors_bbox_map >= 0).float().unsqueeze(-1)).repeat(
1, 4)
# Initialize class labels and assigned bounding box coordinates with
# zeros
class_labels = torch.zeros(num_anchors, dtype=torch.long,
device=device)
assigned_bb = torch.zeros((num_anchors, 4), dtype=torch.float32,
device=device)
# Label classes of anchor boxes using their assigned ground-truth
# bounding boxes. If an anchor box is not assigned any, we label its
# class as background (the value remains zero)
indices_true = torch.nonzero(anchors_bbox_map >= 0)
bb_idx = anchors_bbox_map[indices_true]
class_labels[indices_true] = label[bb_idx, 0].long() + 1
assigned_bb[indices_true] = label[bb_idx, 1:]
# Offset transformation
offset = offset_boxes(anchors, assigned_bb) * bbox_mask
batch_offset.append(offset.reshape(-1))
batch_mask.append(bbox_mask.reshape(-1))
batch_class_labels.append(class_labels)
bbox_offset = torch.stack(batch_offset)
bbox_mask = torch.stack(batch_mask)
class_labels = torch.stack(batch_class_labels)
return (bbox_offset, bbox_mask, class_labels)14.4.3.3. An Example14.4.3.3 例
Let’s illustrate anchor box labeling via a concrete example. We define ground-truth bounding boxes for the dog and cat in the loaded image, where the first element is the class (0 for dog and 1 for cat) and the remaining four elements are the -axis coordinates at the upper-left corner and the lower-right corner (range is between 0 and 1). We also construct five anchor boxes to be labeled using the coordinates of the upper-left corner and the lower-right corner: (the index starts from 0). Then we plot these ground-truth bounding boxes and anchor boxes in the image.
英語のヒント
具体的な例を通じて、アンカーボックスのラベルづけを示そう。読み込んだ画像の中の犬と猫の正解の境界ボックスを定義する。最初の要素はクラス(犬は0、猫は1)であり、残りの四つの要素は左上の角と右下の角の軸座標(範囲は0から1)である。また、左上の角と右下の角の座標を使って、ラベルをつける五つのアンカーボックス(添字は0から始まる)を構築する。それから、これらの正解の境界ボックスとアンカーボックスを画像に描く。
ground_truth = torch.tensor([[0, 0.1, 0.08, 0.52, 0.92],
[1, 0.55, 0.2, 0.9, 0.88]])
anchors = torch.tensor([[0, 0.1, 0.2, 0.3], [0.15, 0.2, 0.4, 0.4],
[0.63, 0.05, 0.88, 0.98], [0.66, 0.45, 0.8, 0.8],
[0.57, 0.3, 0.92, 0.9]])
fig = d2l.plt.imshow(img)
show_bboxes(fig.axes, ground_truth[:, 1:] * bbox_scale, ['dog', 'cat'], 'k')
show_bboxes(fig.axes, anchors * bbox_scale, ['0', '1', '2', '3', '4']);Using the
multibox_target function defined above, we can label classes and offsets of these anchor boxes based on the ground-truth bounding boxes for the dog and cat. In this example, indices of the background, dog, and cat classes are 0, 1, and 2, respectively. Below we add an dimension for examples of anchor boxes and ground-truth bounding boxes.英語のヒント
上で定義した
multibox_target関数を使うと、犬と猫の正解の境界ボックスにもとづいて、これらのアンカーボックスのクラスとオフセットにラベルをつけられる。この例では、背景、犬、猫のクラスの添字はそれぞれ0、1、2である。下では、アンカーボックスと正解の境界ボックスの事例のための次元を加える。labels = multibox_target(anchors.unsqueeze(dim=0),
ground_truth.unsqueeze(dim=0))There are three items in the returned result, all of which are in the tensor format. The third item contains the labeled classes of the input anchor boxes.
英語のヒント
返された結果には三つの項目があり、どれもテンソルの形式である。3番目の項目は、入力したアンカーボックスのラベルづけされたクラスを含む。
Let’s analyze the returned class labels below based on anchor box and ground-truth bounding box positions in the image. First, among all the pairs of anchor boxes and ground-truth bounding boxes, the IoU of the anchor box and the ground-truth bounding box of the cat is the largest. Thus, the class of is labeled as the cat. Taking out pairs containing or the ground-truth bounding box of the cat, among the rest the pair of the anchor box and the ground-truth bounding box of the dog has the largest IoU. So the class of is labeled as the dog. Next, we need to traverse through the remaining three unlabeled anchor boxes: , , and . For , the class of the ground-truth bounding box with the largest IoU is the dog, but the IoU is below the predefined threshold (0.5), so the class is labeled as background; for , the class of the ground-truth bounding box with the largest IoU is the cat and the IoU exceeds the threshold, so the class is labeled as the cat; for , the class of the ground-truth bounding box with the largest IoU is the cat, but the value is below the threshold, so the class is labeled as background.
英語のヒント
画像の中のアンカーボックスと正解の境界ボックスの位置にもとづいて、返されたクラスのラベルを下で分析しよう。まず、アンカーボックスと正解の境界ボックスのすべての組の中で、アンカーボックスと猫の正解の境界ボックスのIoUが最大である。したがって、のクラスは猫とラベルづけされる。か猫の正解の境界ボックスを含む組を除くと、残りの中では、アンカーボックスと犬の正解の境界ボックスの組のIoUが最大である。そこで、のクラスは犬とラベルづけされる。次に、ラベルのない残りの三つのアンカーボックス、、を順にたどる必要がある。では、IoUが最大の正解の境界ボックスのクラスは犬だが、IoUはあらかじめ決めた閾値(0.5)を下回るので、クラスは背景とラベルづけされる。では、IoUが最大の正解の境界ボックスのクラスは猫で、IoUは閾値を超えるので、クラスは猫とラベルづけされる。では、IoUが最大の正解の境界ボックスのクラスは猫だが、値は閾値を下回るので、クラスは背景とラベルづけされる。
labels[2]tensor([[0, 1, 2, 0, 2]])The second returned item is a mask variable of the shape (batch size, four times the number of anchor boxes). Every four elements in the mask variable correspond to the four offset values of each anchor box. Since we do not care about background detection, offsets of this negative class should not affect the objective function. Through elementwise multiplications, zeros in the mask variable will filter out negative class offsets before calculating the objective function.
英語のヒント
2番目に返される項目は、形状が(バッチの大きさ、アンカーボックスの数の4倍)のマスクの変数である。マスクの変数の4つの要素ごとに、各アンカーボックスの四つのオフセットの値に対応する。背景の検出には関心がないので、この負のクラスのオフセットは目的関数に影響してはならない。要素ごとの掛け算を通じて、マスクの変数のゼロは、目的関数を計算する前に負のクラスのオフセットを取り除く。
labels[1]tensor([[0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 1., 1.,
1., 1.]])The first returned item contains the four offset values labeled for each anchor box. Note that the offsets of negative-class anchor boxes are labeled as zeros.
英語のヒント
最初に返される項目は、各アンカーボックスにラベルづけされた四つのオフセットの値を含む。負のクラスのアンカーボックスのオフセットはゼロとラベルづけされることに注意してほしい。
labels[0]tensor([[-0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00, 1.40e+00, 1.00e+01,
2.59e+00, 7.18e+00, -1.20e+00, 2.69e-01, 1.68e+00, -1.57e+00,
-0.00e+00, -0.00e+00, -0.00e+00, -0.00e+00, -5.71e-01, -1.00e+00,
4.17e-06, 6.26e-01]])