How do you alter the size of a Pytorch Dataset?
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 datasets are sized by the __len__ method and indexed by __getitem__. To alter a dataset's size, you can use torch.utils.data.Subset to select specific indices, torch.utils.data.random_split to split into smaller datasets, or override __len__ in a custom wrapper. These approaches avoid copying data — they create views over the original dataset.
Using Subset (Select Specific Indices)
Subset takes a dataset and a list of indices, creating a smaller dataset without copying data:
Using random_split
random_split divides a dataset into non-overlapping subsets:
Custom Dataset Wrapper (Override len)
For more control, wrap the dataset and override __len__ and __getitem__:
Repeating / Expanding a Dataset
To make a dataset appear larger (useful for balancing classes or matching epoch sizes):
ConcatDataset (Combine Multiple Datasets)
Filtering by Condition
Select samples that match a condition (e.g., specific classes):
Or use Subset with filtered indices:
Using Samplers for Effective Size Control
Instead of modifying the dataset, use a sampler with the DataLoader:
Common Pitfalls
- Modifying
__len__without adjusting__getitem__: If__len__returns 100 but__getitem__can access indices beyond 100, the DataLoader works fine — but manual iteration withfor i in range(len(dataset))will miss samples. Keep them consistent. - Using
random_splitwithout a seed: Without aGeneratorseed,random_splitproduces different splits each run. For reproducible experiments, always passgenerator=torch.Generator().manual_seed(42). - Large index lists consuming memory: Storing 10 million indices in a Python list uses significant memory. For very large datasets, use a range-based approach or a sampler instead of materializing all indices.
- Forgetting that
Subsetdoes not copy data:Subsetholds a reference to the original dataset. If the original is modified or deleted, the subset breaks. Keep the original dataset alive for the subset's lifetime. - Shuffle conflicts with custom samplers:
DataLoader(shuffle=True)andsampler=...are mutually exclusive. When using aRandomSampleror other custom sampler, do not setshuffle=True.
Summary
- Use
Subset(dataset, indices)to select specific samples by index - Use
random_split(dataset, [sizes])to split into non-overlapping subsets - Override
__len__and__getitem__in a wrapper class for custom sizing logic - Use
ConcatDatasetto combine multiple datasets into one - Use
RandomSampler(num_samples=N)to limit samples per epoch without altering the dataset - Always set a random seed with
torch.Generator().manual_seed()for reproducible splits
Related reading
- How do you invert a tensor of boolean values in Pytorch?
- How does one create a distributed data loader with PyTorch's TorchMeta for meta-learning?
- How does one implement adversarial examples in pytorch?
- How does one use Pytorch cuda with an A100 GPU?
- How do you compute accuracy in a regression model, after rounding predictions to classes, in keras?
- How do you compute accuracy in a regression model, after rounding predictions to classes, in keras?
- How do you convert a time.struct_time object into a datetime object?
- How do you create a boolean mask for a tensor in Keras?
.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.