v9.1.1
Menu

Mini-Batch SGD

hardPRONeural NetworksMachine Learning 2

Implement one epoch of mini-batch Stochastic Gradient Descent for a simple linear model y=w⋅x+by = w \cdot x + b.

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:

w=w−α⋅∂L∂w,b=b−α⋅∂L∂bw = w - \alpha \cdot \frac{\partial L}{\partial w}, \quad b = b - \alpha \cdot \frac{\partial L}{\partial b}

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

Input
X = [1, 2, 3, 4]
y = [2, 4, 6, 8]
w = 0, b = 0
lr = 0.01, batch_size = 2
Output
(0.5708, 0.1918)
Reasoning
  • Inputs: four points that lie exactly on y=2xy = 2x, starting parameters w=b=0w = b = 0, step size α=0.01\alpha = 0.01, and batches of m=2m = 2. Two updates: {(1,2),(2,4)}\{(1,2),(2,4)\}, then {(3,6),(4,8)}\{(3,6),(4,8)\}.
  • Gradients are averages over the batch: ∂L∂w=−2m∑xi(yi−y^i)\frac{\partial L}{\partial w} = -\frac{2}{m}\sum x_i (y_i - \hat{y}_i) and ∂L∂b=−2m∑(yi−y^i)\frac{\partial L}{\partial b} = -\frac{2}{m}\sum (y_i - \hat{y}_i), with y^i=wxi+b\hat{y}_i = w x_i + b.
  • Batch 1: y^=(0,0)\hat{y} = (0, 0), so ∂L∂w=−(1⋅2+2⋅4)=−10\frac{\partial L}{\partial w} = -(1 \cdot 2 + 2 \cdot 4) = -10 and ∂L∂b=−(2+4)=−6\frac{\partial L}{\partial b} = -(2 + 4) = -6. Then w=0.1w = 0.1, b=0.06b = 0.06.
  • Batch 2 uses the new parameters: y^=(0.36,0.46)\hat{y} = (0.36, 0.46), residuals (5.64,7.54)(5.64, 7.54), giving ∂L∂w=−(3⋅5.64+4⋅7.54)=−47.08\frac{\partial L}{\partial w} = -(3 \cdot 5.64 + 4 \cdot 7.54) = -47.08 and ∂L∂b=−13.18\frac{\partial L}{\partial b} = -13.18. Then w=0.1+0.4708=0.5708w = 0.1 + 0.4708 = 0.5708, b=0.06+0.1318=0.1918b = 0.06 + 0.1318 = 0.1918.
  • Notice that (0.5708, 0.1918) is still far from the true (2,0)(2, 0), yet one full-batch step on all four points would reach only (0.3,0.1)(0.3, 0.1): 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)

Learn this in

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.