Deep learning and neural networksLoading progress…

Data and minibatches

Translate an inspected NumPy model into tensors, modules, automatic differentiation and a clear training loop.

Feeding the model in batches

You rarely train on the whole dataset in one step. A DataLoader walks the dataset and hands you batches: tensors whose first axis is the batch axis. Each row of a batch is one independent example, and the same weights are applied to every row.

  • batch_size sets how many examples per step. If the dataset size is not a multiple, the last batch is smaller.
  • drop_last=True discards that smaller batch.
  • shuffle=True visits the examples in a new random order each epoch. Features and targets are shuffled together, so they stay paired.
batch_size4
batch 1 (4)sample 0sample 1sample 2sample 3
batch 2 (4)sample 4sample 5sample 6sample 7
batch 3 (2)sample 8sample 9
dataset of 10 samples (indices 0..9) loader = DataLoader(ds, batch_size=4, shuffle=False, drop_last=False) len(loader) = 3 batch sizes: 4, 4, 2

The shuffled order here comes from a small generator of our own. Real PyTorch draws a different permutation, but the rules are the same: every sample once per epoch, X and y shuffled together.

Ten samples. Change the settings and see exactly which samples fall in which batch.

Predict first. What does the batch axis of a tensor represent?

from torch.utils.data import DataLoader, TensorDataset
loader = DataLoader(TensorDataset(X, y), batch_size=4, shuffle=True, drop_last=False)
for xb, yb in loader:          # xb: (4, features), yb: (4,) ... the last batch may be smaller
    ...
Chapter context

PyTorch provides tensor operations and differentiation infrastructure. The framework removes bookkeeping, but it does not remove the need to understand dimensions, parameter ownership, device placement and evaluation behavior.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

For a batch X of shape (B,d), a dense output with h features has shape (B,h). torch.nn.Linear stores weight with shape (h,d) and computes X times weight-transpose plus bias. Parameter count is d*h+h. PyTorch execution belongs in a linked notebook or supported runtime; the chapter does not assume browser PyTorch.

Worked example

A batch has shape (2,4). A Linear(4,3) layer stores a (3,4) weight and a length-three bias. Its output is (2,3). The parameter count is 4×3+3=15. This differs from the batch's element count: model parameters are shared across both examples.

Reference code

The following example uses the Python standard library and does not call a remote service.

batch, inputs, outputs = 2,4,3
weight_shape = (outputs,inputs)
output_shape = (batch,outputs)
assert weight_shape == (3,4)
assert output_shape == (2,3)
assert inputs*outputs+outputs == 15

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

eval mode and no_grad are independent. Model parameters do not multiply with batch size. A tensor detached for logging must not replace the tensor used to compute the training loss.