Bird
Raised Fist0
PyTorchml~20 mins

Data augmentation in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Data augmentation
Problem:You are training a simple image classifier on a small dataset of handwritten digits. The model currently overfits: it performs very well on training images but poorly on validation images.
Current Metrics:Training accuracy: 98%, Validation accuracy: 70%, Training loss: 0.05, Validation loss: 1.2
Issue:The model overfits because the training data is limited and lacks variety. This causes poor generalization to new images.
Your Task
Use data augmentation to increase the variety of training images and reduce overfitting. Target validation accuracy >85% while keeping training accuracy below 95%.
You can only add data augmentation transforms to the training dataset.
Do not change the model architecture or optimizer settings.
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

# Define simple CNN model
class SimpleCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 16, 3, 1)
        self.conv2 = nn.Conv2d(16, 32, 3, 1)
        self.fc1 = nn.Linear(32 * 5 * 5, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = nn.functional.relu(self.conv1(x))
        x = nn.functional.max_pool2d(x, 2)
        x = nn.functional.relu(self.conv2(x))
        x = nn.functional.max_pool2d(x, 2)
        x = torch.flatten(x, 1)
        x = nn.functional.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# Data augmentation transforms for training
train_transforms = transforms.Compose([
    transforms.RandomRotation(15),
    transforms.RandomHorizontalFlip(),
    transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)),
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])

# Validation transforms (no augmentation)
val_transforms = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])

# Load datasets
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=train_transforms)
val_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=val_transforms)

train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=1000, shuffle=False)

# Initialize model, loss, optimizer
model = SimpleCNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Training loop
for epoch in range(10):
    model.train()
    train_loss = 0
    correct_train = 0
    for data, target in train_loader:
        optimizer.zero_grad()
        output = model(data)
        loss = criterion(output, target)
        loss.backward()
        optimizer.step()
        train_loss += loss.item() * data.size(0)
        pred = output.argmax(dim=1)
        correct_train += pred.eq(target).sum().item()
    train_loss /= len(train_loader.dataset)
    train_acc = 100. * correct_train / len(train_loader.dataset)

    model.eval()
    val_loss = 0
    correct_val = 0
    with torch.no_grad():
        for data, target in val_loader:
            output = model(data)
            loss = criterion(output, target)
            val_loss += loss.item() * data.size(0)
            pred = output.argmax(dim=1)
            correct_val += pred.eq(target).sum().item()
    val_loss /= len(val_loader.dataset)
    val_acc = 100. * correct_val / len(val_loader.dataset)

    print(f'Epoch {epoch+1}: Train loss {train_loss:.4f}, Train acc {train_acc:.2f}%, Val loss {val_loss:.4f}, Val acc {val_acc:.2f}%')
Added data augmentation transforms: random rotation, horizontal flip, and random affine translation to training data.
Kept validation data transforms unchanged to fairly evaluate model performance.
Did not change model architecture or optimizer settings.
Results Interpretation

Before augmentation: Training accuracy 98%, Validation accuracy 70%, Training loss 0.05, Validation loss 1.2

After augmentation: Training accuracy 93%, Validation accuracy 87%, Training loss 0.15, Validation loss 0.35

Data augmentation increases training data variety, which reduces overfitting. This leads to better validation accuracy and more reliable model generalization.
Bonus Experiment
Try adding dropout layers to the model to further reduce overfitting and compare results.
💡 Hint
Insert nn.Dropout layers after fully connected layers and retrain the model with the same augmented data.

Practice

(1/5)
1. What is the main purpose of data augmentation in PyTorch training pipelines?
easy
A. To reduce the size of the training dataset
B. To create new training data by modifying existing data
C. To speed up model training by skipping data preprocessing
D. To convert data into a different file format

Solution

  1. Step 1: Understand data augmentation concept

    Data augmentation means making new training examples by changing existing ones, like flipping or rotating images.
  2. Step 2: Identify the purpose in training

    This helps the model see more variety and avoid memorizing only the original data, improving learning.
  3. Final Answer:

    To create new training data by modifying existing data -> Option B
  4. Quick Check:

    Data augmentation = create new data [OK]
Hint: Data augmentation means changing data to get more examples [OK]
Common Mistakes:
  • Thinking it reduces dataset size
  • Confusing augmentation with speeding training
  • Believing it changes file formats
2. Which of the following is the correct way to apply a random horizontal flip to an image tensor using torchvision transforms?
easy
A. transforms.RandomHorizontalFlip(p=0.5)
B. transforms.HorizontalFlip(prob=0.5)
C. transforms.RandomFlip(direction='horizontal')
D. transforms.FlipHorizontal(0.5)

Solution

  1. Step 1: Recall torchvision transform syntax

    The correct transform for horizontal flip is RandomHorizontalFlip with a probability parameter p.
  2. Step 2: Match correct syntax

    transforms.RandomHorizontalFlip(p=0.5) uses transforms.RandomHorizontalFlip(p=0.5), which is the exact PyTorch syntax.
  3. Final Answer:

    transforms.RandomHorizontalFlip(p=0.5) -> Option A
  4. Quick Check:

    Correct transform name and parameter = C [OK]
Hint: Look for 'RandomHorizontalFlip' with p= probability [OK]
Common Mistakes:
  • Using wrong transform names
  • Using 'prob' instead of 'p'
  • Incorrect parameter names or missing parentheses
3. What will be the output shape of the image tensor after applying the following transform?
transform = transforms.Compose([
    transforms.RandomRotation(30),
    transforms.ToTensor()
])

image = Image.open('sample.jpg')
tensor_image = transform(image)
print(tensor_image.shape)
medium
A. [3, H, W] where H and W are original image height and width
B. [H, W, 3] where H and W are original image height and width
C. [1, H, W] grayscale image shape
D. [3, 30, 30] fixed size after rotation

Solution

  1. Step 1: Understand transforms.Compose and RandomRotation

    RandomRotation rotates the image but keeps the original size (height and width). ToTensor converts the image to a tensor with shape [channels, height, width].
  2. Step 2: Determine output tensor shape

    Since the image is color (3 channels), the tensor shape will be [3, H, W], where H and W are original height and width.
  3. Final Answer:

    [3, H, W] where H and W are original image height and width -> Option A
  4. Quick Check:

    Rotation keeps size, ToTensor outputs [3, H, W] [OK]
Hint: ToTensor outputs [channels, height, width] shape [OK]
Common Mistakes:
  • Confusing channel order as last dimension
  • Assuming rotation changes image size
  • Thinking output is grayscale shape
4. Identify the error in this PyTorch data augmentation code snippet:
transform = transforms.Compose([
    transforms.RandomHorizontalFlip(prob=0.5),
    transforms.RandomRotation(degrees=45),
    transforms.ToTensor()
])
medium
A. RandomRotation degrees must be a tuple, not a single number
B. ToTensor should come before RandomRotation
C. RandomHorizontalFlip should use keyword argument p=0.5
D. Compose cannot combine multiple transforms

Solution

  1. Step 1: Check RandomHorizontalFlip usage

    RandomHorizontalFlip requires the probability argument as p=0.5, not prob=0.5.
  2. Step 2: Verify other transforms

    RandomRotation accepts a single number for degrees, ToTensor can come last, and Compose supports multiple transforms.
  3. Final Answer:

    RandomHorizontalFlip should use keyword argument p=0.5 -> Option C
  4. Quick Check:

    Correct argument name = p [OK]
Hint: Check argument names carefully in transform constructors [OK]
Common Mistakes:
  • Passing positional argument instead of keyword
  • Thinking degrees must be tuple
  • Misordering transforms in Compose
5. You want to augment a dataset of images to improve model robustness. Which combination of transforms would best increase variety without changing image size or color channels?
Options:
A) RandomHorizontalFlip(p=0.5) + RandomRotation(15) + ColorJitter(brightness=0.2)
B) RandomResizedCrop(size=224) + Grayscale(num_output_channels=1)
C) RandomVerticalFlip(p=1.0) + RandomRotation(90) + ToTensor()
D) Resize(128) + RandomCrop(64) + RandomHorizontalFlip(p=0.5)
hard
A. Resize and crop to smaller size (changes image size)
B. RandomResizedCrop and converting to grayscale (changes size and channels)
C. Vertical flip and 90-degree rotation (may change orientation drastically)
D. RandomHorizontalFlip, small RandomRotation, and ColorJitter to vary brightness

Solution

  1. Step 1: Analyze each option's effect on size and channels

    RandomHorizontalFlip, small RandomRotation, and ColorJitter to vary brightness flips, rotates slightly, and changes brightness without resizing or changing channels. RandomResizedCrop and converting to grayscale (changes size and channels) changes size and converts to grayscale. Vertical flip and 90-degree rotation (may change orientation drastically) rotates 90 degrees and flips vertically, which changes orientation drastically. Resize and crop to smaller size (changes image size) resizes and crops, changing size.
  2. Step 2: Choose the option that keeps size and channels but increases variety

    RandomHorizontalFlip, small RandomRotation, and ColorJitter to vary brightness best fits the requirement by augmenting with flips, small rotations, and brightness changes without altering size or channels.
  3. Final Answer:

    RandomHorizontalFlip, small RandomRotation, and ColorJitter to vary brightness -> Option D
  4. Quick Check:

    Keep size and channels, add mild augmentations = A [OK]
Hint: Pick augmentations that don't resize or change color channels [OK]
Common Mistakes:
  • Choosing transforms that resize images
  • Converting images to grayscale unintentionally
  • Using large rotations that distort orientation