プリンキピア

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

14.1.2. Training with Image Augmentation14.1.2 画像の拡張を使った訓練

Let’s train a model with image augmentation. Here we use the CIFAR-10 dataset instead of the Fashion-MNIST dataset that we used before. This is because the position and size of the objects in the Fashion-MNIST dataset have been normalized, while the color and size of the objects in the CIFAR-10 dataset have more significant differences. The first 32 training images in the CIFAR-10 dataset are shown below.
英語のヒント
画像の拡張を使ってモデルを訓練しよう。ここでは、前に使ったFashion-MNISTのデータセットの代わりに、CIFAR-10のデータセットを使う。Fashion-MNISTのデータセットでは物体の位置と大きさが正規化されているのに対し、CIFAR-10のデータセットでは物体の色と大きさの違いがもっと大きいからである。CIFAR-10のデータセットの最初の32枚の訓練画像を下に示す。
all_images = torchvision.datasets.CIFAR10(train=True, root="../data",
                                          download=True)
d2l.show_images([all_images[i][0] for i in range(32)], 4, 8, scale=0.8);
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ../data/cifar-10-python.tar.gz
100%|██████████| 170498071/170498071 [00:04<00:00, 37716809.52it/s]
Extracting ../data/cifar-10-python.tar.gz to ../data
In order to obtain definitive results during prediction, we usually only apply image augmentation to training examples, and do not use image augmentation with random operations during prediction. Here we only use the simplest random left-right flipping method. In addition, we use a ToTensor instance to convert a minibatch of images into the format required by the deep learning framework, i.e., 32-bit floating point numbers between 0 and 1 with the shape of (batch size, number of channels, height, width).
英語のヒント
予測のときに確定的な結果を得るため、ふつう画像の拡張は訓練事例にだけ当てはめ、予測のときにはランダムな操作を伴う画像の拡張を使わない。ここでは、最も単純なランダムな左右反転の手法だけを使う。さらに、ToTensorインスタンスを使って、画像のミニバッチを深層学習のフレームワークが必要とする形式、つまり0から1のあいだの32ビット浮動小数点数で、形状が(バッチの大きさ、チャネル数、高さ、幅)のものに変換する。
train_augs = torchvision.transforms.Compose([
     torchvision.transforms.RandomHorizontalFlip(),
     torchvision.transforms.ToTensor()])

test_augs = torchvision.transforms.Compose([
     torchvision.transforms.ToTensor()])
Next, we define an auxiliary function to facilitate reading the image and applying image augmentation. The transform argument provided by PyTorch’s dataset applies augmentation to transform the images. For a detailed introduction to DataLoader, please refer to Section 4.2.
英語のヒント
次に、画像を読み、画像の拡張を当てはめるのを容易にする補助関数を定義する。PyTorchのデータセットが与えるtransform引数は、画像を変換するために拡張を当てはめる。DataLoaderの詳しい紹介は4.2節を参照。
def load_cifar10(is_train, augs, batch_size):
    dataset = torchvision.datasets.CIFAR10(root="../data", train=is_train,
                                           transform=augs, download=True)
    dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
                    shuffle=is_train, num_workers=d2l.get_dataloader_workers())
    return dataloader

14.1.2.1. Multi-GPU Training14.1.2.1 複数GPUでの訓練

We train the ResNet-18 model from Section 8.6 on the CIFAR-10 dataset. Recall the introduction to multi-GPU training in Section 13.6. In the following, we define a function to train and evaluate the model using multiple GPUs.
英語のヒント
CIFAR-10のデータセットで8.6節のResNet-18モデルを訓練する。13.6節での複数GPUの訓練の紹介を思い出そう。以下では、複数のGPUを使ってモデルを訓練し評価する関数を定義する。
#@save
def train_batch_ch13(net, X, y, loss, trainer, devices):
    """Train for a minibatch with multiple GPUs (defined in Chapter 13)."""
    if isinstance(X, list):
        # Required for BERT fine-tuning (to be covered later)
        X = [x.to(devices[0]) for x in X]
    else:
        X = X.to(devices[0])
    y = y.to(devices[0])
    net.train()
    trainer.zero_grad()
    pred = net(X)
    l = loss(pred, y)
    l.sum().backward()
    trainer.step()
    train_loss_sum = l.sum()
    train_acc_sum = d2l.accuracy(pred, y)
    return train_loss_sum, train_acc_sum

#@save
def train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
               devices=d2l.try_all_gpus()):
    """Train a model with multiple GPUs (defined in Chapter 13)."""
    timer, num_batches = d2l.Timer(), len(train_iter)
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 1],
                            legend=['train loss', 'train acc', 'test acc'])
    net = nn.DataParallel(net, device_ids=devices).to(devices[0])
    for epoch in range(num_epochs):
        # Sum of training loss, sum of training accuracy, no. of examples,
        # no. of predictions
        metric = d2l.Accumulator(4)
        for i, (features, labels) in enumerate(train_iter):
            timer.start()
            l, acc = train_batch_ch13(
                net, features, labels, loss, trainer, devices)
            metric.add(l, acc, labels.shape[0], labels.numel())
            timer.stop()
            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
                animator.add(epoch + (i + 1) / num_batches,
                             (metric[0] / metric[2], metric[1] / metric[3],
                              None))
        test_acc = d2l.evaluate_accuracy_gpu(net, test_iter)
        animator.add(epoch + 1, (None, None, test_acc))
    print(f'loss {metric[0] / metric[2]:.3f}, train acc '
          f'{metric[1] / metric[3]:.3f}, test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec on '
          f'{str(devices)}')
Now we can define the train_with_data_aug function to train the model with image augmentation. This function gets all available GPUs, uses Adam as the optimization algorithm, applies image augmentation to the training dataset, and finally calls the train_ch13 function just defined to train and evaluate the model.
英語のヒント
これで、画像の拡張を使ってモデルを訓練するtrain_with_data_aug関数を定義できる。この関数は、使えるすべてのGPUを取得し、最適化アルゴリズムとしてAdamを使い、訓練データセットに画像の拡張を当てはめ、最後に、いま定義したtrain_ch13関数を呼び出してモデルを訓練し評価する。
batch_size, devices, net = 256, d2l.try_all_gpus(), d2l.resnet18(10, 3)
net.apply(d2l.init_cnn)

def train_with_data_aug(train_augs, test_augs, net, lr=0.001):
    train_iter = load_cifar10(True, train_augs, batch_size)
    test_iter = load_cifar10(False, test_augs, batch_size)
    loss = nn.CrossEntropyLoss(reduction="none")
    trainer = torch.optim.Adam(net.parameters(), lr=lr)
    net(next(iter(train_iter))[0])
    train_ch13(net, train_iter, test_iter, loss, trainer, 10, devices)
Let’s train the model using image augmentation based on random left-right flipping.
英語のヒント
ランダムな左右反転にもとづく画像の拡張を使って、モデルを訓練しよう。
train_with_data_aug(train_augs, test_augs, net)
loss 0.215, train acc 0.925, test acc 0.810
4728.8 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]