Sub topic 4
Loading data in batches
This chapter covers how PyTorch turns a folder of images into batches a model can consume. It assumes you know basic Python, have seen PyTorch tensors and modules, and understand what an epoch and a batch are. The previous chapters covered folder layout and the transforms. Here we connect them to Dataset and DataLoader.
The two objects: Dataset and DataLoader
PyTorch splits data handling into two roles.
- A
Datasetanswers one question: "give me sample numberi." It implements__len__and__getitem__. For images,__getitem__opens a file, applies the transform, and returns an(image_tensor, label)pair. - A
DataLoaderwraps a dataset. It chooses which indices to fetch, groups samples into batches, stacks them into single tensors, and can do the work in parallel worker processes.
The split lets you change how you batch without touching how you read a single image.
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),
])
# Expected layout: data/train/<class_name>/*.jpg and data/val/<class_name>/*.jpg
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)
num_classes = len(train_ds.classes)What ImageFolder gives you
ImageFolder scans the root directory and treats each sub-folder as one class. Folder names are sorted alphabetically and assigned integer labels starting at 0. You can inspect the result:
print(train_ds.classes) # e.g. ['cat', 'dog', 'fox']
print(train_ds.class_to_idx) # e.g. {'cat': 0, 'dog': 1, 'fox': 2}
print(len(train_ds)) # number of images
path, label = train_ds.samples[0]
print(path, label)Three points matter in practice.
- Labels come from folder names only. Nothing is read from the files until
__getitem__runs, so building the dataset is fast even for large folders. It also means a mislabeled file in the wrong folder is silently trained on as that class. - The class order must match across splits.
train_dsandval_dseach compute their own mapping. Ifval/is missing a class folder, the labels shift and validation accuracy is wrong without any error. Check thattrain_ds.classes == val_ds.classesafter you build both. - Corrupt or non-image files fail late. A truncated JPEG raises an error in the middle of an epoch, not at construction. Run one pass over the dataset before a long training job to catch these early.
assert train_ds.classes == val_ds.classes, "train and val class folders differ"
# Smoke test: load every image once with no augmentation randomness concerns.
from PIL import Image
bad = []
for path, _ in train_ds.samples + val_ds.samples:
try:
with Image.open(path) as img:
img.verify()
except Exception as exc:
bad.append((path, str(exc)))
print(f"{len(bad)} unreadable files")Why the transforms differ per split
Each dataset holds its own transform, which is why there are two ImageFolder objects rather than one.
- The training pipeline uses
RandomResizedCropandRandomHorizontalFlip. These run every time an image is fetched, so the model sees a slightly different version of each photo every epoch. - The validation pipeline uses
Resize(256)thenCenterCrop(224). It is deterministic, so a given image always produces the same tensor and validation numbers are comparable between epochs. - Both end with
ToTensorandNormalizeusing the ImageNet mean and standard deviation, because the pretrained weights were trained on inputs scaled that way.
A common mistake is passing the training transform to the validation dataset. Accuracy then becomes noisy from epoch to epoch because each evaluation sees different random crops.
What a batch looks like
Iterating a loader yields one batch per step. The default collate function stacks the individual tensors along a new first dimension.
images, labels = next(iter(train_loader))
print(images.shape) # torch.Size([32, 3, 224, 224])
print(labels.shape) # torch.Size([32])
print(labels.dtype) # torch.int64
print(images.dtype) # torch.float32The shape is [batch, channels, height, width]. Stacking only works because every transformed image has the same size, which is the job of the crop. Without a fixed size, collation fails with a "stack expects each tensor to be equal size" error. The labels are int64 class indices, which is what nn.CrossEntropyLoss expects.
The last batch of an epoch may be smaller than batch_size when the dataset size is not a multiple of it. That is fine for fine-tuning. The loop in the next chapters weights loss by images.size(0) so a short batch does not distort the epoch average.
DataLoader settings that matter
| Argument | What it does | Guidance for fine-tuning |
|---|---|---|
| `batch_size` | Samples per step | 16 to 64 is typical. Larger batches use more GPU memory. If you hit an out-of-memory error, halve it first. |
| `shuffle` | Reorders samples each epoch | `True` for training, `False` for validation. |
| `num_workers` | Worker processes loading data | 0 loads in the main process. Try 2 to 8 and watch GPU utilization. |
| `pin_memory` | Uses page-locked host memory | Set `True` when training on a CUDA GPU. It speeds host-to-GPU copies. |
| `drop_last` | Drops the final short batch | Usually `False`. Use `True` only if something in your model needs a fixed batch size. |
| `persistent_workers` | Keeps workers alive between epochs | Useful with `num_workers > 0` when epochs are short. |
Shuffling
Shuffling matters for training. ImageFolder lists files class by class, so without shuffling each batch would contain images of a single class and gradient updates would swing wildly. Validation does not update weights, so order is irrelevant and skipping the shuffle keeps runs reproducible.
Workers
Image decoding and augmentation run on the CPU. If they are slower than the GPU, the GPU sits idle. Workers fix this by preparing future batches in parallel.
- Start with
num_workers=4and measure. More is not always faster, because each worker uses memory and the data may be limited by disk speed. - On Windows and macOS, worker processes are started by spawning a fresh interpreter. Put your training code under
if __name__ == "__main__":, or you will get a runtime error about starting a new process before the current one has finished bootstrapping. - If you debug with breakpoints or get confusing tracebacks from workers, set
num_workers=0temporarily.
Measuring whether loading is the bottleneck
A quick check is to time a pass over the loader with no model at all.
import time
start = time.perf_counter()
n = 0
for images, labels in train_loader:
n += images.size(0)
elapsed = time.perf_counter() - start
print(f"{n / elapsed:.0f} images/sec from the loader alone")If the loader alone delivers fewer images per second than the model can process, loading is the bottleneck. Try more workers, pin_memory=True, smaller source images, or a faster disk. Very large original photos are a common cause: decoding a 12-megapixel JPEG just to crop it to 224 pixels is expensive, and resizing the dataset once on disk can speed up every epoch.
Common errors
FileNotFoundErroror "Found no valid file for the classes". The path is wrong, or a class folder contains no files with a recognized image extension.- Validation accuracy is near chance with a good training score. Check that the class lists match and that the validation transform has no random operations.
- "stack expects each tensor to be equal size". A transform is missing a resize or crop, so images reach collation at different sizes.
- Grayscale or RGBA images cause channel errors.
ImageFolderloads images with PIL'sconvert("RGB")by default, so this is handled for you. If you write a custom dataset, call.convert("RGB")yourself. - Training hangs or crashes with workers on Windows. Add the
__main__guard described above.
Putting it together
The loaders defined here feed directly into the training loop. The only things the loop needs from this chapter are train_loader, val_loader, and num_classes, which sets the size of the new classification head.
Exercise
You build val_ds with train_tfms by mistake, and your validation accuracy changes by a few points each time you evaluate the same unchanged model. Why does this happen, and what is the fix? Also name one extra check you should run on the two datasets before training.
Show answer
train_tfms contains RandomResizedCrop and RandomHorizontalFlip, which pick new random values every time an image is loaded, so the same model sees different inputs on each evaluation and the score fluctuates. The fix is to build val_ds with val_tfms (Resize, CenterCrop, ToTensor, Normalize), which is deterministic. As an extra check, assert that train_ds.classes == val_ds.classes, so that both splits map class names to the same integer labels.
Exercise
Your training loop shows low GPU utilization, and a loader-only timing test reports 90 images per second while the model can process 400 per second. Name two changes to the DataLoader settings you would try, and explain why each might help.
Show answer
Increase num_workers (for example from 0 or 2 to 4 or 8) so that decoding and augmentation run in parallel across CPU processes and batches are ready before the GPU needs them. Set pin_memory=True (on a CUDA machine) so batches are copied to the GPU from page-locked memory, which makes the transfer faster. Setting persistent_workers=True is also reasonable when epochs are short, and resizing very large source images on disk can help as well.