页面简介
正文摘录
In Section 7.1, we mentioned that large datasets are a prerequisite for the success of deep neural networks in various applications. Image augmentation generates similar but distinct training examples after a series of random changes to the training images, thereby expanding the size of the training set. Alternatively, image augmentation can be motivated by the fact that random tweaks of training examples allow models to rely less on certain attributes, thereby improving their generalization ability. For example, we can crop an image in different ways to make the object of interest appear in different positions, thereby reducing the dependence of a model on the position of the object. We can also adjust factors such as brightness and color to reduce a model’s sensitivity to color. It is probably true that image augmentation was indispensable for the success of AlexNet at that time. In this section we will discuss this widely used technique in computer vision. TensorFlowJAX # 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() PyTorchTensorFlowJAXMXNet import torchvision import warnings import keras from PIL import Image import tensorflow as tf from mxnet import image PyTorch warnings.filterwarnings('ignore', message='.*dtype.*align.*', category=np.exceptions.VisibleDeprecationWarning) 20.1.1 Common Image Augmentation Methods In our investigation of common image augmentation methods, we will use the following \(400\times 500\) image as an example. PyTorchTensorFlowJAXMXNet 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()); Most image augmentation methods have a certain degree of randomness. To make it easier for us to observe the effect of image augmentation, next we define an auxiliary function apply. This function runs the image augmentation method aug multiple times on the input image img and shows all the results. 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 Flipping and Cropping PyTorchTensorFlowJAXMXNet Flipping the image left and right usually does not change the category of the object. This is one of the earliest and most widely used methods of image augmentation. Next, we use the transforms module to create the RandomHorizontalFlip instance, which flips an image left and right with a 50% chance. Flipping the image left and right usually does not change the category of the object. This is one of the earliest and most widely used methods of image augmentation. Next, we define a RandomHorizontalFlip function using tf.image, which flips an image left and right with a 50% chance. We convert between PIL images and TensorFlow tensors as needed. Flipping the image left and right usually does not change the category of the object. This is one of the earliest and most widely used methods of image augmentation. Next, we define a RandomHorizontalFlip function using tf.image, which flips an image left and right with a 50% chance. We convert between PIL images and TensorFlow tensors as needed. Flipping the image left and right usually does not change the category of the object. This is one of the earliest and most widely used methods of image augmentation. Next, we use the transforms module to create the RandomFlipLeftRight instance, which flips an image left and right with a 50% chance. PyTorchTensorFlowJAXMXNet 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()) PyTorchTensorFlowJAXMXNet Flipping up and down is not as common as flipping left and right. But at least for this example image, flipping up and down does not hinder recognition. Next, we create a RandomVerticalFlip instance to flip an image up and down with a 50% chance. Flipping up and down is not as common as flipping left and right. But at least for this example image, flipping up and down does not hinder recognition. Next, we create a RandomVerticalFlip function to flip an image up and down with a 50% chance. Flipping up and down is not as common as flipping left and right. But at least for this example image, flipping up and down does not hinder recognition. Next, we create a RandomVerticalFlip function to flip an image up and down with a 50% chance. Flipping up and down is not as common as flipping left and right. But at least for this example image, flipping up and down does not hinder recognition. Next, we create a RandomFlipTopBottom instance to flip an image up and down with a 50% chance. PyTorchTensorFlowJAXMXNet 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()) In the example image we used, the cat is in the middle of the image, but this may not be the case in general. In Section 6.5, we explained that the pooling layer can reduce the sensitivity of a convolutional layer to the target position. In addition, we can also randomly crop the image to make objects appear in different positions in the image at different scales, which can also reduce the sensitivity of a model to the target position. In the code below, we randomly crop an area with an area of \(10\% \sim 100\%\) of the original area each time, and the ratio of width to height of this area is randomly selected from \(0.5 \sim 2\). Then, the width and height of the region are both scaled to 200 pixels. Unless otherwise specified, the random number between \(a\) and \(b\) in this section refers to a continuous value obtained by random and uniform sampling from the interval \([a, b]\). PyTorchTensorFlowJAXMXNet 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.f