KatInterview

Build Linear Regression and MSE Loss Without Libraries

Machine LearningModel answer
MediumModel answerMachine Learninggradient-descentloss-functionsfrom-scratch

Last updated

Code mean squared error from scratch, then build a linear regression class with fit and predict methods using gradient descent.

Your task is to build a linear regression implementation without using any prebuilt regression or loss classes from machine learning libraries. You may use NumPy for array operations.

Part 1: Mean Squared Error

Create a function that computes the mean squared error between true values and predictions:

$$\text{MSE} = \frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2$$

Then derive and state the gradient of this loss with respect to the predictions $\hat{y}$.

Your function should:

  • Accept two arrays of equal length
  • Return a scalar loss value
  • Handle edge cases like empty inputs or extreme values appropriately

Part 2: Linear Regression Class

Build a LinearRegression class with these methods:

  • fit(X, y): Train the model on feature matrix X (shape (n_samples, n_features)) and target vector y (shape (n_samples,))
  • predict(X): Return predictions for new data

The model should learn both weights and a bias term by minimizing the MSE loss you defined in Part 1.

Implementation Requirements

  • Use gradient descent to optimize the parameters
  • Include input shape validation
  • Discuss how you would verify correctness
  • State the computational complexity per training iteration

Questions to Address

  • How do you compute gradients with respect to weights and bias?
  • What learning rate and stopping criteria will you use?
  • Should features be normalized, and if so, how?
  • When would you prefer a closed-form solution over gradient descent?

Hints

Hint 1

The MSE gradient with respect to predictions is (2/n)(ŷ - y). Use the chain rule to get weight and bias gradients.

Hint 2

Feature scaling to zero mean and unit variance stabilizes gradient descent and allows a single learning rate to work across features.

Hint 3

Test on data where you know the answer: a perfect linear relationship, or compare against the closed-form solution W = (X^T X)^(-1) X^T y.