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).
def 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,)