Run one training epoch with full-batch, mini-batch or SGD updates

Why it matters Every training loop, from scikit-learn's SGDRegressor to a PyTorch DataLoader with drop_last=False, has this last-batch case.

Full-batch, mini-batch and SGD are the same loop with a different batch size. Getting the last, smaller batch right is the classic slip.

Write run_epoch(X, y, w, b, lr, batch_size) for linear regression. X is (n, d), y is (n,), w is (d,), b a float. Walk the rows in order in batches X[i:i + batch_size]. For each batch, with pred = Xb @ w + b and loss = mean over the batch of 0.5 * (pred - yb)^2, take one gradient step on w and b. The last batch may be smaller; average over its real size. Return (w, b, n_updates).

Signaturedef run_epoch(X, y, w, b, lr, batch_size)

Example

X = [[1], [2], [3]], y = [2, 4, 6], w = [0], b = 0, lr = 0.1, batch_size = 2 gives w = [1.76], b = 0.72 (rounded) after 2 updates.

Understand the idea

An epoch is one pass over the training data. You can take one big careful step after seeing everything (full batch), one quick noisy step per example (SGD), or something in between (mini-batch). It is like tasting soup: taste the whole pot, one spoon, or a ladle.

Tiny example: rows x = 1, 2, 3 with y = 2x, w = 0, lr = 0.1, batch 2. First batch: residuals are -2, -4, so grad_w = (1 * -2 + 2 * -4) / 2 = -5 and w becomes 0.5. The second batch has only one row, so its mean divides by 1, not 2.

Rule per batch of m rows: r = Xb w + b - yb, w -= lr * Xb^T r / m, b -= lr * sum(r) / m.

Large models train with mini-batches because they fit in GPU memory and the noise even helps generalisation.

Shapes and data flow

X (n, d), batch Xb (m, d) with m <= batch_size, grad_w (d,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplerun_epoch([[1.0], [2.0], [3.0]], [2.0, 4.0, 6.0], [0.0], 0.0, 0.1, 2)
  • Sample 2: full batchrun_epoch([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], [1.0, 2.0, 3.0], [0.0, 0.0], 0.0, 0.5, 10)
  • Test 3: sgdrun_epoch([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], [1.0, 2.0, 3.0], [0.0, 0.0], 0.0, 0.5, 1)
  • Test 4: ragged last batchrun_epoch([[1.0], [-1.0], [2.0], [0.5], [3.0]], [1.0, 0.0, 2.0, 1.0, -1.0], [0.2], 0.1, 0.05, 3)