Turn a Folder of Photos into Batches
A model learns from examples, and for an image classifier an example is a photo together with the name of what it shows. Before any training can start, a pile of photo files has to become that: a collection that hands out one prepared image and its label at a time, divided into separate sets for training, choosing and testing, and served in groups that the network can process together. This page explains each of those steps and the mistakes that quietly spoil a measurement when one of them is done carelessly.
One folder per class
The simplest way to label thousands of photos is to let the folders do it. You make one folder for each class and put every photo of that class inside it. The folder name is the label: a photo in cat/ is a cat, wherever it came from and whatever its file is called. Nobody has to write a list of labels, and moving a wrongly sorted photo to the right folder corrects its label.
In torchvision this convention is read by torchvision.datasets.ImageFolder. You give it the top folder, often called the root, and it treats every subfolder of the root as one class.
- photos/
- bird/ class
- cat/ class
- dog/ class
- LICENSE.txt not a class
- robin.jpg
- img_001.jpg
- img_002.png
- park.jpeg
A network does not output words, it outputs one score per class, so each class name needs a fixed number: the position of its score. ImageFolder builds that mapping by sorting the folder names alphabetically and numbering them from 0. It does not matter which folder was created first or how the file system lists them; the sorted order decides. The result is kept in classes, the sorted list of names, and class_to_idx, the dictionary from name to number.
| Class name (folder) | Class number |
|---|---|
| bird | 0 |
| cat | 1 |
| dog | 2 |
Because the mapping comes from the names alone, the same folders give the same numbers on every run. That matters later: a trained model only outputs the number 1, and the list classes is what turns it back into "cat". Adding a new folder called ant/ would shift every number by one, so the mapping belongs with the model.
Two details keep the folder tidy without extra work. First, files lying directly in the root, such as a licence file, are neither classes nor samples. Second, inside a class folder, only files with an image extension (.jpg, .jpeg, .png, .webp and a few others, in any letter case) become samples; images in nested subfolders of a class are included too. A class folder with no valid image raises an error by default.
True or false?
If the folder dog/ was created before cat/, ImageFolder gives dog the number 0.
False. The folder names are sorted alphabetically before they are numbered, so cat comes before dog whatever the creation order.
Renaming a photo file inside cat/ does not change its label.
True. The label comes from the folder the file sits in, not from the file name.
A dataset hands out one example on request
Once the folders are read, you have a dataset: an object that knows how many examples it holds and returns any one of them when you ask by its position. In PyTorch this means two operations, len(dataset) for the count and dataset[i] for example number i. For an image dataset, dataset[i] returns a pair: the image and its class number.
When ImageFolder is created, it opens no image at all. It walks the folders and records a list of pairs, the path of each file and its class number, in a fixed sorted order. The pixels are read only when an example is requested, and that is also the moment the image is prepared.
- dataset[i] looks up pair i
- Open file Pillow, RGB
- Transform resize, crop, scale
- (image, label) tensor, number
- dataset[i] to Open file
- Open file to Transform
- Transform to (image, label)
First the dataset opens the file with Pillow and converts it to three colour channels, so a greyscale or transparent PNG arrives as an ordinary RGB picture. Then it hands that picture to the transform: a function you give the dataset that turns a freshly opened image into exactly what the model expects. A typical transform resizes and crops the picture to the model's input size, turns it into a float tensor and normalises it, the same preparation the pretrained weights were trained with.
Since the weights ship their own preparation, the simplest correct transform is the one they provide:
from torchvision.datasets import ImageFolder
from torchvision.models import MobileNet_V3_Small_Weights
weights = MobileNet_V3_Small_Weights.DEFAULT
full = ImageFolder("photos", transform=weights.transforms())
print(full.classes) # ['bird', 'cat', 'dog']
print(full.class_to_idx) # {'bird': 0, 'cat': 1, 'dog': 2}
image, label = full[0]
print(image.shape, label) # torch.Size([3, 224, 224]) 0The transform of these weights resizes the shorter side to 256 pixels, cuts out the central 224 by 224 square, scales the pixel values to the range 0 to 1 and normalises each colour channel. So every example comes out as a float tensor of shape (3, 224, 224), whatever the size of the original photo.
Preparing at load time, rather than once in advance, has two practical effects. Memory stays small, because only the images being used right now are in it, and the photos on disk stay untouched, so you can change the preparation without rewriting any file. The cost is that the decoding and resizing are repeated every time an image is requested, in every epoch.
True or false?
Creating an ImageFolder reads every photo into memory.
False. It only collects the path and class number of each file. A photo is opened when dataset[i] asks for it.
A greyscale photo in a class folder still arrives with three colour channels.
True. The default loader converts every image to RGB before the transform runs.
A random split that never changes
A classifier is judged on photos it never learned from, so the examples are divided into three sets. The training set is what the model learns from. The validation set is what you look at while making choices, such as how long to train. The test set is kept aside for the final measurement. Each of these numbers means something only if no photo is in two sets: a photo the model trained on is no test at all.
The split also has to be random. ImageFolder lists its examples class by class, so simply cutting the list into pieces would put all the dogs in the test set and none in training. The fix is to shuffle the positions first and then cut the shuffled list into consecutive blocks.
- 0 bird
- 1 bird
- 2 bird
- 3 cat
- 4 cat
- 5 cat
- 6 cat
- 7 cat
- 8 dog
- 9 dog
- 10 dog
- 11 dog
- 7 cat
- 2 bird
- 10 dog
- 0 bird
- 5 cat
- 11 dog
- 3 cat
- 8 dog
- 1 bird
- 9 dog
- 4 cat
- 6 cat
Each position appears exactly once in the shuffled list, so cutting it into blocks can never place a photo in two sets. That is what torch.utils.data.random_split does: it draws one random permutation of all positions and gives each set the next block of it.
The second requirement is that the split is random once. If every run shuffled differently, a photo that was in the test set yesterday could be in training today, and results from different runs would be measured on different photos. Random numbers in PyTorch come from a generator, and a generator started from the same seed produces the same sequence every time. Giving the split its own seeded generator makes it identical on every run:
import torch
from torch.utils.data import random_split
split_rng = torch.Generator().manual_seed(42)
train_set, val_set, test_set = random_split(
full, [800, 100, 100], generator=split_rng
)
print(len(train_set), len(val_set), len(test_set)) # 800 100 100The lengths must add up to the size of the dataset (here a dataset of 1,000 photos), or random_split raises an error. It also accepts fractions such as [0.8, 0.1, 0.1] and rounds them to whole counts itself; whole counts leave no doubt about the sizes.
The generator argument is what keeps the split fixed. Without it, the split draws from PyTorch's global generator, which in a fresh program is started from an unpredictable seed. Even after torch.manual_seed, the global generator is shared, so the split would depend on every random draw made before it. A dedicated generator ties the split to its own seed and nothing else.
The three results are Subset objects. A subset copies no images: it is a list of positions into the one underlying dataset, so all three sets read the same files through the same transform. And "identical on every run" holds on one machine with one library version: PyTorch does not promise the same random numbers across releases or platforms.
True or false?
Cutting the dataset into blocks without shuffling first gives a fair split.
False. ImageFolder lists the examples class by class, so unshuffled blocks would give the last sets only the last classes.
With the same seed, the same dataset and the same library version, random_split puts each photo in the same set on every run.
True. A generator started from the same seed draws the same permutation, so the same blocks come out.
Each Subset returned by random_split holds its own copy of the images.
False. A Subset is a list of positions into the shared dataset; the images are read from it when requested.
Counting the classes in each set
Real collections rarely hold the same number of photos for every class. Before training, count the examples of each class in each set. The count needs no image to be opened: the dataset's targets list holds the class number of every example, and a subset's indices say which examples it holds.
from collections import Counter
for name, subset in [("train", train_set), ("val", val_set), ("test", test_set)]:
counts = Counter(full.targets[i] for i in subset.indices)
print(name, {full.classes[c]: n for c, n in sorted(counts.items())})Suppose a collection of 1,000 photos holds 500 cats, 300 dogs and 200 birds, split as above. A random split keeps roughly the same proportions in every set, but small sets wander a little, which the counts show:
| Set | bird | cat | dog | Total |
|---|---|---|---|---|
| training | 160 | 404 | 236 | 800 |
| validation | 20 | 47 | 33 | 100 |
| test | 20 | 49 | 31 | 100 |
The counts decide what a useless model would score, which is the number any real result has to beat. A model that picks one of \( k \) classes at random is right one time in \( k \) on average, whatever the counts. A model that ignores the image and always answers the largest class is right as often as that class's share of the set:
Random guess among three classes
Always the largest class, on the test set above
So on this test set, a model with 45 % accuracy looks well above the 33 % of random guessing, yet a model that never looks at a photo reaches 49 %. When the classes are equal, the two baselines meet at \( 1/k \); the more unequal they are, the higher the largest class's share and the less a single accuracy number says on its own. Counting the sets also catches a broken split early, such as a class that is missing from the validation set.
True or false?
With five classes, 20 % accuracy is always the score of a model that ignores the image.
False. Random guessing gives 20 %, but always answering the largest class gives that class's share, which is higher when the classes are unequal.
Counting the examples per class in each set does not require opening any image.
True. The class numbers are already in the dataset's targets, and each subset lists the positions it holds.
Batches of images
A training loop does not feed the network one image at a time: it computes the loss on a batch of examples, takes one optimizer step and moves on, and one pass over every batch is an epoch. For images, a batch is a single tensor with an extra dimension in front, so 32 images of shape (3, 224, 224) become one tensor of shape (32, 3, 224, 224), next to a tensor of their 32 labels.
Putting tensors on top of each other along a new dimension is called stacking, and it only works when they all have the same shape. That is the reason the transform brings every photo to one size: a 640 by 480 photo and a 300 by 400 photo cannot be stacked, but two 224 by 224 crops can.
- label 2
- label 0
- label 1
- four examples, each image (3, 224, 224)
- images (4, 3, 224, 224)
- labels tensor([2, 0, 1, 2])
The DataLoader of torch.utils.data does this work. It asks the dataset for batch_size examples, stacks their images into one tensor and turns their class numbers into one tensor of whole numbers. Iterating over the loader yields one such pair per batch.
from torch.utils.data import DataLoader
shuffle_rng = torch.Generator().manual_seed(0)
train_loader = DataLoader(train_set, batch_size=32, shuffle=True, generator=shuffle_rng)
val_loader = DataLoader(val_set, batch_size=32)
images, labels = next(iter(train_loader))
print(images.shape) # torch.Size([32, 3, 224, 224])
print(labels.shape) # torch.Size([32])A few settings are worth knowing, because their defaults are not what people often expect:
batch_sizedefaults to 1, so set it yourself.shuffledefaults toFalse. For training,shuffle=Truedraws a new order of the training examples in every epoch, so the batches are not the same groups each time. A seededgeneratormakes that sequence of orders repeat from run to run. The validation and test loaders need no shuffling: the order does not change their accuracy.- When the set size is not a multiple of the batch size, the last batch is smaller. A validation set of 100 photos in batches of 32 gives three batches of 32 and one of 4.
drop_last=Truewould throw that last batch away, which you do not want when every example should be measured. num_workersdefaults to 0, which means the examples are loaded in the main process, one after another. That is the simplest setting and keeps a seeded run repeatable.
True or false?
A DataLoader shuffles the examples unless you tell it not to.
False. shuffle defaults to False; you switch it on for the training loader.
Without a transform that brings photos to one size, the default DataLoader cannot build a batch from photos of different sizes.
True. A batch is made by stacking the image tensors, and stacking needs every tensor to have the same shape.