3.3.4 · D3Deep Learning Frameworks

Worked examples — Datasets and DataLoaders

2,577 words12 min readBack to topic

This is the drill-yard for Datasets and DataLoaders. The parent note built the machinery: __len__, __getitem__, batching, collation, drop_last. Here we push that machinery through every corner case — the ugly divisions, the empty inputs, the ragged batches — so that when your own DataLoader misbehaves at 2 a.m., you have already seen the failure.

Before we count a single batch, let us re-earn the one symbol everything depends on.

We need one tool to answer that: integer division with a remainder. Not ordinary division — because you cannot train on "half a handful."

The drop_last idea shows up the moment your batches feed mini-batch gradient descent and again in the training loop, so it is worth beating flat.


The scenario matrix

Every question this topic can throw at you is one of these cells. The worked examples below are tagged with the cell(s) they cover.

Cell Situation What's tricky Example
A divides evenly by () floor = ceiling, no leftover Ex 1
B does not divide evenly, drop_last=False ragged last batch survives Ex 2
C Same, drop_last=True you lose samples every epoch Ex 3
D Degenerate: (batch bigger than dataset) exactly one batch, maybe short Ex 4
E Degenerate: batches, pure stochastic; and empty jar Ex 5
F Collation of ragged samples (variable length) must pad to a rectangle Ex 6
G Real-world word problem: epochs, steps, wall-clock chain the formulas together Ex 7
H Exam twist: shuffle + multi-epoch sample counting shuffling changes order not count Ex 8

The worked examples


Recall Quick self-test

Batches when ? ::: (last one size 4). Batches when ? ::: ; 4 samples dropped. gives how many batches? ::: — the loop never runs. Padded shape of a batch of 3 sequences (lengths 4,2,5, feature dim 3)? ::: . Does shuffle=True change how many times a sample is seen per epoch? ::: No — exactly once; only the order changes. Steps/epoch for ? ::: .

Next: plug these batches into the training loop, recall why batching stabilizes mini-batch gradient descent, and see how the same counting logic scales in distributed training and reuse pretrained pipelines in transfer learning.