20.1  图像增广

7.1 节 提到过大型数据集是成功应用深度神经网络的先决条件。图像增广在对训练图像进行一系列的随机变化之后,生成相似但不同的训练样本,从而扩大了训练集的规模。此外,应用图像增广的原因是,随机改变训练样本可以减少模型对某些属性的依赖,从而提高模型的泛化能力。例如,我们可以以不同的方式裁剪图像,使感兴趣的对象出现在不同的位置,减少模型对于对象出现位置的依赖。我们还可以调整亮度、颜色等因素来降低模型对颜色的敏感度。可以说,图像增广技术对于 AlexNet 的成功是必不可少的。本节将讨论这项广泛应用于计算机视觉的技术。

# cuDNN's convolution autotuner allocates large transient scratch buffers when
# the input's batch dimension is dynamic -- here the tf.data loader yields a
# variable-size final batch -- spiking the reserved footprint to ~8.6 GiB for
# this ResNet-18 / batch-256 training step. Disabling autotuning falls back to
# cuDNN's default low-memory algorithm (same result), and we cap the workspace
# as a backstop; the true footprint drops to ~4.5 GiB. TensorFlow reads these
# variables when it starts cuDNN, so this cell runs before the imports.
import os
os.environ['TF_CUDNN_USE_AUTOTUNE'] = '0'
os.environ['TF_CUDNN_WORKSPACE_LIMIT_IN_MB'] = '2048'
# Disable XLA's convolution autotuning. For this ResNet-18 / batch-256 training
# step the autotuner selects algorithms whose scratch reserves ~8.1 GiB of GPU
# memory; the default (non-tuned) algorithm computes exactly the same result
# with far less workspace (~3 GiB true footprint). JAX reads XLA_FLAGS once,
# when it starts, so this cell runs before the imports.
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
                           ' --xla_gpu_autotune_level=0').strip()
import torchvision
import warnings
import keras
from PIL import Image
import tensorflow as tf
from mxnet import image
warnings.filterwarnings('ignore', message='.*dtype.*align.*',
                        category=np.exceptions.VisibleDeprecationWarning)

20.1.1 常用的图像增广方法

在探索常用图像增广方法时,我们将使用下面这张尺寸为 \(400\times 500\) 的图像作为示例。

d2l.set_figsize()
img = d2l.Image.open('../img/cat1.jpg')
d2l.plt.imshow(img);

d2l.set_figsize()
img = Image.open('../img/cat1.jpg')
d2l.plt.imshow(img);

from PIL import Image
d2l.set_figsize()
img = Image.open('../img/cat1.jpg')
d2l.plt.imshow(img);

d2l.set_figsize()
img = image.imread('../img/cat1.jpg')
d2l.plt.imshow(img.asnumpy());

大多数图像增广方法都具有一定的随机性。为了便于观察图像增广的效果,我们下面定义辅助函数 apply。此函数在输入图像 img 上多次运行图像增广方法 aug 并显示所有结果。

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)

20.1.1.1 翻转和裁剪

左右翻转图像通常不会改变目标的类别,是最早且最广泛使用的图像增广方法之一。接下来,我们使用 transforms 模块创建 RandomHorizontalFlip 实例,以 50% 的概率将图像左右翻转。

左右翻转图像通常不会改变目标的类别,是最早且最广泛使用的图像增广方法之一。接下来,我们使用 tf.image 定义 RandomHorizontalFlip 函数,以 50% 的概率将图像左右翻转,并按需在 PIL 图像与 TensorFlow 张量之间转换。

左右翻转图像通常不会改变目标的类别,是最早且最广泛使用的图像增广方法之一。接下来,我们使用 tf.image 定义 RandomHorizontalFlip 函数,以 50% 的概率将图像左右翻转,并按需在 PIL 图像与 TensorFlow 张量之间转换。

左右翻转图像通常不会改变目标的类别,是最早且最广泛使用的图像增广方法之一。接下来,我们使用 transforms 模块创建 RandomFlipLeftRight 实例,以 50% 的概率将图像左右翻转。

apply(img, torchvision.transforms.RandomHorizontalFlip())

def RandomHorizontalFlip():
    def aug(img):
        img_tf = tf.constant(np.array(img))
        img_tf = tf.image.random_flip_left_right(img_tf)
        return Image.fromarray(img_tf.numpy())
    return aug

apply(img, RandomHorizontalFlip())

def RandomHorizontalFlip():
    def aug(img):
        img_tf = tf.constant(np.array(img))
        img_tf = tf.image.random_flip_left_right(img_tf)
        return Image.fromarray(img_tf.numpy())
    return aug

apply(img, RandomHorizontalFlip())

apply(img, gluon.data.vision.transforms.RandomFlipLeftRight())

上下翻转不如左右翻转常见,但至少对于这张示例图像而言,上下翻转并不会妨碍识别。接下来,我们创建 RandomVerticalFlip 实例,以 50% 的概率将图像上下翻转。

上下翻转不如左右翻转常见,但至少对于这张示例图像而言,上下翻转并不会妨碍识别。接下来,我们定义 RandomVerticalFlip 函数,以 50% 的概率将图像上下翻转。

上下翻转不如左右翻转常见,但至少对于这张示例图像而言,上下翻转并不会妨碍识别。接下来,我们定义 RandomVerticalFlip 函数,以 50% 的概率将图像上下翻转。

上下翻转不如左右翻转常见,但至少对于这张示例图像而言,上下翻转并不会妨碍识别。接下来,我们创建 RandomFlipTopBottom 实例,以 50% 的概率将图像上下翻转。

apply(img, torchvision.transforms.RandomVerticalFlip())

def RandomVerticalFlip():
    def aug(img):
        img_tf = tf.constant(np.array(img))
        img_tf = tf.image.random_flip_up_down(img_tf)
        return Image.fromarray(img_tf.numpy())
    return aug

apply(img, RandomVerticalFlip())

def RandomVerticalFlip():
    def aug(img):
        img_tf = tf.constant(np.array(img))
        img_tf = tf.image.random_flip_up_down(img_tf)
        return Image.fromarray(img_tf.numpy())
    return aug

apply(img, RandomVerticalFlip())

apply(img, gluon.data.vision.transforms.RandomFlipTopBottom())

在我们使用的示例图像中,猫位于图像的中间,但并非所有图像都是这样。在 6.5 节 中,我们解释了汇聚层可以降低卷积层对目标位置的敏感性。另外,我们可以通过对图像进行随机裁剪,使物体以不同的比例出现在图像的不同位置。这也可以降低模型对目标位置的敏感性。

下面的代码每次随机裁剪一块面积为原面积 \(10\% \sim 100\%\) 的区域,且该区域的宽高比从 \(0.5 \sim 2\) 中随机抽取,随后将该区域的宽和高都缩放到 200 像素。除非另有说明,本节中 \(a\) 和 \(b\) 之间的随机数均指在区间 \([a, b]\) 上均匀随机采样得到的连续值。

shape_aug = torchvision.transforms.RandomResizedCrop(
    (200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)

def RandomResizedCrop(size, scale=(0.1, 1), ratio=(0.5, 2)):
    target_h, target_w = size
    def aug(img):
        img_tf = tf.constant(np.array(img))
        h, w = tf.shape(img_tf)[0], tf.shape(img_tf)[1]
        area = tf.cast(h * w, tf.float32)
        log_ratio = (tf.math.log(float(ratio[0])), tf.math.log(float(ratio[1])))
        target_area = tf.random.uniform([], scale[0], scale[1]) * area
        aspect = tf.exp(tf.random.uniform([], log_ratio[0], log_ratio[1]))
        crop_h = tf.cast(tf.round(tf.sqrt(target_area / aspect)), tf.int32)
        crop_w = tf.cast(tf.round(tf.sqrt(target_area * aspect)), tf.int32)
        crop_h = tf.minimum(crop_h, h)
        crop_w = tf.minimum(crop_w, w)
        offset_h = tf.random.uniform([], 0, h - crop_h + 1, dtype=tf.int32)
        offset_w = tf.random.uniform([], 0, w - crop_w + 1, dtype=tf.int32)
        img_tf = tf.image.crop_to_bounding_box(img_tf, offset_h, offset_w,
                                                crop_h, crop_w)
        img_tf = tf.cast(img_tf, tf.float32)
        img_tf = tf.image.resize(img_tf, [target_h, target_w])
        img_tf = tf.cast(img_tf, tf.uint8)
        return Image.fromarray(img_tf.numpy())
    return aug

shape_aug = RandomResizedCrop((200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)

def RandomResizedCrop(size, scale=(0.1, 1), ratio=(0.5, 2)):
    target_h, target_w = size
    def aug(img):
        img_tf = tf.constant(np.array(img))
        h, w = tf.shape(img_tf)[0], tf.shape(img_tf)[1]
        area = tf.cast(h * w, tf.float32)
        log_ratio = (tf.math.log(float(ratio[0])), tf.math.log(float(ratio[1])))
        target_area = tf.random.uniform([], scale[0], scale[1]) * area
        aspect = tf.exp(tf.random.uniform([], log_ratio[0], log_ratio[1]))
        crop_h = tf.cast(tf.round(tf.sqrt(target_area / aspect)), tf.int32)
        crop_w = tf.cast(tf.round(tf.sqrt(target_area * aspect)), tf.int32)
        crop_h = tf.minimum(crop_h, h)
        crop_w = tf.minimum(crop_w, w)
        offset_h = tf.random.uniform([], 0, h - crop_h + 1, dtype=tf.int32)
        offset_w = tf.random.uniform([], 0, w - crop_w + 1, dtype=tf.int32)
        img_tf = tf.image.crop_to_bounding_box(img_tf, offset_h, offset_w,
                                                crop_h, crop_w)
        img_tf = tf.cast(img_tf, tf.float32)
        img_tf = tf.image.resize(img_tf, [target_h, target_w])
        img_tf = tf.cast(img_tf, tf.uint8)
        return Image.fromarray(img_tf.numpy())
    return aug

shape_aug = RandomResizedCrop((200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)

shape_aug = gluon.data.vision.transforms.RandomResizedCrop(
    (200, 200), scale=(0.1, 1), ratio=(0.5, 2))
apply(img, shape_aug)

20.1.1.2 改变颜色

另一类增广方法是改变颜色。我们可以调整图像颜色的四个方面:亮度、对比度、饱和度和色调。在下面的示例中,我们将图像亮度随机改变最多 0.5。

亮度被随机缩放到原图的 50%(\(1-0.5\))至 150%(\(1+0.5\))之间。

tf.image.random_brightness 向 \([0, 1]\) 范围内的像素值加上 \([-0.5, 0.5]\) 内的随机偏移量,因此属于加性调整而非乘性缩放。

tf.image.random_brightness 向 \([0, 1]\) 范围内的像素值加上 \([-0.5, 0.5]\) 内的随机偏移量,因此属于加性调整而非乘性缩放。

亮度被随机缩放到原图的 50%(\(1-0.5\))至 150%(\(1+0.5\))之间。

apply(img, torchvision.transforms.ColorJitter(
    brightness=0.5, contrast=0, saturation=0, hue=0))

def RandomBrightness(max_delta):
    def aug(img):
        img_tf = tf.cast(tf.constant(np.array(img)), tf.float32) / 255.0
        img_tf = tf.image.random_brightness(img_tf, max_delta)
        img_tf = tf.clip_by_value(img_tf, 0.0, 1.0)
        return Image.fromarray((img_tf.numpy() * 255).astype(np.uint8))
    return aug

apply(img, RandomBrightness(0.5))

def RandomBrightness(max_delta):
    def aug(img):
        img_tf = tf.cast(tf.constant(np.array(img)), tf.float32) / 255.0
        img_tf = tf.image.random_brightness(img_tf, max_delta)
        img_tf = tf.clip_by_value(img_tf, 0.0, 1.0)
        return Image.fromarray((img_tf.numpy() * 255).astype(np.uint8))
    return aug

apply(img, RandomBrightness(0.5))

apply(img, gluon.data.vision.transforms.RandomBrightness(0.5))

类似地,我们可以随机更改图像的色调。

apply(img, torchvision.transforms.ColorJitter(
    brightness=0, contrast=0, saturation=0, hue=0.5))

def RandomHue(max_delta):
    def aug(img):
        img_tf = tf.cast(tf.constant(np.array(img)), tf.float32) / 255.0
        img_tf = tf.image.random_hue(img_tf, max_delta)
        img_tf = tf.clip_by_value(img_tf, 0.0, 1.0)
        return Image.fromarray((img_tf.numpy() * 255).astype(np.uint8))
    return aug

apply(img, RandomHue(0.5))

def RandomHue(max_delta):
    def aug(img):
        img_tf = tf.cast(tf.constant(np.array(img)), tf.float32) / 255.0
        img_tf = tf.image.random_hue(img_tf, max_delta)
        img_tf = tf.clip_by_value(img_tf, 0.0, 1.0)
        return Image.fromarray((img_tf.numpy() * 255).astype(np.uint8))
    return aug

apply(img, RandomHue(0.5))

apply(img, gluon.data.vision.transforms.RandomHue(0.5))

我们还可以创建颜色抖动变换,设置如何同时随机更改图像的亮度(brightness)、对比度(contrast)、饱和度(saturation)和色调(hue)。

color_aug = torchvision.transforms.ColorJitter(
    brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
apply(img, color_aug)

def RandomColorJitter(brightness=0, contrast=0, saturation=0, hue=0):
    def aug(img):
        img_tf = tf.cast(tf.constant(np.array(img)), tf.float32) / 255.0
        if brightness > 0:
            img_tf = tf.image.random_brightness(img_tf, brightness)
        if contrast > 0:
            img_tf = tf.image.random_contrast(img_tf, 1 - contrast,
                                              1 + contrast)
        if saturation > 0:
            img_tf = tf.image.random_saturation(img_tf, 1 - saturation,
                                                1 + saturation)
        if hue > 0:
            img_tf = tf.image.random_hue(img_tf, hue)
        img_tf = tf.clip_by_value(img_tf, 0.0, 1.0)
        return Image.fromarray((img_tf.numpy() * 255).astype(np.uint8))
    return aug

color_aug = RandomColorJitter(brightness=0.5, contrast=0.5, saturation=0.5,
                              hue=0.5)
apply(img, color_aug)

def RandomColorJitter(brightness=0, contrast=0, saturation=0, hue=0):
    def aug(img):
        img_tf = tf.cast(tf.constant(np.array(img)), tf.float32) / 255.0
        if brightness > 0:
            img_tf = tf.image.random_brightness(img_tf, brightness)
        if contrast > 0:
            img_tf = tf.image.random_contrast(img_tf, 1 - contrast,
                                              1 + contrast)
        if saturation > 0:
            img_tf = tf.image.random_saturation(img_tf, 1 - saturation,
                                                1 + saturation)
        if hue > 0:
            img_tf = tf.image.random_hue(img_tf, hue)
        img_tf = tf.clip_by_value(img_tf, 0.0, 1.0)
        return Image.fromarray((img_tf.numpy() * 255).astype(np.uint8))
    return aug

color_aug = RandomColorJitter(brightness=0.5, contrast=0.5, saturation=0.5,
                              hue=0.5)
apply(img, color_aug)

color_aug = gluon.data.vision.transforms.RandomColorJitter(
    brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)
apply(img, color_aug)

20.1.1.3 结合多种图像增广方法

在实践中,我们通常会组合多种图像增广方法。例如,可以通过 Compose 实例将上面定义的不同图像增广方法串联起来,依次应用到每张图像上。

augs = torchvision.transforms.Compose([
    torchvision.transforms.RandomHorizontalFlip(), color_aug, shape_aug])
apply(img, augs)

def Compose(transforms):
    def aug(img):
        for t in transforms:
            img = t(img)
        return img
    return aug

augs = Compose([RandomHorizontalFlip(), color_aug, shape_aug])
apply(img, augs)

def Compose(transforms):
    def aug(img):
        for t in transforms:
            img = t(img)
        return img
    return aug

augs = Compose([RandomHorizontalFlip(), color_aug, shape_aug])
apply(img, augs)

augs = gluon.data.vision.transforms.Compose([
    gluon.data.vision.transforms.RandomFlipLeftRight(), color_aug, shape_aug])
apply(img, augs)

20.1.2 使用图像增广进行训练

让我们使用图像增广来训练模型。这里,我们使用 CIFAR-10 数据集,而不是我们之前使用的 Fashion-MNIST 数据集。这是因为 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);

(train_images, train_labels), _ = keras.datasets.cifar10.load_data()
d2l.show_images([Image.fromarray(train_images[i]) for i in range(32)],
                4, 8, scale=0.8);

(train_images, train_labels), _ = tf.keras.datasets.cifar10.load_data()
d2l.show_images([Image.fromarray(train_images[i]) for i in range(32)],
                4, 8, scale=0.8);

d2l.show_images(gluon.data.vision.CIFAR10(
    train=True)[:32][0], 4, 8, scale=0.8);

为了在预测阶段得到确定性的结果,通常只对训练样本应用图像增广,而在预测阶段不使用带随机操作的图像增广。这里我们仅使用最简单的随机左右翻转;此外,还将小批量图像转换为深度学习框架所需的格式,即取值在 0 到 1 之间的 32 位浮点数。

ToTensor 实例完成这一数值转换,并将张量形状调整为(批量大小,通道数,高度,宽度)。

我们将图像转换为 32 位浮点数并除以 255,张量保持通道在后的形状(批量大小,高度,宽度,通道数)。

我们将图像转换为 32 位浮点数并除以 255,张量保持通道在后的形状(批量大小,高度,宽度,通道数)。

ToTensor 实例完成这一数值转换,并将张量形状调整为(批量大小,通道数,高度,宽度)。

train_augs = torchvision.transforms.Compose([
     torchvision.transforms.RandomHorizontalFlip(),
     torchvision.transforms.ToTensor()])

test_augs = torchvision.transforms.Compose([
     torchvision.transforms.ToTensor()])
def train_augs(image, label):
    image = tf.cast(image, tf.float32) / 255.0
    image = tf.image.random_flip_left_right(image)
    return image, label

def test_augs(image, label):
    image = tf.cast(image, tf.float32) / 255.0
    return image, label
def train_augs(image, label):
    image = tf.cast(image, tf.float32) / 255.0
    image = tf.image.random_flip_left_right(image)
    return image, label

def test_augs(image, label):
    image = tf.cast(image, tf.float32) / 255.0
    return image, label
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()])

接下来定义一个辅助函数,以便读取图像并应用图像增广。PyTorch 数据集提供的 transform 参数负责应用图像增广变换图像;有关 DataLoader 的详细介绍见 3.2 节。

接下来定义一个辅助函数,以便读取图像并应用图像增广。我们使用 keras.datasets 加载 CIFAR-10,并用 tf.data.Dataset 进行分批与预处理;有关数据加载的详细介绍见 3.2 节。

接下来定义一个辅助函数,以便读取图像并应用图像增广。我们使用 tf.keras.datasets 加载 CIFAR-10,用 tf.data.Dataset 完成分批,再通过 as_numpy_iterator() 将每批数据转换为 NumPy 数组供 JAX 使用;有关数据加载的详细介绍见 3.2 节。

接下来,我们定义了一个辅助函数,以便于读取图像和应用图像增广。Gluon 数据集提供的 transform_first 函数将图像增广应用于每个训练样本的第一个元素(由图像和标签组成),即应用在图像上。有关 DataLoader 的详细介绍,请参阅 3.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
def load_cifar10(is_train, aug_fn, batch_size):
    (train_imgs, train_lbls), (test_imgs, test_lbls) = (
        keras.datasets.cifar10.load_data())
    if is_train:
        images, labels = train_imgs, train_lbls.squeeze()
    else:
        images, labels = test_imgs, test_lbls.squeeze()
    ds = tf.data.Dataset.from_tensor_slices((images, labels))
    if is_train:
        ds = ds.shuffle(10000)
    ds = ds.map(aug_fn, num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
    return ds
def load_cifar10(is_train, aug_fn, batch_size):
    (train_imgs, train_lbls), (test_imgs, test_lbls) = (
        tf.keras.datasets.cifar10.load_data())
    if is_train:
        images, labels = train_imgs, train_lbls.squeeze()
    else:
        images, labels = test_imgs, test_lbls.squeeze()
    ds = tf.data.Dataset.from_tensor_slices((images, labels))
    if is_train:
        ds = ds.shuffle(10000)
    ds = ds.map(aug_fn, num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.batch(batch_size).prefetch(tf.data.AUTOTUNE)
    return ds
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())

20.1.2.1 在可用设备上进行训练

我们在 CIFAR-10 数据集上训练 7.4 节 中的 ResNet-18 模型。回顾 13.6 节 对多 GPU 训练的介绍,下面定义一个在可用设备上训练和评估模型的函数。

网络封装在 nn.DataParallel 中,自动将每个小批量切分到所有可用 GPU 上。

训练在单个设备上运行。

训练在单个设备上运行。

每个小批量通过 split_batch 切分到所有可用 GPU 上。

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() if l.numel() > 1 else l * y.numel()
    train_acc_sum = d2l.accuracy(pred, y)
    return train_loss_sum, train_acc_sum

def train_batch_ch13(net, X, y, loss, optimizer):
    """Train for a minibatch with Keras (defined in Chapter 13)."""
    with tf.GradientTape() as tape:
        pred = net(X, training=True)
        l = loss(y, pred)
    grads = tape.gradient(l, net.trainable_variables)
    optimizer.apply_gradients(zip(grads, net.trainable_variables))
    train_loss_sum = tf.reduce_sum(l)
    train_acc_sum = tf.reduce_sum(
        tf.cast(tf.argmax(pred, axis=1) == tf.cast(y, tf.int64), tf.float32))
    return train_loss_sum, train_acc_sum

@nnx.jit
def train_batch_ch13(net, optimizer, X, y):
    """Train for a minibatch with JAX (defined in Chapter 13)."""
    def compute_loss(model):
        logits = model(X)
        loss = optax.softmax_cross_entropy_with_integer_labels(
            logits, y).mean()
        return loss, logits
    (loss, logits), grads = nnx.value_and_grad(
        compute_loss, has_aux=True)(net)
    optimizer.update(net, grads)
    train_loss_sum = loss * X.shape[0]
    train_acc_sum = (logits.argmax(axis=-1) == y).sum()
    return train_loss_sum, train_acc_sum

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). `1` (not `labels.shape[0]`) so that
    # the summed gradient is applied without rescaling.
    trainer.step(1, 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
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 examples
        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)}')

def train_ch13(net, train_iter, test_iter, loss, optimizer, num_epochs):
    """Train a model with Keras (defined in Chapter 13)."""
    num_batches = sum(1 for _ in train_iter)
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 1],
                            legend=['train loss', 'train acc', 'test acc'])
    timer = d2l.Timer()
    for epoch in range(num_epochs):
        # Sum of training loss, sum of training accuracy, no. of examples,
        # no. of examples
        metric = d2l.Accumulator(4)
        for i, (features, labels) in enumerate(train_iter):
            timer.start()
            l, acc = train_batch_ch13(net, features, labels, loss, optimizer)
            n = features.shape[0]
            metric.add(float(l), float(acc), n, n)
            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))
        # Evaluate on test set
        correct, total = 0, 0
        for X, y in test_iter:
            logits = net(X, training=False)
            correct += int(tf.reduce_sum(tf.cast(
                tf.argmax(logits, axis=1) == tf.cast(y, tf.int64),
                tf.float32)))
            total += y.shape[0]
        test_acc = correct / total
        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')

def train_ch13(net, train_iter, test_iter, optimizer, num_epochs):
    """Train a model with JAX (defined in Chapter 13)."""
    num_batches = int(train_iter.cardinality().numpy())
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0, 1],
                            legend=['train loss', 'train acc', 'test acc'])
    timer = d2l.Timer()

    train_net = nnx.view(net, use_running_average=False,
                         raise_if_not_found=False)
    eval_net = nnx.view(net, use_running_average=True,
                        raise_if_not_found=False)

    @nnx.jit
    def eval_step(model, X):
        return model(X)

    for epoch in range(num_epochs):
        # Sum of training loss, sum of training accuracy, no. of examples,
        # no. of examples
        loss_sum = jnp.array(0.0)
        train_correct = jnp.array(0.0)
        num_examples = 0
        timer.start()
        for i, (features, labels) in enumerate(
                train_iter.as_numpy_iterator()):
            l, acc = train_batch_ch13(
                train_net, optimizer, jnp.array(features), jnp.array(labels))
            n = features.shape[0]
            loss_sum += l
            train_correct += acc
            num_examples += n
        # One transfer per epoch also waits for all dispatched training work,
        # keeping the throughput measurement meaningful without synchronizing
        # every minibatch.
        loss_sum, train_correct = jax.device_get((loss_sum, train_correct))
        timer.stop()
        # Evaluate on test set
        correct, total = jnp.array(0), 0
        for X, y in test_iter.as_numpy_iterator():
            logits = eval_step(eval_net, jnp.array(X))
            correct += (logits.argmax(axis=-1) == y).sum()
            total += y.shape[0]
        correct = int(jax.device_get(correct))
        train_loss = float(loss_sum) / num_examples
        train_acc = float(train_correct) / num_examples
        test_acc = correct / total
        animator.add(epoch + 1, (train_loss, train_acc, test_acc))
    print(f'loss {train_loss:.3f}, train acc '
          f'{train_acc:.3f}, test acc {test_acc:.3f}')
    print(f'{num_examples * num_epochs / timer.sum():.1f} examples/sec')
    return net

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 examples
        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)}')

现在可以定义 train_with_data_aug 函数,使用图像增广训练模型。该函数以 Adam 为优化算法,将图像增广应用于训练集,最后调用刚刚定义的 train_ch13 函数训练并评估模型。

该代码单元还通过 d2l.try_all_gpus() 收集所有可用 GPU 并传给 train_ch13。

该代码单元还通过 d2l.try_all_gpus() 收集所有可用 GPU 并传给 train_ch13。

batch_size, devices, net = 256, d2l.try_all_gpus(), d2l.resnet18(10, 3)

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)
    train_ch13(net, train_iter, test_iter, loss, trainer, 10, devices)
batch_size = 256

def get_net_tf():
    return d2l.resnet18(10, 3)

def train_with_data_aug(train_aug_fn, test_aug_fn, net, lr=0.001):
    train_iter = load_cifar10(True, train_aug_fn, batch_size)
    test_iter = load_cifar10(False, test_aug_fn, batch_size)
    loss = keras.losses.SparseCategoricalCrossentropy(
        from_logits=True, reduction='none')
    optimizer = keras.optimizers.Adam(learning_rate=lr)
    train_ch13(net, train_iter, test_iter, loss, optimizer, 10)

net = get_net_tf()
batch_size = 256
net = d2l.resnet18(10, 3, rngs=nnx.Rngs(d2l.get_key()))

def train_with_data_aug(train_aug_fn, test_aug_fn, net, lr=0.001):
    train_iter = load_cifar10(True, train_aug_fn, batch_size)
    test_iter = load_cifar10(False, test_aug_fn, batch_size)
    optimizer = nnx.Optimizer(net, optax.adam(lr), wrt=nnx.Param)
    train_ch13(net, train_iter, test_iter, optimizer, 10)
batch_size, devices, net = 256, d2l.try_all_gpus(), d2l.resnet18(10)
net.initialize(init=init.MSRAPrelu('in', 0), device=devices)  # He initialization

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)

下面使用基于随机左右翻转的图像增广来训练模型。

train_with_data_aug(train_augs, test_augs, net)
loss 0.166, train acc 0.942, test acc 0.830
7182.4 examples/sec on [device(type='cuda', index=0)]

loss 0.166, train acc 0.943, test acc 0.840
673.5 examples/sec

loss 0.169, train acc 0.942, test acc 0.832
6170.6 examples/sec

loss 0.167, train acc 0.943, test acc 0.821
1239.8 examples/sec on [gpu(0)]

20.1.3 小结

  • 图像增广基于现有的训练数据生成随机图像,来提高模型的泛化能力。
  • 为了在预测过程中得到确切的结果,我们通常对训练样本只进行图像增广,而在预测过程中不使用带随机操作的图像增广。
  • 深度学习框架提供了许多不同的图像增广方法,这些方法可以被同时应用。

20.1.4 练习

  1. 在不使用图像增广的情况下训练模型:train_with_data_aug(test_augs, test_augs, net)。比较使用与不使用图像增广时的训练准确率和测试准确率。这一对比实验能否支持“图像增广可以减轻过拟合”的论断?为什么?
  2. 在 CIFAR-10 数据集的模型训练中组合多种不同的图像增广方法,测试准确率是否有所提高?
  3. 查阅深度学习框架的在线文档,看看它还提供了哪些其他图像增广方法。
  4. 数据增广改变了训练实际最小化的目标函数。考虑在增广输入上训练的线性模型 \(f(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b\)。
    1. 对加性噪声 \(\mathbf{x}' = \mathbf{x} + \boldsymbol{\epsilon}\)(其中 \(\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \sigma^2 \mathbf{I})\))和平方损失,证明 \(\mathbb{E}_{\boldsymbol{\epsilon}}[(f(\mathbf{x}') - y)^2] = (f(\mathbf{x}) - y)^2 + \sigma^2 \|\mathbf{w}\|^2\)。因此加噪训练等价于系数为 \(\sigma^2\) 的权重衰减(2.7 节)(Bishop 1995年)。
    2. 设 \(\mathbf{P}\) 为将图像左右翻转的置换矩阵,并设对每张训练图像及其镜像取平均后的损失 \(L(\mathbf{w})\) 关于 \(\mathbf{w}\) 为凸函数。证明:若 \(\mathbf{w}^*\) 最小化 \(L\),则 \(\mathbf{P}\mathbf{w}^*\) 与 \((\mathbf{w}^* + \mathbf{P}\mathbf{w}^*)/2\) 同样取得该极小值。最后一个极小化子对一张图像及其镜像分别给出怎样的预测?
  5. 图像增广只能教会网络它所展示过的不变性。取上文使用随机左右翻转训练的网络,以及第 1 题不使用增广训练的网络:
    1. 在将每张图像左右翻转、将每张图像上下翻转、施加随机亮度变化(brightness=0.5)以及施加随机色调变化(hue=0.5)的 CIFAR-10 测试集上分别评估两个网络,连同原始未修改测试集一起列出每个网络的五项测试准确率表格。左右翻转增广减小了哪些变换下的准确率跌落,又对哪些变换的跌落毫无帮助?
    2. 对使用翻转训练的网络,将每张测试图像与其镜像上的 softmax 输出取平均(测试时增广,test-time augmentation)并汇报测试准确率,解释为什么该分类器在构造上天然对左右翻转保持不变。