Skip to main content

Implement linear regression trained with batch gradient descent in NumPy. For example, on data generated from y = 2x + 3 with a little noise, the weight should end close to 2 and the bias close to 3.

Coding rounds · Intermediate 2

Short answer

Start the weights and bias at zero. Each step: predict with X @ w + b, compute the error, and move against the gradient of the mean squared error, which is (2 / n) * X.T @ (pred - y) for the weights. Repeat until the loss stops falling. Each step costs O(n d).

Deeper answer

Clarify the shapes first: X is n by d, y has length n, w has length d and b is one number. Ask whether the features are scaled. Gradient descent is slow or unstable when columns have very different ranges, so standardise them first.

The loss is the mean of the squared error. Each step: err = X @ w + b - y, then the gradients are grad_w = (2 / n) * X.T @ err and grad_b = 2 * err.mean(). Update with w -= lr * grad_w and b -= lr * grad_b. Stop when the loss changes by less than a small tolerance.

Test against the closed-form answer from np.linalg.lstsq on the same data, and check the gradient against a numerical difference. The loss should fall on every step; if it grows, the learning rate is too large. Interviewers watch for a y of shape (n, 1) against a prediction of shape (n,), which broadcasts to an n by n array without an error, and for a missing bias term.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Regression

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.