Dataset and DataLoader
Quick answer
A Dataset defines how examples are retrieved. A DataLoader creates batches, optionally shuffles sample order and can parallelize reading. Use a small map-style dataset and a seeded generator first, so batching and data alignment are inspectable. Static examples tested locally with PyTorch 2.10.0+cpu; ByteMind execution is unverified.
Inspect the last short batch
import torchfrom torch.utils.data import TensorDataset,DataLoaderds=TensorDataset(torch.arange(5),torch.arange(5)*10)print([(x.tolist(),y.tolist()) for x,y in DataLoader(ds,batch_size=2,shuffle=False)])Expected output: [([0, 1], [0, 10]), ([2, 3], [20, 30]), ([4], [40])]. The feature and label stay paired and the short final batch is retained.
How it works
Map-style datasets implement getitem and usually len. TensorDataset pairs tensors along their first dimension. DataLoader(dataset,batch_size=B,shuffle=True,generator=g,num_workers=0) gathers indexed samples into batches. Default collation stacks compatible tensors; variable-length inputs may need a custom collate_fn. drop_last=True discards a final short batch, while False retains it. Split by entity or time before making loaders when observations are dependent; shuffle only within training. A generator controls sampling and worker base seeds; stochastic transforms in other libraries may need separate worker seeding. IterableDataset has different indexing and sharding rules. Seeded runs are not a promise of identical results on every platform.
Seeded shuffle
import torchfrom torch.utils.data import DataLoaderdef order(seed): return [int(v) for b in DataLoader(torch.arange(7),batch_size=3,shuffle=True,generator=torch.Generator().manual_seed(seed),num_workers=0) for v in b]a,b=order(9),order(9)print(a==b,sorted(a)==list(range(7)))Expected output: True True. Independent loaders with the same seed reproduce the order on this baseline and cover all rows.
Common mistakes
Never shuffle features and targets independently. Avoid dropping validation rows or averaging batch means without weighting by sample count. Do not recreate a generator with the same seed inside each epoch unless repeated order is intentional.
Practice and next steps
Trace batches for five examples with batch_size=2; check that every ID occurs once when drop_last=False.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dataset and DataLoader — knowledge check
Apply dataset and dataloader to small examples and debugging scenarios.
What does TensorDataset preserve?
How many batches for 5 rows, batch size 2, drop_last=False?
Which setting avoids worker processes?
Where should group splitting occur?
Why weight batch means by size?