Get startedGet started for free

Data augmentation in PyTorch

Let's include data augmentation in your Dataset and inspect some images visually to make sure the desired transformations are applied.

First, you'll add the augmenting transformations to train_transforms. Let's use a random horizontal flip and a rotation by a random angle between 0 and 45 degrees. The code that follows to create the Dataset and the DataLoader is exactly the same as before. Finally, you'll reshape the image and display it to see if the new augmenting transformations are visible.

All the imports you need have been called for you:

from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader
from torchvision import transforms
import matplotlib.pyplot as plt

Time to augment some cloud photos!

This exercise is part of the course

Intermediate Deep Learning with PyTorch

View Course

Exercise instructions

  • Add two more transformations to train_transforms to perform a random horizontal flip and then a rotation by a random angle between 0 and 45 degrees.
  • Reshape the image tensor from the DataLoader to make it suitable for display.
  • Display the image.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

train_transforms = transforms.Compose([
    # Add horizontal flip and rotation
    ____,
    ____,
    transforms.ToTensor(),
    transforms.Resize((128, 128)),
])

dataset_train = ImageFolder(
  "clouds_train",
  transform=train_transforms,
)

dataloader_train = DataLoader(
  dataset_train, shuffle=True, batch_size=1
)

image, label = next(iter(dataloader_train))
# Reshape the image tensor
image = image.____.____(____, ____, ____) 
# Display the image
____
plt.show()
Edit and Run Code