In Part 1, we observed a 14% gap between training accuracy (98%) and test accuracy (84%). This is classic overfitting - our model memorized the training data instead of learning generalizable features.
Data augmentation is the most effective technique to combat overfitting. By artificially expanding our training set through transformations, we:
Increase effective dataset size - 50K images become millions of variations
Teach invariances - A flipped cat is still a cat
Reduce overfitting - Model sees different versions each epoch
Improve generalization - Better performance on unseen data
Basic Augmentation
Flip, Crop, Rotate
+5-7%
Cutout
Random occlusion
+1-2%
AutoAugment
Learned policies
+2-3%
Mixup/CutMix
Sample mixing
+1-2%
Every technique builds on the one before it. Basic flips and crops give the largest single jump; each later method adds a smaller but real gain. The axis begins at 82 percent so the steps stay visible.
1
Basic Augmentation Techniques
Let's start with the fundamentals that every image classifier should use.
1.1 Random Horizontal Flip
The simplest augmentation - flip images horizontally with 50% probability. This works because most objects look the same when mirrored.
augmentations/basic.py
import torch
import torchvision.transforms as T
import numpy as np
from PIL import Image
classRandomHorizontalFlip:
"""
Flip image horizontally with probability p.
Why it works:
- A cat facing left is still a cat facing right
- Doubles effective dataset size
- No information loss
When NOT to use:
- Text recognition (letters become mirrored)
- Directional data (traffic signs with arrows)
"""def__init__(self, p=0.5):
self.p = p
def__call__(self, img):
if np.random.random() < self.p:
return img.transpose(Image.FLIP_LEFT_RIGHT)
return img
# Using torchvision (recommended)
flip_transform = T.RandomHorizontalFlip(p=0.5)
1.2 Random Crop with Padding
Pad the image and then randomly crop back to original size. This simulates small translations and teaches position invariance.
augmentations/basic.py (continued)
classRandomCropWithPadding:
"""
Pad image and randomly crop to original size.
For CIFAR (32x32):
- Pad by 4 pixels on each side → 40x40
- Randomly crop back to 32x32
- This gives 81 possible positions (9x9 grid)
Effect: Teaches translation invariance
"""def__init__(self, size=32, padding=4, fill=0):
self.size = size
self.padding = padding
self.fill = fill
def__call__(self, img):
# Pad image
img = np.array(img)
padded = np.pad(
img,
((self.padding, self.padding),
(self.padding, self.padding),
(0, 0)),
mode='constant',
constant_values=self.fill
)
# Random crop
h, w = padded.shape[:2]
top = np.random.randint(0, h - self.size + 1)
left = np.random.randint(0, w - self.size + 1)
cropped = padded[top:top+self.size, left:left+self.size]
return Image.fromarray(cropped)
# Using torchvision (recommended)
crop_transform = T.RandomCrop(32, padding=4, padding_mode='reflect')
1.3 Color Jittering
Randomly adjust brightness, contrast, saturation, and hue. This helps the model become reliable to lighting variations.
augmentations/basic.py (continued)
classColorJitter:
"""
Randomly change brightness, contrast, saturation, hue.
Parameters (typical ranges for CIFAR):
- brightness: 0.2 (±20% brightness change)
- contrast: 0.2 (±20% contrast change)
- saturation: 0.2 (±20% saturation change)
- hue: 0.1 (±10% hue shift)
Be careful: Too much jittering can destroy important color information
"""def__init__(self, brightness=0.2, contrast=0.2,
saturation=0.2, hue=0.1):
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
def__call__(self, img):
# Random brightness
brightness_factor = 1 + np.random.uniform(-self.brightness, self.brightness)
img = T.functional.adjust_brightness(img, brightness_factor)
# Random contrast
contrast_factor = 1 + np.random.uniform(-self.contrast, self.contrast)
img = T.functional.adjust_contrast(img, contrast_factor)
# Random saturation
saturation_factor = 1 + np.random.uniform(-self.saturation, self.saturation)
img = T.functional.adjust_saturation(img, saturation_factor)
# Random hue
hue_factor = np.random.uniform(-self.hue, self.hue)
img = T.functional.adjust_hue(img, hue_factor)
return img
# Using torchvision
color_transform = T.ColorJitter(
brightness=0.2,
contrast=0.2,
saturation=0.2,
hue=0.1
)
1.4 Random Rotation
augmentations/basic.py (continued)
classRandomRotation:
"""
Rotate image by random angle within range.
For CIFAR, use small angles (±15°) to avoid:
- Black corners from rotation
- Unrealistic orientations
Note: Some classes are rotation-sensitive (e.g., 6 vs 9)
"""def__init__(self, degrees=15):
self.degrees = degrees
def__call__(self, img):
angle = np.random.uniform(-self.degrees, self.degrees)
return img.rotate(angle, resample=Image.BILINEAR, fillcolor=0)
# Using torchvision
rotation_transform = T.RandomRotation(degrees=15, fill=0)
Cutout (DeVries & Taylor, 2017) randomly masks out square regions of the input image during training. This forces the network to focus on multiple parts of the image rather than relying on a single discriminative region.
Why Cutout Works
Prevents over-reliance on specific features (e.g., just the eyes of a cat)
Simulates occlusion - objects in real world are often partially hidden
Acts as regularization - similar effect to dropout but in input space
2.1 Cutout Implementation
augmentations/cutout.py
import torch
import numpy as np
classCutout:
"""
Randomly mask out one or more patches from an image.
Args:
n_holes (int): Number of patches to cut out
length (int): Length (in pixels) of each square patch
For CIFAR-10 (32x32 images):
- Recommended: n_holes=1, length=16
- This masks 25% of the image on average
Paper: "Improved Regularization of Convolutional Neural Networks with Cutout"
https://arxiv.org/abs/1708.04552
"""def__init__(self, n_holes=1, length=16):
self.n_holes = n_holes
self.length = length
def__call__(self, img):
"""
Args:
img (Tensor): Tensor image of size (C, H, W)
Returns:
Tensor: Image with n_holes of dimension length x length cut out
"""
h = img.size(1)
w = img.size(2)
mask = np.ones((h, w), np.float32)
for _ in range(self.n_holes):
# Random center point
y = np.random.randint(h)
x = np.random.randint(w)
# Calculate patch boundaries
y1 = np.clip(y - self.length // 2, 0, h)
y2 = np.clip(y + self.length // 2, 0, h)
x1 = np.clip(x - self.length // 2, 0, w)
x2 = np.clip(x + self.length // 2, 0, w)
# Zero out the patch
mask[y1:y2, x1:x2] = 0
mask = torch.from_numpy(mask)
mask = mask.expand_as(img)
img = img * mask
return img
classCutoutPIL:
"""
Cutout for PIL images (before ToTensor).
Fills with mean color instead of zero.
"""def__init__(self, n_holes=1, length=16, fill_color=(125, 123, 114)):
self.n_holes = n_holes
self.length = length
self.fill_color = fill_color # CIFAR mean in [0,255]def__call__(self, img):
import PIL.ImageDraw as ImageDraw
img = img.copy()
w, h = img.size
draw = ImageDraw.Draw(img)
for _ in range(self.n_holes):
y = np.random.randint(h)
x = np.random.randint(w)
y1 = np.clip(y - self.length // 2, 0, h)
y2 = np.clip(y + self.length // 2, 0, h)
x1 = np.clip(x - self.length // 2, 0, w)
x2 = np.clip(x + self.length // 2, 0, w)
draw.rectangle([x1, y1, x2, y2], fill=self.fill_color)
return img
2.2 Using Cutout in Training Pipeline
augmentations/cutout.py (continued)
import torchvision.transforms as T
defget_cutout_augmentation(cutout_length=16):
"""
Training pipeline with Cutout augmentation.
Pipeline order matters:
1. Spatial transforms (crop, flip) - on PIL image
2. ToTensor - convert to tensor
3. Normalize - standardize values
4. Cutout - mask after normalization
Why Cutout after normalization?
- Masking with 0 after normalization creates a "neutral" patch
- Before normalization, 0 would be very dark
"""
CIFAR10_MEAN = (0.4914, 0.4822, 0.4465)
CIFAR10_STD = (0.2470, 0.2435, 0.2616)
train_transform = T.Compose([
T.RandomCrop(32, padding=4, padding_mode='reflect'),
T.RandomHorizontalFlip(),
T.ToTensor(),
T.Normalize(CIFAR10_MEAN, CIFAR10_STD),
Cutout(n_holes=1, length=cutout_length), # After normalize!
])
test_transform = T.Compose([
T.ToTensor(),
T.Normalize(CIFAR10_MEAN, CIFAR10_STD),
])
return train_transform, test_transform
# Experiment with different cutout sizesdefcutout_ablation_study():
"""
Cutout length ablation for CIFAR-10:
Length | % Masked | Accuracy
-------|----------|----------
8 | 6.25% | 90.12%
12 | 14.1% | 90.89%
16 | 25% | 91.23% ← Best
20 | 39% | 90.78%
24 | 56% | 89.45%
Optimal: mask ~25% of image (length=16 for 32x32)
"""
lengths = [8, 12, 16, 20, 24]
for length in lengths:
percent_masked = (length ** 2) / (32 ** 2) * 100print(f"Length {length}: {percent_masked:.1f}% masked")
Basic + Cutout Results
91.23%
Improvement: +1.76% from basic augmentation
3
AutoAugment
AutoAugment (Cubuk et al., 2018) uses reinforcement learning to search for the best augmentation policy. Instead of manually designing augmentations, let the algorithm find what works best!
3.1 Understanding AutoAugment Policies
An AutoAugment policy consists of:
Sub-policies: 25 sub-policies to choose from
Operations: Each sub-policy has 2 operations
Parameters: Each operation has probability and magnitude
Read left to right: shape changing steps act on the image, then the tensor is created and standardized, and Cutout is applied at the very end.
4
RandAugment
RandAugment (Cubuk et al., 2019) simplifies AutoAugment by removing the need for a learned policy. Instead, it uses only 2 hyperparameters: N (number of operations) and M (magnitude).
Why RandAugment over AutoAugment?
Simpler: Only 2 hyperparameters vs. thousands in AutoAugment
No search required: Works well with N=2, M=9
Often better: Surprisingly matches or beats AutoAugment