Load csv and Image dataset in pytorch
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
PyTorch loads data through the Dataset and DataLoader classes. For CSV data, you create a custom Dataset that reads a CSV file (typically with pandas) and returns tensors. For image datasets, use torchvision.datasets.ImageFolder for directory-structured data or a custom Dataset that reads image paths from a CSV and loads them with PIL. The DataLoader then wraps any Dataset to provide batching, shuffling, and parallel data loading. This two-layer design separates data access logic from training loop mechanics.
Loading a CSV Dataset
The __getitem__ method returns a single sample as tensors. DataLoader collates individual samples into batches automatically.
Loading Images from a Directory
ImageFolder automatically assigns class labels based on subdirectory names. The transform pipeline handles resizing, tensor conversion, and normalization.
Loading Images Referenced by a CSV
This pattern is common when labels are in a CSV file separate from the image directory, or when you need metadata beyond simple class folders.
Combined CSV Features + Images
For multi-modal models, a single Dataset can return multiple inputs. The DataLoader handles batching all of them together.
DataLoader Configuration
Common Pitfalls
- Forgetting
__len__or__getitem__:DataLoaderrequires both methods on the dataset. Missing either raisesTypeError.__len__returns the dataset size,__getitem__returns a single sample by index. - Not converting to tensors in
__getitem__: Returning raw NumPy arrays or Python lists works but is slower. PyTorch's default collate function converts them to tensors, but explicit conversion in__getitem__catches type errors earlier and is more efficient. - Using
num_workers > 0on Windows withoutif __name__ == '__main__': Windows usesspawnfor multiprocessing, which re-imports the module. Without the__main__guard, workers crash with pickle errors. Always wrapDataLoaderiteration inif __name__ == '__main__'on Windows. - Loading all images into memory at
__init__: For large image datasets, loading all images during initialization causes out-of-memory errors. Load images lazily in__getitem__— each image is loaded on demand and garbage-collected after use. - Not normalizing image tensors:
ToTensor()scales pixel values to [0, 1], but pretrained models (ResNet, VGG) expect ImageNet normalization (mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]). Missing this step causes poor model performance with pretrained weights.
Summary
- Create a custom
Datasetsubclass with__len__and__getitem__for CSV data - Use
torchvision.datasets.ImageFolderfor directory-structured image datasets - For CSV-referenced images, build a custom
Datasetthat reads paths from the CSV and loads images in__getitem__ - Wrap any
DatasetwithDataLoaderfor batching, shuffling, and parallel loading - Use
pin_memory=Trueandnum_workers > 0for faster GPU training - Apply
transforms.Composefor image preprocessing (resize, normalize, augment)
Related reading
- LSTM time sequence generation using PyTorch
- Meaning of parameters in torch.nn.conv2d
- ''module'' object has no attribute ''SummaryWriter''
- Neither PyTorch nor TensorFlow 2.0 have been found.Models won''t be available and only tokenizers, configuration and file/data utilities can be used
- Load image files in a directory as dataset for training in Tensorflow
- Load model with ML.NET saved with keras
- onnxruntime inference is way slower than pytorch on GPU
- OSError Error no file named ''pytorch_model.bin'', ''tf_model.h5'', ''model.ckpt.index''
.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.