KatInterview

Batch Gradient Descent Linear Regression Session Simulator

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinggradient-descentlinear-regressionmse

Last 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].

  • X is a list of n rows, each a list of d numbers. y is a list of n targets.
  • Discard any previously trained model. Start with all weights equal to 0.0 and the bias equal to 0.0.
  • Perform exactly iterations gradient steps. In each step:
    1. Using the current parameters, compute the error e_i = prediction_i - y_i for every sample.
    2. Compute the gradients from those errors:
      • grad_w[j] = (2/n) * sum(e_i * X[i][j])
      • grad_b = (2/n) * sum(e_i)
    3. Update all parameters at once, after all gradients are computed:
      • weights[j] -= learning_rate * grad_w[j]
      • bias -= learning_rate * grad_b
  • Append None to 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 becomes weights = [] and bias = 0.0, no steps are run, and None is appended. A later predict on rows with zero features gives 0.0 per row.
  • iterations = 0: the model stays at all zeros, so every prediction is 0.0.
  • Length mismatch: if X and y have different lengths in a non-empty fit, raise ValueError.
  • Predict before any fit: raise ValueError.
  • Row width mismatch in predict: if a row's length differs from the number of trained weights, raise ValueError.
  • Unknown command name: raise ValueError.
  • A very large learning rate is not an error. Values may blow up to inf or nan, 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 X has the same number of features within a single fit call.
  • iterations is a non-negative integer.
  • learning_rate is 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.