How to split data into train and test sets using torchvision.datasets.Imagefolder?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
torchvision.datasets.ImageFolder loads image samples from a directory tree, but it does not split the dataset into training and test sets for you. The usual workflow is to build the dataset once, create a reproducible index split, and then expose those indices through Subset objects. The subtle part is transforms: train and test sets often need different transforms, so sharing one dataset object is not always enough.
Start with One ImageFolder
An ImageFolder expects this directory layout:
Each subdirectory name becomes a class label. To inspect the full dataset:
At this point, you have one dataset containing all samples.
Use random_split for a Simple Split
If train and test can share the same transform, random_split is the simplest solution.
This works well for many baseline projects and gives a reproducible split because the generator seed is fixed.
The Transform Problem
In real training pipelines, train and test usually need different transforms. Training often uses augmentation, while test uses only deterministic preprocessing.
That creates a problem: random_split returns subsets that still point at the same underlying dataset object. If that dataset has one transform, both subsets use it.
For example, this is often not what you want:
- training with random flips and crops
- test set also receiving random flips and crops accidentally
The fix is to separate the indices from the dataset object.
Use Two Dataset Instances with Shared Indices
Create two ImageFolder datasets that point at the same directory but use different transforms. Then apply the same split indices to both.
This gives reproducible sample membership while keeping train and test preprocessing separate.
Build DataLoaders After the Split
Once the subsets exist, wrap them in DataLoader objects.
Shuffle the training loader, not the test loader. That keeps evaluation deterministic and easier to debug.
Think About Class Balance
random_split does not guarantee stratification. If the dataset is imbalanced, the train and test subsets may end up with noticeably different class ratios. For many projects that is acceptable. For more sensitive evaluation, stratified splitting is better, but that usually requires building the split from the label list explicitly.
With ImageFolder, labels are available in dataset.targets, so class-aware splitting is possible if needed. The important point is that random splitting and balanced splitting are not the same thing.
Common Pitfalls
- Using
random_spliton one dataset object and then forgetting that both subsets share the same transform. - Applying training augmentation to the test set by accident.
- Forgetting to fix the random seed and then getting different splits on every run.
- Shuffling the test loader and making evaluation harder to compare.
- Assuming a random split is automatically stratified by class.
Summary
- '
ImageFolderloads the full dataset, but you still need to define the train-test split yourself.' - '
random_splitis fine when both subsets can share the same transform.' - When train and test need different transforms, use separate dataset instances with shared split indices.
- Build
DataLoaderobjects after creating the subsets. - If class balance matters, do not assume a random split is enough.
Related reading
- How to tell PyTorch to not use the GPU?
- How to test one single image in pytorch
- How to use both gpus in kaggle for training in pytorch?
- How to Use Class Weights with Focal \`Loss\` in PyTorch for Imbalanced dataset for MultiClass Classification
- How to split data on balanced training set and test set on sklearn
- How to split data raw text into test/train sets with scikit crossvalidation module?
- How to use torch.nn.parallel.DistributedDataParallel in this case?
- Hyperparameter optimization for Pytorch model
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.