プリンキピア

第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 A1,A2,…,Ana and the ground-truth bounding boxes are B1,B2,…,Bnb, where na≥nb. Let’s define a matrix 𝐗∈ℝna×nb, whose element xij in the ith row and jth column is the IoU of the anchor box Ai and the ground-truth bounding box Bj. The algorithm consists of the following steps:
英語のヒント
画像が与えられたとき、アンカーボックスがA1,A2,…,Ana、正解の境界ボックスがB1,B2,…,Bnbであるとする。ここでna≥nbである。行列𝐗∈ℝna×nbを定義しよう。そのithの行とjthの列にある要素xijは、アンカーボックスAiと正解の境界ボックスBjのIoUである。アルゴリズムは次の手順からなる。
  1. Find the largest element in matrix 𝐗 and denote its row and column indices as i1 and j1, respectively. Then the ground-truth bounding box Bj1 is assigned to the anchor box Ai1. This is quite intuitive because Ai1 and Bj1 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 i1th row and the j1th column in matrix 𝐗.
    英語のヒント
    行列𝐗の最大の要素を見つけ、その行と列の添字をそれぞれi1とj1で表す。すると、正解の境界ボックスBj1がアンカーボックスAi1に割り当てられる。Ai1とBj1は、アンカーボックスと正解の境界ボックスのすべての組の中で最も近いので、これはかなり直観的である。最初の割り当ての後、行列𝐗のi1thの行とj1thの列のすべての要素を捨てる。
  2. Find the largest of the remaining elements in matrix 𝐗 and denote its row and column indices as i2 and j2, respectively. We assign ground-truth bounding box Bj2 to anchor box Ai2 and discard all the elements in the i2th row and the j2th column in matrix 𝐗.
    英語のヒント
    行列𝐗の残りの要素の中で最大のものを見つけ、その行と列の添字をそれぞれi2とj2で表す。正解の境界ボックスBj2をアンカーボックスAi2に割り当て、行列𝐗のi2thの行とj2thの列のすべての要素を捨てる。
  3. At this point, elements in two rows and two columns in matrix 𝐗 have been discarded. We proceed until all elements in nb columns in matrix 𝐗 are discarded. At this time, we have assigned a ground-truth bounding box to each of nb anchor boxes.
    英語のヒント
    この時点で、行列𝐗の2行と2列の要素が捨てられている。行列𝐗のnb列のすべての要素が捨てられるまで続ける。このとき、nb個のアンカーボックスのそれぞれに正解の境界ボックスを割り当てたことになる。
  4. Only traverse through the remaining na−nb anchor boxes. For example, given any anchor box Ai, find the ground-truth bounding box Bj with the largest IoU with Ai throughout the ith row of matrix 𝐗, and assign Bj to Ai only if this IoU is greater than a predefined threshold.
    英語のヒント
    残りのna−nb個のアンカーボックスだけを順にたどる。たとえば、任意のアンカーボックスAiが与えられたら、行列𝐗のithの行全体でAiとのIoUが最大の正解の境界ボックスBjを見つけ、このIoUがあらかじめ決めた閾値より大きい場合にだけBjをAiに割り当てる。
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 x23, we assign the ground-truth bounding box B3 to the anchor box A2. Then, we discard all the elements in row 2 and column 3 of the matrix, find the largest x71 in the remaining elements (shaded area), and assign the ground-truth bounding box B1 to the anchor box A7. 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 x54 in the remaining elements (shaded area), and assign the ground-truth bounding box B4 to the anchor box A5. 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 x92 in the remaining elements (shaded area), and assign the ground-truth bounding box B2 to the anchor box A9. After that, we only need to traverse through the remaining anchor boxes A1,A3,A4,A6,A8 and determine whether to assign them ground-truth bounding boxes according to the threshold.
英語のヒント
具体的な例を使って、上のアルゴリズムを示そう。図14.4.2(左)に示すように、行列𝐗の最大値がx23だとすると、正解の境界ボックスB3をアンカーボックスA2に割り当てる。それから、行列の2行目と3列目のすべての要素を捨て、残りの要素(網かけの領域)の中で最大のx71を見つけ、正解の境界ボックスB1をアンカーボックスA7に割り当てる。次に、図14.4.2(中央)に示すように、行列の7行目と1列目のすべての要素を捨て、残りの要素(網かけの領域)の中で最大のx54を見つけ、正解の境界ボックスB4をアンカーボックスA5に割り当てる。最後に、図14.4.2(右)に示すように、行列の5行目と4列目のすべての要素を捨て、残りの要素(網かけの領域)の中で最大のx92を見つけ、正解の境界ボックスB2をアンカーボックスA9に割り当てる。その後は、残りのアンカーボックスA1,A3,A4,A6,A8を順にたどり、閾値に従ってそれらに正解の境界ボックスを割り当てるかどうかを決めるだけでよい。
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_map

14.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 A is assigned a ground-truth bounding box B. On the one hand, the class of the anchor box A will be labeled as that of B. On the other hand, the offset of the anchor box A will be labeled according to the relative position between the central coordinates of B and A 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 A and B as (xa,ya) and (xb,yb), their widths as wa and wb, and their heights as ha and hb, respectively. We may label the offset of A as
英語のヒント
これで、各アンカーボックスのクラスとオフセットにラベルをつけられる。アンカーボックスAに正解の境界ボックスBが割り当てられたとする。一方では、アンカーボックスAのクラスはBのクラスとしてラベルづけされる。他方では、アンカーボックスAのオフセットは、BとAの中心座標のあいだの相対的な位置と、この二つのボックスのあいだの相対的な大きさに従ってラベルづけされる。データセットの中のボックスの位置と大きさがさまざまであることを考えると、それらの相対的な位置と大きさに変換を当てはめて、もっと一様に分布し当てはめやすいオフセットにできる。ここでは、よく使われる変換を説明する。AとBの中心座標をそれぞれ(xa,ya)と(xb,yb)、幅をwaとwb、高さをhaとhbとする。Aのオフセットは次のようにラベルづけできる。
(xb−xawa−μxσx,yb−yaha−μyσy,log⁡wbwa−μwσw,log⁡hbha−μhσh),(14.4.3)
where default values of the constants are μx=μy=μw=μh=0,σx=σy=0.1, and σw=σh=0.2. This transformation is implemented below in the offset_boxes function.
英語のヒント
ここで定数のデフォルト値はμx=μy=μw=μh=0,σx=σy=0.1とσw=σh=0.2である。この変換は、下の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 offset
If 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 (x,y)-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: A0,…,A4 (the index starts from 0). Then we plot these ground-truth bounding boxes and anchor boxes in the image.
英語のヒント
具体的な例を通じて、アンカーボックスのラベルづけを示そう。読み込んだ画像の中の犬と猫の正解の境界ボックスを定義する。最初の要素はクラス(犬は0、猫は1)であり、残りの四つの要素は左上の角と右下の角の(x,y)軸座標(範囲は0から1)である。また、左上の角と右下の角の座標を使って、ラベルをつける五つのアンカーボックスA0,…,A4(添字は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 A4 and the ground-truth bounding box of the cat is the largest. Thus, the class of A4 is labeled as the cat. Taking out pairs containing A4 or the ground-truth bounding box of the cat, among the rest the pair of the anchor box A1 and the ground-truth bounding box of the dog has the largest IoU. So the class of A1 is labeled as the dog. Next, we need to traverse through the remaining three unlabeled anchor boxes: A0, A2, and A3. For A0, 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 A2, 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 A3, 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.
英語のヒント
画像の中のアンカーボックスと正解の境界ボックスの位置にもとづいて、返されたクラスのラベルを下で分析しよう。まず、アンカーボックスと正解の境界ボックスのすべての組の中で、アンカーボックスA4と猫の正解の境界ボックスのIoUが最大である。したがって、A4のクラスは猫とラベルづけされる。A4か猫の正解の境界ボックスを含む組を除くと、残りの中では、アンカーボックスA1と犬の正解の境界ボックスの組のIoUが最大である。そこで、A1のクラスは犬とラベルづけされる。次に、ラベルのない残りの三つのアンカーボックスA0、A2、A3を順にたどる必要がある。A0では、IoUが最大の正解の境界ボックスのクラスは犬だが、IoUはあらかじめ決めた閾値(0.5)を下回るので、クラスは背景とラベルづけされる。A2では、IoUが最大の正解の境界ボックスのクラスは猫で、IoUは閾値を超えるので、クラスは猫とラベルづけされる。A3では、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]])