Mini-Batch SGD
Implement one epoch of mini-batch Stochastic Gradient Descent for a simple linear model .
Given training data, split it into mini-batches of size batch_size. For each batch, compute the mean gradient of MSE loss and update the parameters:
Process batches in order (first batch_size elements, then next batch_size, etc.). The last batch may be smaller.
Return the final (w, b) after one full epoch, rounded to 4 decimal places.
Example
X = [1, 2, 3, 4] y = [2, 4, 6, 8] w = 0, b = 0 lr = 0.01, batch_size = 2
(0.5708, 0.1918)
- Inputs: four points that lie exactly on , starting parameters , step size , and batches of . Two updates: , then .
- Gradients are averages over the batch: and , with .
- Batch 1: , so and . Then , .
- Batch 2 uses the new parameters: , residuals , giving and . Then , .
- Notice that
(0.5708, 0.1918)is still far from the true , yet one full-batch step on all four points would reach only : updating between batches lets batch 2 build on batch 1.
Constraints
- X: list of scalar inputs, y: list of targets
- w, b: initial scalar parameters
- learning_rate: float, batch_size: int >= 1
- Return (w, b) after one epoch, rounded to 4 decimal places
- MSE gradients: dw = -2/n * sum(x*(y-pred)), db = -2/n * sum(y-pred)