.. _sec_image_augmentation:
画像拡張
========
| :numref:`sec_alexnet`
では、さまざまな応用において深層ニューラルネットワークが成功するための前提条件として、大規模データセットが必要であることを述べた。
| *画像拡張*
は、訓練画像に一連のランダムな変換を施すことで、元の画像に似ているが異なる訓練例を生成し、訓練データセットの規模を拡大する。
| 別の見方をすると、画像拡張は、訓練例に対するランダムな微調整によって、モデルが特定の属性に過度に依存しにくくなり、その結果として汎化能力が向上する、という事実に動機づけられている。
| たとえば、画像をさまざまな方法で切り抜くことで、注目対象が異なる位置に現れるようにでき、これにより対象の位置へのモデルの依存を減らせる。
| また、明るさや色などの要素を調整して、色に対するモデルの感度を下げることもできる。
| 当時の AlexNet の成功には、画像拡張が不可欠だった可能性が高いだろう。
| この節では、コンピュータビジョンで広く使われているこの手法について説明する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
%matplotlib inline
from d2l import torch as d2l
import torch
import torchvision
from torch import nn
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
%matplotlib inline
from d2l import mxnet as d2l
from mxnet import autograd, gluon, image, init, np, npx
from mxnet.gluon import nn
npx.set_np()
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5):
Y = [aug(img) for _ in range(num_rows * num_cols)]
d2l.show_images(Y, num_rows, num_cols, scale=scale)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5):
Y = [aug(img) for _ in range(num_rows * num_cols)]
d2l.show_images(Y, num_rows, num_cols, scale=scale)
.. raw:: html
.. raw:: html
一般的な画像拡張手法
--------------------
一般的な画像拡張手法を調べるにあたり、以下の :math:`400\times 500`
の画像を例として用いる。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.set_figsize()
img = d2l.Image.open('../img/cat1.jpg')
d2l.plt.imshow(img);
.. figure:: output_image-augmentation_5ce40d_18_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.set_figsize()
img = image.imread('../img/cat1.jpg')
d2l.plt.imshow(img.asnumpy());
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
[07:00:45] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU
.. figure:: output_image-augmentation_5ce40d_21_1.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
train_with_data_aug(train_augs, test_augs, net)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
train_with_data_aug(train_augs, test_augs, net)
.. raw:: html
.. raw:: html
多くの画像拡張手法には、ある程度のランダム性がある。画像拡張の効果を観察しやすくするために、まず補助関数
``apply`` を定義する。この関数は、画像拡張手法 ``aug`` を入力画像
``img`` に対して複数回実行し、その結果をすべて表示す。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def apply(img, aug, num_rows=2, num_cols=4, scale=1.5):
Y = [aug(img) for _ in range(num_rows * num_cols)]
d2l.show_images(Y, num_rows, num_cols, scale=scale)
反転と切り抜き
~~~~~~~~~~~~~~
| 画像を左右反転する ことは、通常、対象のカテゴリを変えない。
| これは、最も早くから使われ、かつ最も広く用いられている画像拡張手法の一つである。
| 次に、\ ``transforms`` モジュールを使って ``RandomHorizontalFlip``
のインスタンスを作成する。これは、50% の確率で画像を左右反転する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, torchvision.transforms.RandomHorizontalFlip())
.. figure:: output_image-augmentation_5ce40d_35_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, gluon.data.vision.transforms.RandomFlipLeftRight())
.. figure:: output_image-augmentation_5ce40d_38_0.svg
.. raw:: html
.. raw:: html
| 上下反転する
ことは、左右反転ほど一般的ではない。とはいえ、この例の画像では、上下反転しても認識の妨げにはならない。
| 次に、\ ``RandomVerticalFlip`` のインスタンスを作成し、50%
の確率で画像を上下反転する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, torchvision.transforms.RandomVerticalFlip())
.. figure:: output_image-augmentation_5ce40d_44_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, gluon.data.vision.transforms.RandomFlipTopBottom())
.. figure:: output_image-augmentation_5ce40d_47_0.svg
.. raw:: html
.. raw:: html
| ここで用いた例の画像では猫が画像の中央にいるが、一般にはそうとは限らない。
| :numref:`sec_pooling`
では、プーリング層によって畳み込み層の対象位置に対する感度を下げられることを説明した。
| さらに、画像をランダムに切り抜くことで、対象が画像内の異なる位置や異なるスケールで現れるようにでき、これもモデルの対象位置への感度を下げるのに役立ちる。
| 以下のコードでは、毎回元の面積の :math:`10\% \sim 100\%` の領域を
ランダムに切り抜き、その領域の幅と高さの比を :math:`0.5 \sim 2`
の範囲からランダムに選ぶ。次に、その領域の幅と高さをどちらも 200
ピクセルに拡大縮小する。
| 特に断りがない限り、この節での :math:`a` と :math:`b`
の間の乱数とは、区間 :math:`[a, b]`
から一様分布に従ってランダムサンプリングされた連続値を指す。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
shape_aug = torchvision.transforms.RandomResizedCrop(
(200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)
.. figure:: output_image-augmentation_5ce40d_53_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
shape_aug = gluon.data.vision.transforms.RandomResizedCrop(
(200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)
.. figure:: output_image-augmentation_5ce40d_56_0.svg
.. raw:: html
.. raw:: html
色の変更
~~~~~~~~
別の拡張手法として、色を変更する方法がある。画像の色に関して、明るさ、コントラスト、彩度、色相の
4 つの側面を変更できる。以下の例では、画像の 明るさをランダムに変更
し、元の画像の 50% (:math:`1-0.5`) から 150% (:math:`1+0.5`)
の範囲の値にする。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, torchvision.transforms.ColorJitter(
brightness=0.5, contrast=0, saturation=0, hue=0))
.. figure:: output_image-augmentation_5ce40d_62_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, gluon.data.vision.transforms.RandomBrightness(0.5))
.. figure:: output_image-augmentation_5ce40d_65_0.svg
.. raw:: html
.. raw:: html
同様に、画像の 色相をランダムに変更 することもできる。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, torchvision.transforms.ColorJitter(
brightness=0, contrast=0, saturation=0, hue=0.5))
.. figure:: output_image-augmentation_5ce40d_71_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
apply(img, gluon.data.vision.transforms.RandomHue(0.5))
.. figure:: output_image-augmentation_5ce40d_74_0.svg
.. raw:: html
.. raw:: html
また、\ ``RandomColorJitter`` のインスタンスを作成し、画像の
``brightness``\ 、\ ``contrast``\ 、\ ``saturation``\ 、\ ``hue`` を
同時にランダム変更する方法 を設定することもできる。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
color_aug = torchvision.transforms.ColorJitter(
brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
apply(img, color_aug)
.. figure:: output_image-augmentation_5ce40d_80_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
color_aug = gluon.data.vision.transforms.RandomColorJitter(
brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
apply(img, color_aug)
.. figure:: output_image-augmentation_5ce40d_83_0.svg
.. raw:: html
.. raw:: html
複数の画像拡張手法の組み合わせ
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| 実際には、複数の画像拡張手法を組み合わせる ことがよくある。
| たとえば、上で定義したさまざまな画像拡張手法を組み合わせ、\ ``Compose``
インスタンスを通して各画像に適用できる。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
augs = torchvision.transforms.Compose([
torchvision.transforms.RandomHorizontalFlip(), color_aug, shape_aug])
apply(img, augs)
.. figure:: output_image-augmentation_5ce40d_89_0.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
augs = gluon.data.vision.transforms.Compose([
gluon.data.vision.transforms.RandomFlipLeftRight(), color_aug, shape_aug])
apply(img, augs)
.. figure:: output_image-augmentation_5ce40d_92_0.svg
.. raw:: html
.. raw:: html
画像拡張を用いた学習
--------------------
| 画像拡張を用いてモデルを学習してみよう。
| ここでは、以前使った Fashion-MNIST データセットの代わりに CIFAR-10
データセットを使う。
| これは、Fashion-MNIST
データセットでは対象の位置とサイズが正規化されている一方、CIFAR-10
データセットでは対象の色とサイズにより大きな違いがあるためである。
| CIFAR-10 データセットの最初の 32 個の訓練画像を以下に示す。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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);
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ../data/cifar-10-python.tar.gz
100%|██████████| 170498071/170498071 [02:37<00:00, 1084703.38it/s]
Extracting ../data/cifar-10-python.tar.gz to ../data
.. figure:: output_image-augmentation_5ce40d_98_1.svg
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
d2l.show_images(gluon.data.vision.CIFAR10(
train=True)[:32][0], 4, 8, scale=0.8);
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
Downloading /opt/mxnet/datasets/cifar10/cifar-10-binary.tar.gz from https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/dataset/cifar10/cifar-10-binary.tar.gz...
.. figure:: output_image-augmentation_5ce40d_101_1.svg
.. raw:: html
.. raw:: html
| 予測時に確定的な結果を得るため、通常は画像拡張を訓練例にのみ適用し、予測時にはランダム操作を伴う画像拡張を使わない。
| ここでは最も単純な左右反転のランダム拡張のみを使う。さらに、\ ``ToTensor``
インスタンスを使って画像のミニバッチを深層学習フレームワークが要求する形式、すなわち
| 形状が (バッチサイズ, チャネル数, 高さ, 幅) で、0 から 1 の間の 32
ビット浮動小数点数に変換する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
train_augs = torchvision.transforms.Compose([
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor()])
test_augs = torchvision.transforms.Compose([
torchvision.transforms.ToTensor()])
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
train_augs = gluon.data.vision.transforms.Compose([
gluon.data.vision.transforms.RandomFlipLeftRight(),
gluon.data.vision.transforms.ToTensor()])
test_augs = gluon.data.vision.transforms.Compose([
gluon.data.vision.transforms.ToTensor()])
.. raw:: html
.. raw:: html
| 次に、画像の読み込みと画像拡張の適用を容易にする 補助関数を定義する。
| PyTorch のデータセットが提供する ``transform``
引数は、画像を変換する際に拡張を適用する。
| ``DataLoader`` の詳細な説明については、 :numref:`sec_fashion_mnist`
を参照しよ。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
def load_cifar10(is_train, augs, batch_size):
return gluon.data.DataLoader(
gluon.data.vision.CIFAR10(train=is_train).transform_first(augs),
batch_size=batch_size, shuffle=is_train,
num_workers=d2l.get_dataloader_workers())
.. raw:: html
.. raw:: html
マルチ GPU 学習
~~~~~~~~~~~~~~~
| :numref:`sec_resnet` の ResNet-18 モデルを CIFAR-10
データセットで学習する。
| :numref:`sec_multi_gpu_concise` におけるマルチ GPU
学習の説明を思い出してほしい。
| 以下では、複数の GPU を使ってモデルを学習・評価する関数を定義する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
#@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
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
#@save
def train_batch_ch13(net, features, labels, loss, trainer, devices,
split_f=d2l.split_batch):
"""Train for a minibatch with multiple GPUs (defined in Chapter 13)."""
X_shards, y_shards = split_f(features, labels, devices)
with autograd.record():
pred_shards = [net(X_shard) for X_shard in X_shards]
ls = [loss(pred_shard, y_shard) for pred_shard, y_shard
in zip(pred_shards, y_shards)]
for l in ls:
l.backward()
# The `True` flag allows parameters with stale gradients, which is useful
# later (e.g., in fine-tuning BERT)
trainer.step(labels.shape[0], ignore_stale_grad=True)
train_loss_sum = sum([float(l.sum()) for l in ls])
train_acc_sum = sum(d2l.accuracy(pred_shard, y_shard)
for pred_shard, y_shard in zip(pred_shards, y_shards))
return train_loss_sum, train_acc_sum
.. raw:: html
.. raw:: html
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
#@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)}')
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
#@save
def train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
devices=d2l.try_all_gpus(), split_f=d2l.split_batch):
"""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'])
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, split_f)
metric.add(l, acc, labels.shape[0], labels.size)
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_gpus(net, test_iter, split_f)
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)}')
.. raw:: html
.. raw:: html
| ここで、画像拡張を用いてモデルを学習する ``train_with_data_aug``
関数を定義する。
| この関数は利用可能なすべての GPU を取得し、最適化アルゴリズムとして
Adam を使い、訓練データセットに画像拡張を適用し、最後に先ほど定義した
``train_ch13`` 関数を呼び出してモデルを学習・評価する。
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
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)
.. raw:: html
.. raw:: html
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
batch_size, devices, net = 256, d2l.try_all_gpus(), d2l.resnet18(10)
net.initialize(init=init.Xavier(), ctx=devices)
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 = gluon.loss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'adam',
{'learning_rate': lr})
train_ch13(net, train_iter, test_iter, loss, trainer, 10, devices)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
[07:00:57] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for GPU
[07:00:57] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for GPU
.. raw:: html
.. raw:: html
それでは、ランダム左右反転に基づく画像拡張を用いて モデルを学習
してみよう。
.. raw:: latex
\diilbookstyleinputcell
.. code:: python
train_with_data_aug(train_augs, test_augs, net)
.. raw:: latex
\diilbookstyleoutputcell
.. parsed-literal::
:class: output
loss 0.231, train acc 0.921, test acc 0.836
4857.3 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]
.. figure:: output_image-augmentation_5ce40d_149_1.svg
まとめ
------
- 画像拡張は、既存の訓練データに基づいてランダムな画像を生成し、モデルの汎化能力を向上させる。
- 予測時に確定的な結果を得るため、通常は画像拡張を訓練例にのみ適用し、予測時にはランダム操作を伴う画像拡張を使わない。
- 深層学習フレームワークは、同時に適用できる多様な画像拡張手法を提供している。
演習
----
1. 画像拡張を使わずにモデルを学習せよ:
``train_with_data_aug(test_augs, test_augs)``.
画像拡張を使う場合と使わない場合の訓練精度とテスト精度を比較しよ。この比較実験は、画像拡張が過学習を緩和できるという主張を支持できるか。なぜか。
2. CIFAR-10
データセットでのモデル学習に、複数の異なる画像拡張手法を組み合わせよ。テスト精度は向上するか。
3. 深層学習フレームワークのオンラインドキュメントを参照しよ。ほかにどのような画像拡張手法が提供されているか。