Deterministic Mini-Batch Gradient Descent for a Line Fit
Arrays & HashingAuto-graded · 19 test casesLast updated
Fit a slope and intercept to 2D points by running deterministic mini-batch gradient descent on mean squared error, with exact batching, update order and edge-case rules.
Fit a Line with Mini-Batch Gradient Descent
You are given a list of points (x, y) and must fit the line y_hat = slope * x + intercept by minimizing mean squared error. Implement a fixed, deterministic training procedure so the result is exactly reproducible.
Loss and gradients
For a batch B of points, the loss is
L = (1 / |B|) * sum over (x, y) in B of (slope * x + intercept - y)^2
Its gradients with respect to the parameters are
dL/dslope = (2 / |B|) * sum of (slope * x + intercept - y) * xdL/dintercept = (2 / |B|) * sum of (slope * x + intercept - y)
Training procedure
- Start with
slope = 0.0andintercept = 0.0. - Training runs for
epochsepochs. - In each epoch, walk through the points in the given order, without shuffling, and split them into consecutive batches of
batch_sizepoints. If the number of points is not a multiple ofbatch_size, the last batch of the epoch is smaller. - For each batch, in order:
- Compute both gradients using the current
slopeandintercept(before changing either one). Average over the actual number of points in that batch. - Update both parameters:
param = param - learning_rate * gradient.
- Compute both gradients using the current
- Batches are processed in sequence, so each batch uses the parameters left by the previous batch.
Edge cases
- If
datais empty orepochs <= 0, return[0.0, 0.0]. - If
batch_size <= 0, treat it as1. - If
batch_sizeis at least the number of points, each epoch is a single full-batch step.
Task
Return the learned parameters as [slope, intercept] after all epochs finish. Floating-point results are compared against the expected values, so follow the procedure above exactly, including the order of operations per batch.
Constraints
datais a list of[x, y]pairs of real numbers; its length may be 0.learning_rateis a positive real number.epochsis an integer, possibly 0 or negative.batch_sizeis an integer, possibly 0 or negative.- No shuffling, no learning-rate decay, no early stopping.
Examples
Example 1
Input: train_line_minibatch([[1, 3], [2, 5], [3, 7]], 0.05, 100, 1)
Output: [1.9999883766494664, 1.000034870051602]
Example 2
Input: train_line_minibatch([[0, 2], [1, 4], [2, 6], [3, 8]], 0.05, 50, 2)
Output: [2.0146224786564066, 1.9642415082297286]
Example 3
Input: train_line_minibatch([[-2, 5], [-1, 3], [0, 1], [1, -1], [2, -3]], 0.02, 100, 5)
Output: [-1.999521576250686, 0.9831296806411504]
Hints
Hint 1
Write the gradient for one batch first: both gradients share the residual `slope * x + intercept - y`; the slope gradient multiplies it by `x`.
Hint 2
Compute both gradients from the old parameters before updating either one, and divide by the real length of the current batch, which matters for a shorter last batch.
Hint 3
Use two nested loops: epochs on the outside, and slices `data[start:start + batch_size]` stepping by `batch_size` on the inside. Handle the empty-data, non-positive-epochs and non-positive-batch-size cases up front.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is to simulate a precisely specified training loop.
For one batch, the residual of a point is r = slope * x + intercept - y. Applying the chain rule to the squared error gives 2r for the loss, then multiplies by x for the slope and by 1 for the intercept. Averaging over the batch gives:
dL/dslope = (2 / |B|) * sum(r * x)dL/dintercept = (2 / |B|) * sum(r)
The algorithm:
- Return
[0.0, 0.0]immediately if there is no data ornum_epochs <= 0. - Clamp
batch_sizeto at least 1. - Initialize both parameters to zero.
- For each epoch, step through the points in strides of
batch_size, slicing out each consecutive batch (the last one may be shorter). - For each batch, accumulate
sum(r * x)andsum(r)using the current parameters, scale by2 / len(batch), then update both parameters. Both gradients are fully computed before either parameter changes, so the update is simultaneous.
Why it is correct
Each step is gradient descent on the exact MSE of the current batch, using the true batch length so a short final batch is averaged correctly. Because the data order, batch boundaries, initialization and epoch count are all fixed, the sequence of parameter values is fully determined, so the output matches the expected values. With a sufficiently small learning rate the loss is a convex quadratic, so the parameters move toward the least-squares solution. With small batches they hover near it rather than converging exactly.
Complexity
- Time:
O(num_epochs * n), since each point is processed once per epoch with constant work. - Space:
O(batch_size)for the slice of the current batch (O(1)if indexed directly).
Reference solution
from typing import List
def train_line_minibatch(points: List[List[float]], lr: float, num_epochs: int, batch_size: int) -> List[float]:
if not points or num_epochs <= 0:
return [0.0, 0.0]
slope = 0.0
intercept = 0.0
n = len(points)
batch_size = max(1, batch_size)
for _ in range(num_epochs):
for start in range(0, n, batch_size):
batch = points[start:start + batch_size]
grad_slope = 0.0
grad_intercept = 0.0
for x, y in batch:
residual = slope * x + intercept - y
grad_slope += residual * x
grad_intercept += residual
scale = 2.0 / len(batch)
slope -= lr * scale * grad_slope
intercept -= lr * scale * grad_intercept
return [slope, intercept]