0
0
PytorchHow-ToBeginner · 3 min read

How to Use Random Flip in PyTorch for Image Augmentation

Use torchvision.transforms.RandomHorizontalFlip or RandomVerticalFlip to randomly flip images during training. These transforms take a p parameter for the probability of flipping and can be applied to image tensors or PIL images.
📐

Syntax

The random flip transforms in PyTorch are part of torchvision.transforms. You can use:

  • RandomHorizontalFlip(p=0.5): flips the image left-right with probability p.
  • RandomVerticalFlip(p=0.5): flips the image up-down with probability p.

These transforms can be composed with others using transforms.Compose.

python
import torchvision.transforms as transforms

# Random horizontal flip with 50% chance
random_hflip = transforms.RandomHorizontalFlip(p=0.5)

# Random vertical flip with 30% chance
random_vflip = transforms.RandomVerticalFlip(p=0.3)
💻

Example

This example shows how to apply a random horizontal flip to a sample image tensor. The image is flipped with 50% chance each time the transform is applied.

python
import torch
import torchvision.transforms as transforms
from PIL import Image
import requests
from io import BytesIO

# Load an example image from the web
url = 'https://pytorch.org/assets/images/deeplab1.png'
response = requests.get(url)
img = Image.open(BytesIO(response.content))

# Define random horizontal flip transform
random_hflip = transforms.RandomHorizontalFlip(p=0.5)

# Apply transform multiple times to see randomness
for i in range(3):
    flipped_img = random_hflip(img)
    print(f'Flip attempt {i+1}: Flipped =', flipped_img != img)
Output
Flip attempt 1: Flipped = True Flip attempt 2: Flipped = False Flip attempt 3: Flipped = True
⚠️

Common Pitfalls

1. Forgetting to set the probability p: The default is 0.5, but if you want always to flip, set p=1.0.

2. Applying random flip to tensors without proper shape: The input should be a PIL Image or a tensor with shape (C, H, W). If the tensor shape is different, the transform may fail.

3. Using random flip during evaluation: Random flips are for data augmentation during training only. Disable them during validation/testing for consistent results.

python
import torchvision.transforms as transforms

# Wrong: p=0 means no flip
random_flip_wrong = transforms.RandomHorizontalFlip(p=0)

# Right: p=1 means always flip
random_flip_right = transforms.RandomHorizontalFlip(p=1.0)
📊

Quick Reference

TransformDescriptionDefault Probability (p)
RandomHorizontalFlipFlip image left-right randomly0.5
RandomVerticalFlipFlip image up-down randomly0.5

Key Takeaways

Use torchvision.transforms.RandomHorizontalFlip or RandomVerticalFlip with a probability p to randomly flip images.
Apply random flips only during training for data augmentation, not during evaluation.
Input images must be PIL Images or tensors with shape (C, H, W) for the transforms to work correctly.
Set p=1.0 to always flip or p=0 to never flip, depending on your needs.