プリンキピア

第14章コンピュータビジョン

14.7.2. Training14.7.2 訓練

Now we will explain how to train the single shot multibox detection model for object detection.
英語のヒント
では、物体検出のためにシングルショット・マルチボックス検出のモデルをどう訓練するかを説明する。

14.7.2.1. Reading the Dataset and Initializing the Model14.7.2.1 データセットを読み、モデルを初期化する

To begin with, let’s read the banana detection dataset described in Section 14.6.
英語のヒント
まず、14.6節で説明したバナナ検出のデータセットを読もう。
batch_size = 32
train_iter, _ = d2l.load_data_bananas(batch_size)
read 1000 training examples
read 100 validation examples
There is only one class in the banana detection dataset. After defining the model, we need to initialize its parameters and define the optimization algorithm.
英語のヒント
バナナ検出のデータセットにはクラスが一つしかない。モデルを定義した後、そのパラメータを初期化し、最適化アルゴリズムを定義する必要がある。
device, net = d2l.try_gpu(), TinySSD(num_classes=1)
trainer = torch.optim.SGD(net.parameters(), lr=0.2, weight_decay=5e-4)

14.7.2.2. Defining Loss and Evaluation Functions14.7.2.2 損失関数と評価関数を定義する

Object detection has two types of losses. The first loss concerns classes of anchor boxes: its computation can simply reuse the cross-entropy loss function that we used for image classification. The second loss concerns offsets of positive (non-background) anchor boxes: this is a regression problem. For this regression problem, however, here we do not use the squared loss described in Section 3.1.3. Instead, we use the ℓ1 norm loss, the absolute value of the difference between the prediction and the ground-truth. The mask variable bbox_masks filters out negative anchor boxes and illegal (padded) anchor boxes in the loss calculation. In the end, we sum up the anchor box class loss and the anchor box offset loss to obtain the loss function for the model.
英語のヒント
物体検出には2種類の損失がある。最初の損失はアンカーボックスのクラスにかかわるもので、その計算には、画像分類で使った交差エントロピー損失関数をそのまま再利用できる。2番目の損失は正の(背景でない)アンカーボックスのオフセットにかかわるもので、これは回帰の問題である。しかし、この回帰の問題には、ここでは3.1.3節で説明した2乗損失を使わない。代わりに、予測と正解の差の絶対値であるℓ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
We can use accuracy to evaluate the classification results. Due to the used ℓ1 norm loss for the offsets, we use the mean absolute error to evaluate the predicted bounding boxes. These prediction results are obtained from the generated anchor boxes and the predicted offsets for them.
英語のヒント
分類の結果を評価するには正解率を使える。オフセットにℓ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())

14.7.2.3. Training the Model14.7.2.3 モデルを訓練する

When training the model, we need to generate multiscale anchor boxes (anchors) and predict their classes (cls_preds) and offsets (bbox_preds) in the forward propagation. Then we label the classes (cls_labels) and offsets (bbox_labels) of such generated anchor boxes based on the label information Y. Finally, we calculate the loss function using the predicted and labeled values of the classes and offsets. For concise implementations, evaluation of the test dataset is omitted here.
英語のヒント
モデルを訓練するときは、順伝播で、マルチスケールのアンカーボックス(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