101. Fit linear regression in one line with the normal equation
Linear regression finds weights w and a bias b so that X @ w + b is as close as possible to y in squared error. For small problems you can solve it exactly instead of iterating.
Write fit_linear(X, y) that returns (w, b). Add a column of ones to X for the bias and solve (Xb.T Xb) theta = Xb.T y.
Use np.linalg.solve, not an explicit inverse.
def fit_linear(X, y)Example 1
Input: X = [[0.0], [1.0], [2.0]], y = [1.0, 3.0, 5.0]
Output: ([2.0], 1)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Xb = np.hstack([X, ones]). theta = solve(Xb.T @ Xb, Xb.T @ y).
Hint 2
The last entry of theta is b.
Common mistakes
- The column of ones lets the model learn an intercept; without it (the buggy version) the line is forced through the origin.
Understand the idea
Linear regression looks for the weights that make predictions as close as possible to the targets in squared error. For small problems you can solve for them exactly with one linear system, the normal equation, instead of training step by step. Add a column of ones so the model can learn an intercept; without it the line must pass through the origin.
x = [0, 1, 2], y = [1, 3, 5]. Xb has rows [0, 1], [1, 1], [2, 1]. Xb^T Xb = [[5, 3], [3, 3]] and Xb^T y = [13, 9]. Solve 5w + 3b = 13 and 3w + 3b = 9: subtracting gives 2w = 4, so w = 2 and b = 1. That fits y = 2x + 1 exactly.
theta = solve(Xb^T Xb, Xb^T y); the last entry is b
Use a solver rather than an explicit inverse, which is less stable. Quick baselines and many statistics tools use this closed form.
Topics
Companies2
- Amazon a candidate reported this question Amazon AI Research Scientist interview experience (February 2025)
- Meta a candidate reported this question Machine Learning interview questions, page 10 (KatKat)
From public interview reports and guides. Not affiliated with or endorsed by these companies.