270. 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 1
Input: X = [[1], [2], [3]], y = [2, 4, 6], w = [0], b = 0, lr = 0.1, batch_size = 2
Output: w = [1.76], b = 0.72 (rounded) after 2 updates
Example 2
Input: X = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], y = [1.0, 2.0, 3.0], w = [0.0, 0.0], b = 0.0, lr = 0.5, batch_size = 10
Output: ([0.666667, 0.833333], 1.0, 1)
Example 3
Input: X = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], y = [1.0, 2.0, 3.0], w = [0.0, 0.0], b = 0.0, lr = 0.5, batch_size = 1
Output: ([0.75, 1.0], 1.5, 3)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Divide each batch gradient by len(batch), not by batch_size.
Hint 2
Use range(0, n, batch_size).
Hint 3
Compute the residual once per batch.
Hint 4
Use the batch's real length in the mean.
Common mistakes
- Dividing by
batch_sizefor a short last batch. - Computing all gradients with the old w (that is full batch, not mini-batch).
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.
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,)
Topics
Companies3
- Amazon the topic appears in interview reports Coding Algorithms And Data Structures — Tech Interview Concept | PracHub
- Google the topic appears in interview reports Google Interview Prep (Deep-ML)
- Microsoft a candidate reported this question Microsoft Machine Learning Engineer Interview Questions | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.