PIXELBANKv9.1.0
Menu

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:
  • We split the training data into mini-batches of size batch_size = 2, resulting in two batches: (X = [1, 2], y = [2, 4]) and (X = [3, 4], y = [6, 8]).
  • For each batch, we compute the mean gradient of MSE loss. For the first batch, the predicted values are $w \cdot X + b = 0 \cdot [1, 2] + 0 = [0, 0]$, and the gradients are $\frac{\partial L}{\partial w} = -2 \cdot ([2, 4] - [0, 0]) \cdot [1, 2] = -2 \cdot [2, 4] \cdot [1, 2] = -2 \cdot [2 + 8] = -20$ and $\frac{\partial L}{\partial b} = -2 \cdot ([2, 4] - [0, 0]) = -2 \cdot [2 + 4] = -12$. We then update the parameters using these gradients and the learning rate $\alpha = 0.01$.
  • We repeat the process for the second batch, updating the parameters again.
  • After processing both batches, we obtain the final (w, b) values, which are then rounded to 4 decimal places, resulting in (0.5708, 0.1918).

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)
🔒

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

0/0
Run code to see test results.