Sub topic 4
Loading Data in Batches
Assume you know basic Python, PyTorch tensors and modules, and the ideas of loss, epochs, and gradient descent. This chapter focuses on turning labeled image files into batches that a training loop can consume.
Use folders as labels
ImageFolder is a dataset class that assigns labels from folder names. Each sub-folder under the dataset directory represents one class.
A layout such as this gives every image a label:
data/
├── train/
│ ├── cat/
│ │ ├── cat_001.jpg
│ │ └── cat_002.jpg
│ └── dog/
│ └── dog_001.jpg
└── val/
├── cat/
│ └── cat_101.jpg
└── dog/
└── dog_101.jpgImageFolder sorts class names and stores the resulting mapping in dataset.class_to_idx. For example, {"cat": 0, "dog": 1}. Keep this mapping with your trained model because numeric labels only have meaning through their class order.
Each dataset needs a transform. The transform converts a PIL image into the tensor shape and value range expected by the model. Training and validation usually use different transforms: training can use random augmentation, while validation must be repeatable.
Create datasets and loaders
A DataLoader is an iterator that retrieves samples from a dataset and groups them into batches. shuffle=True changes the sample order at the start of each training pass. This reduces the chance that batches reflect an accidental ordering in your files.
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tfms = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
val_tfms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
train_ds = datasets.ImageFolder("data/train", transform=train_tfms)
val_ds = datasets.ImageFolder("data/val", transform=val_tfms)
train_loader = DataLoader(
train_ds, batch_size=32, shuffle=True, num_workers=4
)
val_loader = DataLoader(
val_ds, batch_size=32, shuffle=False, num_workers=4
)
print(train_ds.classes)
print(len(train_ds), len(val_ds))
images, labels = next(iter(train_loader))
print(images.shape) # [32, 3, 224, 224], unless the final batch is smaller
print(labels.shape) # [32]batch_size controls how many images are processed together. Larger batches can improve throughput but use more memory. num_workers starts background processes that load and transform images. Begin with a small value and increase it only if loading is slowing training. On some operating systems or notebook environments, num_workers=0 is the safest choice.
The final batch may contain fewer than 32 images. That is normal. Do not assume every batch has the configured size unless you set drop_last=True, which discards the incomplete training batch.
How a batch reaches the model
In the training loop, move both tensors to the same device as the model:
for images, labels in train_loader:
images = images.to(device)
labels = labels.to(device)
logits = model(images)Check the input before training
Inspect one batch before starting a long run. Confirm the tensor shape, label range, class count, and transform behavior. Many apparent model problems are actually folder, label, or image-loading mistakes.
Exercise
Why should shuffle=True be used for the training loader but usually not for the validation loader?
Show answer
Training benefits from a different sample order each epoch, while validation should measure the same complete set predictably.