Linear Regression
📈 What is linear regression? Linear regression predicts a number as a weighted sum of the features plus a bias,
y ≈ X w + b. It picks the weights that make the squared errors on the training data as small as possible. It is the simplest model with a loss, a gradient and a closed-form answer, which is why it opens so many ML coding rounds.
Interviewers use it as a warm-up or as the first part of a longer problem, and the follow-ups (regularization, scaling, when to prefer gradient descent) are where it is graded.
The Prompt
Linear regression is short, so the interviewer looks at the details: a correct gradient, a bias that is handled deliberately, and a solver that doesn't fall over on real data.
"Implement linear regression. Fit it with gradient descent, then give me the closed-form solution, and add L2 regularization."
Clarifying Questions
You: What are the inputs? I'll assume X is an (n, d) float array and y is (n,), and I return weights
(d,) and a scalar bias.
Interviewer: Yes. Don't make me add a column of ones.
You: Which loss exactly? I'll use the mean squared error, and for ridge add l2 * ||w||^2. Should the bias be
regularized?
Interviewer: Mean squared error is fine. Don't regularize the bias.
You: For gradient descent, a fixed learning rate and number of steps, or a stopping rule?
Interviewer: Fixed is fine. Tell me how you would pick the learning rate.
You: Can features be on very different scales, or exactly collinear?
Interviewer: Assume real data, so yes to both.
What You'll Build
fit_gd(X, y, lr, epochs, l2) -> (w, b): vectorized gradient descent on the mean squared error plus ridge.fit_closed_form(X, y, l2) -> (w, b): the exact minimizer, solving a(d, d)system without a matrix inverse.mse(X, y, w, b) -> float: the loss, used in tests.