How to Use Random Flip in PyTorch for Image Augmentation
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 probabilityp.RandomVerticalFlip(p=0.5): flips the image up-down with probabilityp.
These transforms can be composed with others using transforms.Compose.
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.
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)
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.
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
| Transform | Description | Default Probability (p) |
|---|---|---|
| RandomHorizontalFlip | Flip image left-right randomly | 0.5 |
| RandomVerticalFlip | Flip image up-down randomly | 0.5 |