InterviewPrepKit

Home / Coding / Machine Learning Coding / Linear Models / Linear Regression (Normal Equation)

Linear Regression (Normal Equation)

medium 00:00
Solving tips
  • Prepend a column of ones to X so the intercept is learned as just another weight — the algebra stays a single matrix equation.
  • Solve the linear system (X^T X) w = X^T y directly; np.linalg.solve is more accurate and faster than forming np.linalg.inv.
  • Keep track of shapes: X is (n, d), the augmented matrix is (n, d+1), and the returned weight vector is (d+1,).

Fit an ordinary least squares linear regression using the closed-form normal equation, without calling sklearn or np.linalg.lstsq. Interviewers use this to check that you can go from the OLS objective to working matrix code and that you know the numerically sound way to solve the system.

Definition

For a feature matrix X and targets y, OLS minimizes the squared residuals ||X_aug w - y||^2, where X_aug is X with a leading column of ones so the model has an intercept. The minimizer satisfies the normal equation:

(X_aug^T X_aug) w = X_aug^T y
w = (X_aug^T X_aug)^-1 X_aug^T y

Task

Complete fit_linear_regression(X, y) so it returns the weight vector w of shape (d + 1,). Prepend a column of ones to X to model the bias, form the normal equation, and solve it with np.linalg.solve rather than an explicit matrix inverse. w[0] is the intercept and w[1:] are the coefficients for the columns of X.

Example

X = np.array([[1.0], [2.0], [3.0], [4.0]])
y = np.array([3.0, 5.0, 7.0, 9.0])   # exactly y = 2*x + 1
fit_linear_regression(X, y)          # -> array([1., 2.])

The data lies on the line y = 2x + 1, so the fit recovers bias 1.0 and slope 2.0.

Constraints

  • X has shape (n, d) with n >= d + 1; y has shape (n,).
  • Assume X_aug^T X_aug is invertible (full column rank).
  • Use vectorized NumPy and np.linalg.solve; do not form np.linalg.inv.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug