Batch Gradient Descent Linear Regression Session Simulator
Arrays & HashingAuto-graded · 23 test casesLast updated
Simulate a fit/predict command sequence for a linear model trained with batch gradient descent on mean squared error, using plain Python lists.
Linear Model Trainer Session
You are building a small linear regression engine that learns one weight per feature plus a single bias term. It is trained with batch gradient descent on the mean squared error. The engine is driven by a list of commands, so one call replays an entire session.
Write run_gd_regression_session(commands, payloads). It processes the commands in order and returns one result per command.
Model and loss
For a sample row x with d features, the prediction is bias + sum(x[j] * weights[j]).
For n training samples the loss is:
J = (1/n) * sum((prediction_i - target_i)^2)
Commands
commands[i] is paired with payloads[i].
"fit": the payload is [X, y, learning_rate, iterations].
Xis a list ofnrows, each a list ofdnumbers.yis a list ofntargets.- Discard any previously trained model. Start with all weights equal to
0.0and the bias equal to0.0. - Perform exactly
iterationsgradient steps. In each step:- Using the current parameters, compute the error
e_i = prediction_i - y_ifor every sample. - Compute the gradients from those errors:
grad_w[j] = (2/n) * sum(e_i * X[i][j])grad_b = (2/n) * sum(e_i)
- Update all parameters at once, after all gradients are computed:
weights[j] -= learning_rate * grad_w[j]bias -= learning_rate * grad_b
- Using the current parameters, compute the error
- Append
Noneto the results.
"predict": the payload is [X], where X is a list of rows.
- Append a list with the model's prediction for each row, in order.
Special cases
- Empty training set (
n = 0): the model becomesweights = []andbias = 0.0, no steps are run, andNoneis appended. A laterpredicton rows with zero features gives0.0per row. iterations = 0: the model stays at all zeros, so every prediction is0.0.- Length mismatch: if
Xandyhave different lengths in a non-emptyfit, raiseValueError. - Predict before any fit: raise
ValueError. - Row width mismatch in
predict: if a row's length differs from the number of trained weights, raiseValueError. - Unknown command name: raise
ValueError. - A very large learning rate is not an error. Values may blow up to
infornan, and no exception is raised.
Use ordinary Python floats and follow the formulas above. Outputs are checked against the exact gradient-descent trajectory, so do not use momentum, early stopping, feature scaling, or a different initialisation.
Constraints
len(commands) == len(payloads)- Each row of
Xhas the same number of features within a singlefitcall. iterationsis a non-negative integer.learning_rateis a real number.- Values are small enough that a direct simulation runs quickly.
Examples
Example 1
Input: run_gd_regression_session(['fit', 'predict'], [[[[1], [2], [3]], [2, 4, 6], 0.01, 1000], [[[4]]]])
Output: [None, [7.949548255475097]]
Example 2
Input: run_gd_regression_session(['fit', 'predict'], [[[[1, 0], [0, 1], [1, 1]], [3, -2, 1], 0.05, 2000], [[[2, -1], [0, 3]]]])
Output: [None, [8.000001079845122, -6.000004134108352]]
Example 3
Input: run_gd_regression_session(['fit', 'predict', 'predict'], [[[[0], [1], [2], [3]], [1, 3, 5, 7], 0.1, 500], [[[-1], [4]]], [[[10]]]])
Output: [None, [-1.000000000000004, 9.000000000000004], [21.00000000000001]]
Hints
Hint 1
Write down the gradient first: with errors e = prediction - target, the weight gradient is (2/n) * X^T e and the bias gradient is (2/n) * sum(e).
Hint 2
Compute all errors from the current parameters before changing anything, then apply the weight and bias updates together. Updating the weights first and then computing the bias gradient from the new weights gives a different trajectory.
Hint 3
Reset the model at the start of every fit, keep it between commands so predict can use it, and handle the edge cases: empty data, mismatched lengths, predicting before fitting, wrong row width, and unknown commands.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is to simulate a small stateful model. The session keeps the current weights and bias, and each command either replaces them (fit) or reads them (predict).
Training step
For n samples, let e = X·w + b - y be the error vector. The loss (1/n) * sum(e_i^2) has these gradients:
dJ/dw_j = (2/n) * sum(e_i * X[i][j])dJ/db = (2/n) * sum(e_i)
Each iteration does three things:
- Compute all errors with the current parameters.
- Accumulate the weight and bias gradients from those errors.
- Update every parameter at once by subtracting
learning_rate * gradient.
Computing every error before changing any parameter makes each iteration a true gradient step at a single point (w, b). A common bug is to update the weights first and then compute the bias gradient from the updated weights. That gives a different trajectory and different outputs.
Why it is correct
- The gradient formulas follow directly from the chain rule applied to the squared error.
- The loss is convex, so with a sufficiently small learning rate the iterates approach the global minimum. In the first sample case, training on
y = 2xfor 1000 steps gets close tow = 2, b = 0, so predicting at 4 gives roughly 8. - Each
fitre-initialises the parameters to zero, so repeated fits are independent and deterministic. - The edge cases follow the rules in the statement:
- Empty data gives an empty weight list and zero bias.
- Zero iterations leaves the model at zeros.
- Invalid usage raises
ValueError. - A divergent learning rate simply overflows to
infornanwithout an exception.
Complexity
Let d be the number of features.
fit: time O(iterations * n * d), space O(n + d) for the errors and gradients.predictonmrows: time O(m * d), space O(m) for the output.
Practical notes
With NumPy, each step collapses to three vectorised lines:
err = X @ w + b - y
w -= lr * (2 / n) * (X.T @ err)
b -= lr * (2 / n) * err.sum()
If features have very different scales, the largest one forces a tiny stable learning rate. Standardising columns fixes this, but it is not part of this problem.
Reference solution
from typing import List
def run_gd_regression_session(commands: List[str], payloads: List[List]) -> List:
weights = None
bias = 0.0
results = []
for command, args in zip(commands, payloads):
if command == "fit":
X, y, learning_rate, iterations = args
n_samples = len(X)
if n_samples == 0:
weights = []
bias = 0.0
results.append(None)
continue
n_features = len(X[0])
weights = [0.0] * n_features
bias = 0.0
if n_samples != len(y):
raise ValueError("X and y must have the same number of samples")
for _ in range(iterations):
errors = []
for row, target in zip(X, y):
prediction = bias + sum(row[j] * weights[j] for j in range(n_features))
errors.append(prediction - target)
scale = 2.0 / n_samples
weight_gradients = [0.0] * n_features
bias_gradient = 0.0
for i, error in enumerate(errors):
bias_gradient += error
for j in range(n_features):
weight_gradients[j] += error * X[i][j]
for j in range(n_features):
weights[j] -= learning_rate * scale * weight_gradients[j]
bias -= learning_rate * scale * bias_gradient
results.append(None)
elif command == "predict":
X = args[0]
if weights is None:
raise ValueError("fit must be called before predict")
predictions = []
for row in X:
if len(row) != len(weights):
raise ValueError("feature count mismatch")
prediction = bias + sum(row[j] * weights[j] for j in range(len(weights)))
predictions.append(prediction)
results.append(predictions)
else:
raise ValueError("unknown operation")
return results