How do I load custom image based datasets into Pytorch for use with a CNN?
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
To train a CNN in PyTorch, you need a dataset object that can return one image-label pair at a time and a DataLoader that can batch those samples efficiently. The best implementation depends on how your files are organized: a simple folder-per-class layout can use ImageFolder, while CSV-driven or irregular datasets usually need a custom Dataset.
The important part is not only making the code run. You also need the transforms, labels, and tensor shapes to match the network you plan to train.
Use ImageFolder When the Layout Fits
If your dataset is organized by class directory, torchvision.datasets.ImageFolder already does most of the work:
Then you can load it like this:
If you control the dataset layout, this is often the simplest answer. It saves you from writing label-discovery code manually.
Write a Custom Dataset for CSV or Metadata-Based Labels
If image filenames and labels live in a CSV file, define your own Dataset:
This gives you full control over file paths, label mapping, filtering, and preprocessing.
Wrap It in a DataLoader
The dataset defines how to read one sample. The DataLoader handles batching, shuffling, and parallel loading:
That one-batch sanity check is worth doing before a long training run. It proves that the CNN will receive tensors with the expected shape and that labels are coming through correctly.
Choose Transforms Deliberately
CNN training depends heavily on preprocessing. At minimum, decide:
- target image size
- RGB versus grayscale handling
- normalization values
- which augmentations belong only in training
If you are using a pretrained model, its expected normalization matters. Training may still run without it, but transfer learning quality can drop noticeably.
Debug the Dataset Before Training
Most failed CNN runs are caused by dataset issues rather than architecture issues. Before training, inspect:
- '
class_to_idxor your custom label mapping' - one or two actual images after transform
- tensor shape and dtype
- class balance
This catches common mistakes such as corrupted images, wrong labels, grayscale images mixed into RGB pipelines, or augmentation accidentally applied to validation data.
Common Pitfalls
- Writing a custom dataset when
ImageFolderalready matches the directory structure. - Returning PIL images instead of tensors because transforms were omitted.
- Using labels in a format that does not match the chosen loss function.
- Applying training augmentations to validation or test data.
- Starting training before checking one batch of images and labels.
Summary
- Use
ImageFolderwhen the dataset is already organized by class folders. - Write a custom
Datasetwhen labels come from CSV files or custom metadata. - Use a
DataLoaderfor batching, shuffling, and background workers. - Treat transforms and normalization as part of the model pipeline.
- Inspect a sample batch before training to catch data issues early.
Related reading
- How do I make the initial state of an LSTM trainable in Keras?
- How do I pass a scalar via a TensorFlow feed dictionary
- How do I pass a scalar via a TensorFlow feed dictionary
- How do I plot a Keras/Tensorflow subclassing API model?
- How do I print the model summary in PyTorch?
- How do I print the model summary in PyTorch?
- How do I make a ragged batch in Tensorflow 2.0?
- How do I make a U-matrix?
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my 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.