Skip to content

← Production ML — Training Stack step 1 of 12

Medium End-to-End

Mini-Batch Training

Train a one-feature linear regression model for one pass through the data. Update its weight and bias after each consecutive mini-batch, so later batches use the parameters learned from earlier ones.

Your task

Implement mini_batch_train(x, y, w_init, b_init, lr, batch_size).

  • x and y have shape (N, 1), with N > 0.
  • w_init has shape (1, 1) and b_init has shape (1,).
  • These floating-point tensors share a dtype and device.
  • lr is a nonnegative learning rate; batch_size is a positive integer.

Return a dictionary containing the final "w" tensor of shape (1, 1), the final "b" tensor of shape (1,), and "final_loss" as a Python float. Preserve the parameter dtype and device. Leave all input tensors unchanged.

Process batches in order

Start with copies of w_init and b_init. Use rows 0 through batch_size-1 for the first batch, the next consecutive rows for the second, and so on. Do not shuffle, skip or repeat rows. The last batch may be smaller, and it still gets one update. If batch_size is at least N, there is just one full-data update.

For a batch xb, yb containing B actual rows, compute:

prediction = xb @ w + b
residual = yb - prediction
grad_w = (-2 / B) * (transpose(xb) @ residual)
grad_b = (-2 / B) * sum(residual over rows)
w_next = w - lr * grad_w
b_next = b - lr * grad_b

Both gradients use the same current w and b. Compute them before changing either parameter. Use B, not the configured batch_size or total N, in the mean-squared-error gradient. This matters for a short final batch.

For x=[1, 2], y=[2, 4], initial w=0, b=0, lr=0.1 and batch_size=2, the residuals are [2, 4]. The gradients are -10 and -6, giving w=1 and b=0.6. The updated predictions are [1.6, 2.6], so the final loss is (0.4**2 + 1.4**2) / 2 = 1.06.

Report loss after all updates

Using the final parameters, evaluate every original row again:

final_loss = mean((y - (x @ w + b))**2)

This is not the last batch's loss or the average of losses measured while parameters were changing. Perform exactly one epoch; do not run until the loss converges. With lr=0, the parameters stay unchanged, but still compute their loss over the full dataset.