Data transforms help prepare and change data so a machine learning model can learn better. They make data easier to use and improve model results.
Data transforms in PyTorch
transform = torchvision.transforms.Compose([
torchvision.transforms.Resize((height, width)),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean, std)
])Compose lets you combine many transforms in order.
Transforms like Resize, ToTensor, and Normalize are common for image data.
transform = torchvision.transforms.ToTensor()
transform = torchvision.transforms.Normalize(mean=[0.5], std=[0.5])
transform = torchvision.transforms.Compose([
torchvision.transforms.Resize((28, 28)),
torchvision.transforms.RandomHorizontalFlip(),
torchvision.transforms.ToTensor()
])This code creates a white image, resizes it, converts it to a tensor, and normalizes it. Then it prints the tensor shape and pixel values.
import torch from torchvision import transforms from PIL import Image import numpy as np # Create a dummy image (100x100 pixels, white color) image = Image.fromarray(np.full((100, 100, 3), fill_value=255, dtype=np.uint8)) # Define transforms: resize to 64x64, convert to tensor, normalize transform = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), transforms.Normalize(mean=[1.0, 1.0, 1.0], std=[1.0, 1.0, 1.0]) ]) # Apply transform transformed_image = transform(image) # Print shape and some pixel values print(f"Transformed image shape: {transformed_image.shape}") print(f"Pixel value at (0,0): {transformed_image[:,0,0]}")
Normalization subtracts the mean and divides by std for each channel, so here mean=1 and std=1 makes pixel values zero after normalization.
Transforms are applied in order inside Compose.
Always convert images to tensors before feeding to PyTorch models.
Data transforms prepare raw data for machine learning models.
Use Compose to chain multiple transforms like resize, flip, tensor conversion, and normalization.
Transforms improve model training and prediction quality.
Practice
Solution
Step 1: Understand the role of data transforms
Data transforms modify raw data to make it suitable for model input, such as resizing or normalizing images.Step 2: Differentiate from other tasks
Creating layers, evaluating accuracy, or saving models are separate tasks unrelated to data transforms.Final Answer:
To prepare and modify raw data before feeding it to a model -> Option AQuick Check:
Data transforms = prepare data [OK]
- Confusing transforms with model building
- Thinking transforms evaluate model performance
- Mixing transforms with saving models
Solution
Step 1: Recall the correct class for chaining transforms
PyTorch uses transforms.Compose to chain multiple transforms in a list.Step 2: Check syntax correctness
Only transforms.Compose accepts a list of transforms; others like Sequence, Pipeline, Chain do not exist in torchvision.Final Answer:
transforms.Compose([transforms.Resize(256), transforms.ToTensor()]) -> Option DQuick Check:
Use Compose for chaining transforms [OK]
- Using non-existent classes like Sequence or Pipeline
- Passing transforms as separate arguments instead of a list
- Confusing Compose with other transform functions
transform = transforms.Compose([transforms.Resize(50), transforms.ToTensor()])Solution
Step 1: Understand Resize effect
transforms.Resize(50) resizes the image to 50x50 pixels, keeping the number of channels unchanged (3 channels).Step 2: Understand ToTensor output shape
transforms.ToTensor() converts the image to a tensor with shape [channels, height, width], so shape is [3, 50, 50].Final Answer:
[3, 50, 50] -> Option CQuick Check:
Tensor shape = [channels, height, width] [OK]
- Assuming channels last format
- Confusing Resize parameter as channels
- Mixing height and width order
transform = transforms.Compose([
transforms.Resize(128),
transforms.Normalize(mean=[0.5], std=[0.5]),
transforms.ToTensor()
])Solution
Step 1: Check order of transforms
transforms.Normalize expects a tensor input, but here it is before ToTensor, which converts image to tensor.Step 2: Correct order
ToTensor must come before Normalize to convert image to tensor first, then normalize it.Final Answer:
Normalize should come after ToTensor -> Option BQuick Check:
Normalize after ToTensor [OK]
- Placing Normalize before ToTensor
- Assuming Resize order matters with Normalize
- Thinking ToTensor can be anywhere
Solution
Step 1: Understand transform order for augmentation and normalization
RandomHorizontalFlip works on PIL images, so it must come before ToTensor.Step 2: Normalize after converting to tensor
Normalize requires tensor input, so it must come after ToTensor.Final Answer:
transforms.Compose([transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.5,0.5,0.5], std=[0.5,0.5,0.5])]) -> Option AQuick Check:
Flip before ToTensor, Normalize after ToTensor [OK]
- Applying Normalize before ToTensor
- Applying RandomHorizontalFlip after ToTensor
- Mixing order of augmentation and normalization
Ready to prove it?
Pass the test and this pattern moves unknown
